@cyberart-io/engine 0.0.3 → 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/dist/index.js CHANGED
@@ -5,4 +5,4 @@
5
5
  * Not an OSI open-source license.
6
6
  */
7
7
 
8
- var Mn=(e,t)=>()=>(e&&(t=e(e=0)),t);var $n={};function Kn(e,t){let n=e.indexOf(Kt);if(n===-1)return null;let r=n+Kt.length,a=`const __cyberSkip=new Set(${JSON.stringify(t)});const __cyberOrig=registerProcessor;registerProcessor=(n,p)=>__cyberSkip.has(n)?undefined:__cyberOrig(n,p);`;return e.slice(0,r)+a+e.slice(r)}var nt,je,Hn,ke,Kt,$t=Mn(()=>{"use strict";nt=/AudioWorkletProcessor with name:\s*["'`][^"'`]+["'`]\s+is already registered/i,je="__cyberartWorkletPatchApplied";typeof window<"u"&&!window[je]&&(window.addEventListener("error",e=>{let t=e?.message??"";nt.test(t)&&(e.preventDefault(),e.stopImmediatePropagation())},!0),window.addEventListener("unhandledrejection",e=>{let t=e?.reason,n=typeof t=="string"?t:t?.message??"";nt.test(n)&&e.preventDefault()}),window[je]=!0);Hn=!1,ke=(...e)=>{Hn&&console.log("[workletPatch]",...e)},Kt="((AudioWorkletProcessor,registerProcessor)=>{";if(typeof AudioWorklet<"u"&&!AudioWorklet.prototype[je]){let e=new WeakMap,t=/registerProcessor\s*\(\s*['"`]([^'"`]+)['"`]/g,n=AudioWorklet.prototype.addModule,r=0;AudioWorklet.prototype.addModule=async function(a,s){let u=++r,f=e.get(this);f||(f=new Set,e.set(this,f)),ke(`#${u} addModule`,{url:a.slice(0,64),isBlob:a.startsWith("blob:"),knownBefore:[...f]});let v=a,m=null;if(a.startsWith("blob:")){let h=null;try{h=await(await fetch(a)).text()}catch(S){ke(`#${u} blob fetch failed`,S)}if(h!==null){let S=new Set;for(let E of h.matchAll(t))S.add(E[1]);if(S.size>0){let E=[...S].filter(l=>f.has(l)),N=[...S].filter(l=>!f.has(l));if(E.length>0&&N.length===0){ke(`#${u} short-circuit \u2014 all processors already registered`,E);return}if(E.length>0&&N.length>0){let l=Kn(h,E);if(l!==null){let c=new Blob([l],{type:"application/javascript"});m=URL.createObjectURL(c),v=m,ke(`#${u} rewrote blob; skipping`,E,"allowing",N)}else ke(`#${u} blob rewrite failed; passing original through`)}N.forEach(l=>f.add(l))}}}return n.call(this,v,s).then(()=>{m&&URL.revokeObjectURL(m)},h=>{m&&URL.revokeObjectURL(m);let S=(h&&h.message)??"";if(!(nt.test(S)||/already registered/i.test(S)))throw h})},AudioWorklet.prototype[je]=!0}});var xt=()=>{let e=["ms","moz","webkit","o"];for(let t=0;t<e.length&&!window.requestAnimationFrame;++t)window.requestAnimationFrame=window[e[t]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[e[t]+"CancelAnimationFrame"]||window[e[t]+"CancelRequestAnimationFrame"]},j=window.devicePixelRatio||1,de=/Headless/i.test(navigator.userAgent),pi=/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)||/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform);function Rt(){return Math.min(window.innerWidth,window.innerHeight)}var _e="data-cyberart-canvas",ue=class{constructor(t,n,r=1,i={}){this.width=t,this.height=n;let a=i.container,s=i.adoptFromDocument??!a,u=a?a.querySelector(`canvas[${_e}]`)??a.querySelector("canvas"):null;if(u)this.canvas=u,this.adopted=!0;else if(s){let f=document.getElementById("canvas")??document.querySelector("canvas");f?(this.canvas=f,this.adopted=!0):(this.canvas=document.createElement("canvas"),this.canvas.setAttribute("id","canvas"),this.adopted=!1)}else this.canvas=document.createElement("canvas"),this.adopted=!1;this.canvas.hasAttribute(_e)||this.canvas.setAttribute(_e,""),this.canvas.style.display="block",this.canvas.style.margin="auto",this.ctx=this.canvas.getContext("2d",{colorSpace:"display-p3",alpha:!1}),this.ctx.globalAlpha=r,this.ctx.imageSmoothingEnabled=!1,this.setSize(t,n)}setSize(t,n){this.width=t,this.height=n,this.canvas.width=t,this.canvas.height=n,this.canvas.style.width=`${t/j}px`,this.canvas.style.height=`${n/j}px`,this.imageData=this.ctx.createImageData(t,n),this.ctx.putImageData(this.imageData,0,0)}_blank(t=1){let n=t?Math.max(t,.03):1;this.ctx.fillStyle=`rgba(0,0,0,${n})`,this.ctx.fillRect(0,0,this.width,this.height)}clearAll(){this.ctx.save(),this.ctx.globalAlpha=1,this._blank(),this.ctx.restore()}};function Dt(e,t){let n=e/t,r,i;return n>1?(r=e,i=~~(e/n)):(i=t,r=~~(t*n)),{width:r,height:i,iWidth:1/r,iHeight:1/i,area:r*i,largeDim:Math.max(r,i),smallDim:Math.min(r,i),aspectRatio:n}}function It(e,t=window.innerWidth,n=window.innerHeight){let r=Rt(),i,a;return n<t?e>1?t>=r*e?(i=r*e,a=r):(i=t,a=i/e):(i=r*e,a=r):e>1?(i=r,a=r/e):n<r/e?(a=n,i=a*e):(i=r,a=r/e),[i,a]}var Oe=class{constructor(t=!1,n=!0){this.debugMode=t,this.actionMap={},this.listening=n,this.checkKeypress=this.checkKeypress.bind(this),this.registerAction=this.registerAction.bind(this),this.listening&&window.addEventListener("keydown",this.checkKeypress,!1)}checkKeypress({key:t}){this.debugMode&&console.log(`Pressed ${t}`),t in this.actionMap&&this.actionMap[t]()}inject(t){this.checkKeypress({key:t})}registerAction(t,n,r=!1){if(t.length!==1)throw new Error(`Only single-character actions may be registered. Cannot register: ${t}`);if(t in this.actionMap&&!r)throw new Error(`Action already exists for code: ${t}`);this.actionMap[t]=n}destroy(){this.listening&&window.removeEventListener("keydown",this.checkKeypress,!1),this.actionMap={}}},Mt=Oe;var Le=class{constructor(t,n={}){this.x=-1;this.y=-1;this.isDown=!1;this.clicks=[];this.canvas=t,this.listening=n.listen!==!1,this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.listening&&(t.addEventListener("pointerdown",this.onPointerDown),t.addEventListener("pointermove",this.onPointerMove),t.addEventListener("pointerup",this.onPointerUp))}toCanvasCoords(t){let n=this.canvas.getBoundingClientRect();return{x:(t.clientX-n.left)*(this.canvas.width/n.width),y:(t.clientY-n.top)*(this.canvas.height/n.height)}}onPointerDown(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r,this.isDown=!0,this.clicks.push({x:n,y:r})}onPointerMove(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r}onPointerUp(t){let{x:n,y:r}=this.toCanvasCoords(t);this.x=n,this.y=r,this.isDown=!1}hasClick(){return this.clicks.length>0}consumeClick(){return this.clicks.shift()??null}inject(t,n,r){this.x=n,this.y=r,t==="down"?(this.isDown=!0,this.clicks.push({x:n,y:r})):t==="up"&&(this.isDown=!1)}destroy(){this.listening&&(this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp))}},Ft=Le;function ce(){return{now:()=>performance.now()}}function Ve(e=0){let t=e;return{now:()=>t,set(n){t=n},advance(n){t+=n}}}var _t=(e,t,n,r)=>({now:e,startTime:t,elapsedSinceStart:e-t,deltaSinceLastUpdate:n===null?0:e-n,deltaSinceLastRender:r===null?0:e-r}),Ne=class{constructor(t,n,r,i,a,s={}){this.startTime=0;this.lastUpdateAt=null;this.lastRenderAt=null;this.clockOffsetMs=0;this.pauseStartedAt=null;this.renderAnimation=this.renderAnimation.bind(this),this.dimensionContext=Dt(t,n),this.R=r,this.gameManager=s.gameManager,this.hostChannel=s.hostChannel,this.clock=s.clock??ce(),this.canvas=new ue(this.dimensionContext.width,this.dimensionContext.height,1,s.canvasMount),this.drawingContext=this.canvas.ctx,this.keyboardManager=new Mt(!1,s.captureKeyboard??!0),this.pointerManager=new Ft(this.canvas.canvas,{listen:s.listenToPointer!==!1}),this.animationCart=a;let u=s.customState;this.featureState=a.getDefaultFeatureState?.(this.R,this.dimensionContext,i,this.keyboardManager,u,this.pointerManager,this.gameManager,this.hostChannel),this.cartState=a.getDefaultState(this.R,this.dimensionContext,i,this.keyboardManager,u,this.pointerManager,this.gameManager,this.featureState,this.hostChannel),this.startTime=this.clock.now(),this.canvas.clearAll()}captureFramebuffer(){let t=this.canvas.imageData,n=new ImageData(t.width,t.height);return n.data.set(t.data),n}restoreFramebuffer(t){let n=this.canvas.imageData;return n.width!==t.width||n.height!==t.height||n.data.length!==t.data.length?!1:(n.data.set(t.data),this.drawingContext.putImageData(n,0,0),!0)}setPaused(t){let n=this.clock.now();if(t){this.pauseStartedAt===null&&(this.pauseStartedAt=n);return}this.pauseStartedAt!==null&&(this.clockOffsetMs+=n-this.pauseStartedAt,this.pauseStartedAt=null)}resolveNow(t){let n=this.pauseStartedAt!==null?t-this.pauseStartedAt:0;return t-this.clockOffsetMs-n}getElapsedSinceStart(t=this.clock.now()){return Math.max(0,this.resolveNow(t)-this.startTime)}restoreClock(t,n){this.pauseStartedAt=null,this.lastUpdateAt=null,this.lastRenderAt=null;let r=Math.max(0,t);if(typeof n=="number"&&Number.isFinite(n)){this.startTime=n,this.clockOffsetMs=this.clock.now()-n-r;return}this.clockOffsetMs=0,this.startTime=this.clock.now()-r}getRandomState(){return this.R.getState()}injectKey(t){this.keyboardManager.inject(t)}injectPointer(t,n,r){this.pointerManager.inject(t,n,r)}async updateAnimationState(t,n,r=this.clock.now()){let i=this.resolveNow(r),a=_t(i,this.startTime,this.lastUpdateAt,this.lastRenderAt);this.cartState=this.animationCart.update(this.R,t,n,this.dimensionContext,this.cartState,this.keyboardManager,this.pointerManager,this.gameManager,a,this.featureState,this.hostChannel),this.lastUpdateAt=i}async renderAnimation(t,n,r=this.clock.now()){let i=this.resolveNow(r),a=_t(i,this.startTime,this.lastUpdateAt,this.lastRenderAt);this.animationCart.render(this.R,t,n,this.dimensionContext,this.cartState,this.drawingContext,this.canvas.imageData,this.pointerManager,this.gameManager,a,this.featureState,this.hostChannel),this.lastRenderAt=i}getCanvas(){return this.canvas.canvas}getDrawDetails(){return[this.canvas.canvas,0,0,this.dimensionContext.width,this.dimensionContext.height]}teardown(){try{this.animationCart.teardown?.(this.cartState,this.featureState)}catch(t){console.error("Error during cart teardown",t)}this.keyboardManager.destroy(),this.pointerManager.destroy()}};var He=class extends ue{constructor(t,n,r=1,i=!0,a={}){if(super(t,n,r,a),this.adopted)return;let s=a.container;if(s){this.canvas.parentNode!==s&&s.appendChild(this.canvas);return}if(i){let u=document.getElementById("canvas");u&&u!==this.canvas&&u.parentNode===document.body&&document.body.removeChild(u),document.body.appendChild(this.canvas)}}};function Ot(e){let t=parseInt(e.substring(0,8),16),n=parseInt(e.substring(8,8),16),r=parseInt(e.substring(16,8),16),i=parseInt(e.substring(24,8),16);return{next:()=>{t|=0,n|=0,r|=0,i|=0;let s=(t+n|0)+i|0;return i=i+1|0,t=n^n>>>9,n=r+(r<<3)|0,r=r<<21|r>>>11,r=r+s|0,(s>>>0)/4294967296},getRegs:()=>({a:t,b:n,c:r,d:i}),setRegs:s=>{t=s.a,n=s.b,r=s.c,i=s.d}}}var Se=class{constructor(t){this.seed=t.hash,this.useA=!1,this.genA=Ot(t.hash.substring(2,32)),this.genB=Ot(t.hash.substring(34,32)),this.prngA=this.genA.next,this.prngB=this.genB.next;for(let n=0;n<1e6;n+=2)this.prngA(),this.prngB()}getState(){let t=this.genA.getRegs(),n=this.genB.getRegs();return{seed:this.seed,useA:this.useA,prngA:{a:t.a,b:t.b,c:t.c,d:t.d},prngB:{a:n.a,b:n.b,c:n.c,d:n.d}}}setState(t){if(t.seed!==this.seed)throw new Error(`Random.setState: seed ${t.seed} does not match ${this.seed}`);this.useA=t.useA,this.genA.setRegs(t.prngA),this.genB.setRegs(t.prngB)}r_zero_one(){return this.useA=!this.useA,this.useA?this.prngA():this.prngB()}dec(t,n){return t===void 0?this.r_zero_one():n===void 0?t*this.r_zero_one():t+(n-t)*this.r_zero_one()}int(t,n){return n===void 0&&(n=t,t=0),Math.floor(this.dec(t,n))}bool(t=.5){return this.r_zero_one()<t}sign(){return this.bool()?1:-1}choose(t){return t[this.int(t.length)]}};var Vt="bafybeicjwcq5lxxtfnyj4p2ugcr7ctyb5wl62cbcechj6tsabdq5whcs7u",Lt="https://ipfs.io/ipfs/";function Fn(e){return e.endsWith("/")?e:`${e}/`}var Ce=null;function _n(e){return[...Array(e)].map(()=>Math.floor(Math.random()*16).toString(16)).join("")}function On(e){return e&&e.length>0?e:[{cid:Vt}]}function Ln(e){return e.startsWith("0x")?e:`0x${e}`}var Nt=/^(0[xX])?[0-9a-fA-F]{64}$/;function Vn(e){let t="",n=2166136261,r=522970236;for(let i=0;t.length<64;i++){for(let a=0;a<e.length;a++)n^=e.charCodeAt(a)+i,n=Math.imul(n,16777619),r^=e.charCodeAt(a)+i*17,r=Math.imul(r,16777619);t+=(n>>>0).toString(16).padStart(8,"0"),t+=(r>>>0).toString(16).padStart(8,"0")}return`0x${t.slice(0,64)}`}function Ke(e){let t=typeof e=="number"?String(e):e;return Nt.test(t)?`0x${(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase()}`:Vn(t)}function $e(e,t){if(typeof e=="number"||t==="deterministic")return Ke(e);let n=String(e);return Nt.test(n)?Ke(n):n.startsWith("0x")||n.startsWith("0X")?n:`0x${n}`}function Nn(e){if(!e&&typeof tokenData<"u"&&tokenData?.hash)return{hash:tokenData.hash,tokenId:String(tokenData.tokenId),externalAssetDependencies:On(tokenData.externalAssetDependencies),preferredIPFSGateway:Fn(tokenData.preferredIPFSGateway||Lt),preferredArweaveGateway:tokenData.preferredArweaveGateway};let t=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams;return{hash:e?Ln(e):t.get("hash")||`0x${_n(64)}`,tokenId:"18009999",externalAssetDependencies:[{cid:Vt}],preferredIPFSGateway:Lt}}function tt(e){let t=e?.useCache!==!1;if(t&&Ce&&!e?.hash)return Ce;let n=Nn(e?.hash);return t?Ce=n:Ce||(Ce=n),n}function Ht(e){return new Array(32).fill(null).map((t,n)=>parseInt(e.hash.slice(2+n*2,4+n*2),16))}async function rt(){let e=await import("tone");if(typeof e.start=="function")return e;let t=e.default;return t&&typeof t.start=="function"?t:e}var jt={id:"tone",async load(){await Promise.resolve().then(()=>($t(),$n))},async unlock(){await jt.load(),await(await rt()).start()},async resumeIfSuspended(){let e=await rt();e.context.state==="suspended"&&await e.context.resume()},async suspendIfRunning(){let t=(await rt()).context.rawContext;"suspend"in t&&t.state==="running"&&await t.suspend()}},Ut={tone:jt};function it(e){if(!e)return[];let t=Array.isArray(e)?e:[e],n=[];for(let r of t){if(!(r in Ut)){console.warn(`Unknown audio library "${r}"`);continue}let i=r;n.includes(i)||n.push(i)}return n}function at(e){return e.map(t=>Ut[t])}var Ue="$cyberartTa",$=class extends Error{constructor(t){super(t),this.name="IncompatibleCartStateError"}},ot={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array};function jn(e){for(let t of Object.keys(ot))if(e instanceof ot[t])return t}function Wt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function B(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function st(e){return B(e)?typeof e[Ue]=="string"&&Array.isArray(e.d):!1}function Un(e){return e==null?!1:typeof e=="function"?!0:!(typeof e!="object"||Array.isArray(e)||Wt(e)||B(e))}var Bn=new Set(["audioContextStarted","midiSynths","keepRatioPrimed","audioInitStarted","musicSeekApplied"]);function Bt(e){return e===null?"null":st(e)?String(e[Ue]):Array.isArray(e)?"array":B(e)?"object":typeof e}function Wn(e,t){return e===t||e==="null"||t==="null"}function ee(e){return e.trim().toLowerCase().replace(/^0x/,"")}function zt(e,t,n,r){if(!(!n&&!r)&&ee(e)!==ee(t))throw new $(`Generative cart state is for seed "${t}", but the live token is "${e}"`)}function le(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function qt(e,t){let n=e.dimensions;if(n&&le(n.width)&&le(n.height))return n;if(t&&le(t.width)&&le(t.height))return{width:t.width,height:t.height};if(B(e.state)){let r=e.state.containerWidth,i=e.state.containerHeight;if(le(r)&&le(i))return{width:r,height:i}}return null}function pe(e,t=new WeakSet){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:null;if(!(typeof e=="function"||typeof e>"u"||typeof e=="bigint"||typeof e=="symbol")){if(Wt(e)){let n=jn(e);return n?{[Ue]:n,d:Array.from(e)}:void 0}if(typeof e=="object"&&!t.has(e)){t.add(e);try{if(Array.isArray(e)){let i=[],a=0;for(let s of e){let u=pe(s,t);u!==void 0&&(i.push(u),a++)}return e.length>0&&a===0?void 0:i}if(!B(e)||Un(e))return;let n=Object.keys(e),r={};for(let i of n){if(Bn.has(i))continue;let a=pe(e[i],t);a!==void 0&&(r[i]=a)}return n.length>0&&Object.keys(r).length===0?void 0:r}finally{t.delete(e)}}}}function Pe(e){if(st(e)){let t=ot[e[Ue]];return t?new t(e.d.map(n=>Number(n))):e}if(Array.isArray(e))return e.map(t=>Pe(t));if(B(e)){let t={};for(let n of Object.keys(e))t[n]=Pe(e[n]);return t}return e}function dt(e,t,n,r,i=!0){if(i&&n&&r&&n!==r)throw new $(`Cart state is for "${r}", but the live cart is "${n}"`);if(!B(t)){if(i)throw new $("Cart state snapshot is empty");return}let a=Object.keys(t);if(a.length===0){if(i)throw new $("Cart state snapshot is empty");return}let s=pe(e);if(!B(s)||Object.keys(s).length===0){if(i)throw new $("Live cart has no serializable state");return}let u=a.filter(f=>f in s);if(u.length===0){if(i)throw new $("Cart state snapshot does not overlap the live cart shape");return}for(let f of u){let v=Bt(s[f]),m=Bt(t[f]);if(!Wn(v,m))throw new $(`Cart state field "${f}" has type ${m}, live cart expects ${v}`);if(v==="object"){let h=t[f],S=e[f];B(h)&&!st(h)&&dt(S,h,void 0,void 0,!1)}}}function Gt(e,t){if(!B(e)||!B(t))return;let n=pe(e);if(B(n))for(let r of Object.keys(t))r in n&&(e[r]=Pe(t[r]))}function Yt(e){let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")throw new $("Cart state bundle is not an object");if(t.version!==1)throw new $(`Unsupported cart state version ${String(t.version)}`);if(typeof t.seed!="string"||typeof t.framesElapsed!="number")throw new $("Cart state bundle is missing seed or framesElapsed");return t}var Te="cyberart.asset.ready",xe="cyberart.asset.failed";function te(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function W(e){try{return JSON.stringify(e)}catch{return String(e)}}function ut(e,t,n){let r=t??[],i=n??[],a=Math.max(r.length,i.length);for(let s=0;s<a;s++)if(W(r[s])!==W(i[s]))return`${e}[${s}]: ${W(r[s])} vs ${W(i[s])}`}function Jt(e,t){let n=[];e.seed!==t.seed&&n.push(`seed: ${e.seed} vs ${t.seed}`),e.clock.framesElapsed!==t.clock.framesElapsed&&n.push(`framesElapsed: ${e.clock.framesElapsed} vs ${t.clock.framesElapsed}`),e.clock.now!==t.clock.now&&n.push(`now: ${e.clock.now} vs ${t.clock.now}`),e.clock.frameRate!==t.clock.frameRate&&n.push(`frameRate: ${e.clock.frameRate} vs ${t.clock.frameRate}`),W(e.rng)!==W(t.rng)&&n.push(`rng: ${W(e.rng)} vs ${W(t.rng)}`);let r=ut("actions",e.actions,t.actions);r&&n.push(r);let i=ut("applied",e.applied,t.applied);i&&n.push(i);let a=ut("events",e.events,t.events);return a&&n.push(a),W(e.state)!==W(t.state)&&n.push(`state: ${W(e.state)} vs ${W(t.state)}`),n}function Xt(e){return{type:e.status==="ready"?Te:xe,kind:"state",payload:e.detail===void 0?{id:e.id}:{id:e.id,detail:e.detail}}}function qn(e){if(!e||typeof e!="object")return 0;let t=e;return typeof t.startTime=="number"&&typeof t.lastSimulationUpdateAt=="number"?Math.max(0,t.lastSimulationUpdateAt-t.startTime):0}function Gn(e,t){if(typeof window.resizeTo!="function")return!1;try{if(window.top!==window)return!1}catch{return!1}let n=Math.max(1,Math.round(e)),r=Math.max(1,Math.round(t)),i=Math.max(0,window.outerWidth-window.innerWidth),a=Math.max(0,window.outerHeight-window.innerHeight);try{window.resizeTo(n+i,r+a)}catch{return!1}return Math.abs(window.innerWidth-n)<=8&&Math.abs(window.innerHeight-r)<=8}var Yn=[[0,0],[16,9],[9,16],[4,3],[3,4],[2,1],[1,2],[3,1],[1,3],[1,1]],lt=Yn[0],Jn=lt[0]/lt[1],ct=30,Xn=120,Qn=3840/2160,Zn=2160/3840,Be=class{constructor(t=ct,n=!1,r=window.innerWidth,i=window.innerHeight,a=!0,s,u={}){this.framesElapsed=0;this.frameRate=ct;this._paused=!1;this.savedToken=!1;this.prepared=!1;this.loopRunning=!1;this.fallbackAudio=[];this.audioLibrariesInternal=[];this.virtualClock=null;this.scriptedActions=[];this.initialScriptedActions=[];this.appliedActions=[];this.consumedActionIndexes=new Set;this.outboundEvents=[];this.consecutiveErrorCount=0;this.lastErrorLogAt=0;this.reinitStayPaused=!1;this.reinitPending=!1;this.lastExportedFramebuffer=null;this.pinnedOutput=null;this.pinViewportAtImport=null;this.importing=!1;this.drawLoop=this.drawLoop.bind(this),this.loadCart=this.loadCart.bind(this),this.prepareCart=this.prepareCart.bind(this),this.beginPlayback=this.beginPlayback.bind(this),this.reinit=this.reinit.bind(this),this.tuneFramerate=this.tuneFramerate.bind(this),this.container=u.container,this.seed=u.seed,this.captureKeyboard=u.captureKeyboard??!0,this.customState=u.customState,this.hostChannel=u.hostChannel,this.fallbackAudio=it(u.audio),this.audioLibrariesInternal=this.fallbackAudio;let f=u.deterministic;this.deterministic=!!f;let v=f&&typeof f=="object"?f:{};if(this.deterministic){if(u.clock){let m=u.clock;if(typeof m.advance!="function")throw new Error("deterministic mode requires a virtual clock with advance()");this.virtualClock=m,this.clock=m}else this.virtualClock=Ve(v.origin??0),this.clock=this.virtualClock;this.initialScriptedActions=te(v.actions??[]),this.scriptedActions=te(this.initialScriptedActions)}else this.clock=u.clock??ce();this.isBodyCanvas=this.container?!1:a,this.autoMode=n,this.aspectRatio=Jn,this.selectedAsp=lt,this.isFullscreen=!!document.fullscreenElement,this.updateFrameRate(t),this.tempUnpause=!1,this.synchronous=de,this.containerWidth=r,this.containerHeight=i,this.gameManager=s,this.init(!0)}setGameManager(t){this.gameManager=t}reinit(t){if(!this.importing){if(this.shouldKeepPinnedOutput()){this.fitPinnedCanvas();return}this.reinitPending||(this.reinitStayPaused=this._paused,this.reinitPending=!0),this.paused=!0,clearTimeout(this.reinitTimeout),this.reinitTimeout=setTimeout(()=>{if(this.importing){this.paused=this.reinitStayPaused,this.reinitPending=!1;return}this.updateInProgress?this.reinit(t):(this.requestedAnimationFrame&&cancelAnimationFrame(this.requestedAnimationFrame),this.clearPinnedOutput(),this.init(),this.reloadCart(),this.paused=this.reinitStayPaused,this.reinitPending=!1)},150)}}initSeed(){this.tokenData=this.seed?tt({hash:this.seed,useCache:!1}):tt(),this.rawParams=Ht(this.tokenData),this.mintNo=parseInt(this.tokenData.tokenId)%1e6,console.log("token",this.mintNo,this.tokenData.hash)}init(t=!1){t&&this.initSeed(),this.pureAspectUpdate(this.selectedAsp);let n=this.aspectRatio,[r,i]=It(n,this.containerWidth,this.containerHeight);r*=j,i*=j,this.width=~~r,this.height=~~i,this.atCenterX=this.width/2,this.atCenterY=this.height/2,this.mainCanvas?this.mainCanvas.setSize(this.width,this.height):this.mainCanvas=new He(this.width,this.height,1,this.isBodyCanvas,this.canvasMountOptions())}loadCart(t){this.prepareCart(t)&&this.beginPlayback()}prepareCart(t){if(this.prepared)return!0;try{let n=~~(this.width/1),r=~~(this.height/this.width*n),i=new Se(this.tokenData),a=new Ne(n,r,i,this.rawParams,t,{gameManager:this.gameManager,canvasMount:this.canvasMountOptions(),customState:this.customState,captureKeyboard:this.deterministic?!1:this.captureKeyboard,hostChannel:this.hostChannel,clock:this.clock,listenToPointer:!this.deterministic});return this.animation=a,this.animationCart=t,this.paused=!1,this.framesElapsed=0,this.outboundEvents=[],this.scriptedActions=te(this.initialScriptedActions),this.appliedActions=[],this.consumedActionIndexes=new Set,this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.deterministic&&this.hostChannel&&(this.outboundUnsubscribe=this.hostChannel.onEvent(s=>{this.outboundEvents.push(s)})),this.R=i,this.applyCartFrameRate(t,a),this.resolveAudioLibraries(t),this.prepared=!0,!0}catch(n){return console.error(n),!1}}applyCartFrameRate(t,n){let r=t.metadata,i=r?.frameRate??ct,a=n.cartState?.visualMode??n.featureState?.visualMode,s=a&&r?.frameRateByVisualMode?r.frameRateByVisualMode[a]:void 0;this.updateFrameRate(typeof s=="number"&&s>0?s:i)}get audioLibraries(){return this.audioLibrariesInternal}get needsAudio(){return this.audioLibrariesInternal.length>0}resolveAudioLibraries(t){this.audioLibrariesInternal=it(t.metadata?.audio)}async unlockAudio(){if(this.audioLibrariesInternal.length===0)return;let t=at(this.audioLibrariesInternal);if(de){for(let n of t)await n.load();return}for(let n of t)await n.unlock()}async resumeAudioLibraries(){if(!(this.paused||de))for(let t of at(this.audioLibrariesInternal))try{await t.resumeIfSuspended()}catch(n){console.error(`Failed to resume audio library "${t.id}" after reload`,n)}}beginPlayback(){!this.prepared||this.loopRunning||(this.prepared=!1,this.loopRunning=!0,this.consecutiveErrorCount=0,!this.deterministic&&(this.requestedAnimationFrame=requestAnimationFrame(this.drawLoop)))}get isPrepared(){return this.prepared}get isLoopRunning(){return this.loopRunning}get isDeterministic(){return this.deterministic}getClock(){return{now:this.clock.now(),framesElapsed:this.framesElapsed,frameRate:this.frameRate}}getRandomState(){return this.requirePreparedAnimation().getRandomState()}schedule(t){this.scriptedActions.push(te(t))}async getReplayMetadata(){let t=await this.exportState();return{seed:this.tokenData.hash,clock:this.getClock(),rng:this.getRandomState(),actions:te(this.scriptedActions),applied:te(this.appliedActions),events:te(this.outboundEvents),state:t.state}}async step(t=1){if(!this.deterministic)throw new Error("step() requires createRuntime({ deterministic: true })");this.requirePreparedAnimation(),this.prepared&&!this.loopRunning&&this.beginPlayback(),this.paused=!1;let n=Math.max(0,Math.floor(t));for(let r=0;r<n&&this.animation;r++){let i=this.framesElapsed;if(this.applyScheduledActions(i),await this.processFrame(this.clock.now(),{ignorePause:!0,scheduleNext:!1}),this.framesElapsed===i||(this.virtualClock?.advance(this.targetDrawTime),!this.loopRunning))break}}async advance(t){let n=Math.max(0,Math.round(t/this.targetDrawTime));await this.step(n)}applyScheduledActions(t){let n=this.animation;n&&this.scriptedActions.forEach((r,i)=>{r.atFrame===t&&(this.consumedActionIndexes.has(i)||(this.consumedActionIndexes.add(i),r.type==="pointer"?n.injectPointer(r.pointer.kind,r.pointer.x,r.pointer.y):r.type==="key"?n.injectKey(r.key):r.type==="event"?this.hostChannel?.dispatch(r.event):r.type==="asset"&&this.hostChannel?.dispatch(Xt(r)),this.appliedActions.push({frame:t,action:r})))})}get paused(){return this._paused}set paused(t){this._paused!==t&&(this._paused=t,this.animation?.setPaused(t))}async waitUntilUpdateIdle(){for(;this.updateInProgress;)await new Promise(t=>{this.deterministic?queueMicrotask(t):typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>t()):setTimeout(t,0)})}requirePreparedAnimation(){if(!this.animation)throw new Error("No prepared cart");return this.animation}async exportState(){let t=this.requirePreparedAnimation(),n=this._paused;this.paused=!0,await this.waitUntilUpdateIdle();try{this.lastExportedFramebuffer=t.captureFramebuffer();let r=t.getCanvas();return{version:1,cartId:this.animationCart?.metadata?.id,generative:this.animationCart?.metadata?.generative,seed:this.tokenData.hash,framesElapsed:this.framesElapsed,elapsedSinceStart:t.getElapsedSinceStart(),dimensions:{width:r.width,height:r.height,cssWidth:this.containerWidth,cssHeight:this.containerHeight,dpr:j},state:pe(t.cartState)}}finally{this.paused=n}}async exportStateJSON(){return JSON.stringify(await this.exportState())}peekExportedFramebuffer(){return this.lastExportedFramebuffer}peekSeed(){return this.tokenData?.hash}isGenerative(){return this.animationCart?.metadata?.generative===!0}async importState(t,n){let r=this.requirePreparedAnimation(),i=Yt(t),a=this._paused,s=this.loopRunning;this.paused=!0,await this.waitUntilUpdateIdle(),dt(r.cartState,i.state,this.animationCart?.metadata?.id,i.cartId),zt(this.tokenData.hash,i.seed,this.animationCart?.metadata?.generative,i.generative),clearTimeout(this.reinitTimeout),this.reinitPending=!1,this.importing=!0;let u=qt(i,n?.framebuffer??this.lastExportedFramebuffer);if(u){this.pinOutputSize(u);let m=u.cssWidth??u.width/j,h=u.cssHeight??u.height/j;Gn(m,h),this.syncContainerFromDom(),this.pinViewportAtImport={w:this.containerWidth,h:this.containerHeight}}let f=this.customState,v=!1;try{if(this.customState=Pe(i.state),this.unloadCart(),!this.prepareCart(this.animationCart))throw new Error("Failed to prepare cart while loading state");this.animation.cartState!==this.customState&&Gt(this.animation.cartState,i.state),this.framesElapsed=i.framesElapsed;let m=this.animation,h=m.cartState,S=typeof i.elapsedSinceStart=="number"?i.elapsedSinceStart:qn(h);m.restoreClock(S,typeof h?.startTime=="number"?h.startTime:void 0),a&&m.setPaused(!0);let E=n?.framebuffer??this.lastExportedFramebuffer;E&&m.restoreFramebuffer(E)?h.keepRatioPrimed=!0:await m.renderAnimation(this.framesElapsed,this.rawParams),this.fitPinnedCanvas(),v=!0}catch(m){throw this.clearPinnedOutput(),this.customState=f,this.paused=a,this.animationCart&&(this.syncContainerFromDom(),this.init(),this.reloadCart()),m}finally{this.importing=!1,v&&(this.customState=f,this.paused=a,s&&this.beginPlayback())}}unloadCart(){this.loopRunning=!1,this.requestedAnimationFrame&&cancelAnimationFrame(this.requestedAnimationFrame),this.drawLoopTimeout&&clearTimeout(this.drawLoopTimeout),this.animation?.teardown(),this.animation=void 0,this.prepared=!1,this.audioLibrariesInternal=this.fallbackAudio,this.mainCanvas?.clearAll()}reloadCart(t=!1){let n=this.animationCart;if(!n)return;this.pinnedOutput&&(this.clearPinnedOutput(),this.syncContainerFromDom(),this.init());let r=this.reinitPending?this.reinitStayPaused:this._paused;this.unloadCart(),t&&this.initSeed(),this.loadCart(n),this.paused=r,!this.paused&&!de&&this.resumeAudioLibraries()}getFrameRate(){return this.frameRate}updateFrameRate(t){if(this.frameRate=t,t>=1)this.targetDrawTime=1e3/t;else{let r=1/(2-t);this.targetDrawTime=1e3/r}this.drawTime=this.targetDrawTime}canvasMountOptions(){return{container:this.container,adoptFromDocument:!this.container}}syncContainerFromDom(){if(this.container){this.containerWidth=this.container.clientWidth||this.containerWidth,this.containerHeight=this.container.clientHeight||this.containerHeight;return}this.containerWidth=window.innerWidth,this.containerHeight=window.innerHeight}pinOutputSize(t){this.pinnedOutput=t,this.width=~~t.width,this.height=~~t.height,this.atCenterX=this.width/2,this.atCenterY=this.height/2,this.aspectRatio=this.width/this.height,this.mainCanvas&&this.mainCanvas.setSize(this.width,this.height)}shouldKeepPinnedOutput(){return this.pinnedOutput?(this.syncContainerFromDom(),this.viewportMatches(this.pinnedCssSize())?!0:!!(this.pinViewportAtImport&&this.viewportMatches(this.pinViewportAtImport))):!1}pinnedCssSize(){let t=this.pinnedOutput;return{w:t.cssWidth??t.width/j,h:t.cssHeight??t.height/j}}viewportMatches(t){return Math.abs(this.containerWidth-t.w)<8&&Math.abs(this.containerHeight-t.h)<8}fitPinnedCanvas(){let t=this.pinnedOutput,n=this.canvas;if(!t||!n)return;this.container&&!this.container.style.position&&(this.container.style.position="relative");let r=this.containerWidth||window.innerWidth,i=this.containerHeight||window.innerHeight,a=t.width/j,s=t.height/j;if(a<1||s<1||r<1||i<1)return;let u=Math.min(r/a,i/s),f=a*u,v=s*u;n.style.position="absolute",n.style.left="50%",n.style.top="50%",n.style.transform="translate(-50%, -50%)",n.style.margin="0",n.style.width=`${f}px`,n.style.height=`${v}px`,n.style.imageRendering=Math.abs(u-1)<.01?"auto":"pixelated"}clearPinnedOutput(){let t=this.canvas;this.pinnedOutput=null,this.pinViewportAtImport=null,t&&(t.style.position="",t.style.left="",t.style.top="",t.style.transform="",t.style.imageRendering="",t.style.width="",t.style.height="",t.style.margin="auto")}get canvas(){return this.animation?.getCanvas()??this.mainCanvas?.canvas}destroy(){this.outboundUnsubscribe?.(),this.outboundUnsubscribe=void 0,this.clearPinnedOutput(),this.unloadCart(),clearTimeout(this.reinitTimeout),this.mainCanvas&&!this.mainCanvas.adopted&&this.mainCanvas.canvas.remove()}drawIt(){}tuneFramerate(t){let n=this.lastCall||t;this.lastCall=t,this.drawTime=Math.max(0,this.drawTime+this.targetDrawTime-this.lastCall+n)}async processFrame(t,n={}){let r=n.ignorePause===!0,i=n.scheduleNext!==!1;if(!this.loopRunning&&!r)return;let a=!1,s,u="update";try{if(r||!this.paused||this.tempUnpause){if(!de&&!r&&this.tuneFramerate(t),!this.animation)return;if(u="update",this.updateInProgress=!0,await this.animation.updateAnimationState(this.framesElapsed,this.rawParams,t),this.updateInProgress=!1,u="render",await this.animation.renderAnimation(this.framesElapsed,this.rawParams,t),this.autoMode&&this.animation.cartState.saveToken&&!this.savedToken&&!new URLSearchParams(window.location.search).get("hash")){let m=localStorage.getItem("goodones"),h=JSON.stringify(m?[...JSON.parse(m),this.tokenData.hash]:[this.tokenData.hash]);localStorage.setItem("goodones",h),this.savedToken=!0,localStorage.setItem(this.tokenData.hash,this.mainCanvas.canvas.toDataURL("image/png")),window.location.reload(),this.loopRunning=!1;return}this.framesElapsed++,this.tempUnpause&&(this.tempUnpause=!1)}u="draw",this.drawIt()}catch(f){a=!0,s=f,this.handleFrameError(f,u)}finally{this.updateInProgress=!1}a?(this.consecutiveErrorCount++,this.consecutiveErrorCount>=Xn&&(this.loopRunning=!1,this.onError?.(s,{phase:u,consecutive:this.consecutiveErrorCount,stopped:!0}))):this.consecutiveErrorCount=0,!(!this.loopRunning||!i)&&(this.drawLoopTimeout=setTimeout(()=>{this.requestedAnimationFrame=requestAnimationFrame(this.drawLoop)},this.drawTime))}async drawLoop(t){await this.processFrame(t,{scheduleNext:!0})}handleFrameError(t,n){let r=performance.now();r-this.lastErrorLogAt>=1e3&&(this.lastErrorLogAt=r,console.error(`Animation ${n} error:`,t)),this.consecutiveErrorCount===0&&this.onError?.(t,{phase:n,consecutive:1,stopped:!1})}pureAspectUpdate(t){if(t[0]===0&&t[1]===0){let r=this.containerWidth||window.innerWidth,i=this.containerHeight||window.innerHeight,a=r/i;this.aspectRatio=Math.min(Qn,Math.max(Zn,a))}else this.aspectRatio=t[0]/t[1]}};var er="HostChannel has been destroyed",fe=class{constructor(){this.inbound=[];this.listeners=[];this.closed=!1}dispatch(t){this.requireOpen(),this.inbound.push(t),this.inbound.length>32&&this.inbound.splice(0,this.inbound.length-32)}consume(){if(this.requireOpen(),this.inbound.length===0)return[];let t=this.inbound;return this.inbound=[],t}emit(t){this.requireOpen();for(let n of this.listeners)n(t)}onEvent(t){return this.requireOpen(),this.listeners.push(t),()=>{this.listeners=this.listeners.filter(n=>n!==t)}}clearInbound(){this.requireOpen(),this.inbound=[]}clear(){this.inbound=[],this.listeners=[]}close(){this.closed=!0,this.clear()}requireOpen(){if(this.closed)throw new Error(er)}};var nn=["image","audio","font","spritesheet"],rn=["timeout","cors","not-found","invalid","aborted","resolver"],me="cyberart:fallback/silent",Qt="Asset preloader has been destroyed",tr=4,nr=new Set(nn),rr=new Set(rn),ir={timeout:"asset load timed out",cors:"CORS blocked this asset","not-found":"asset was not found",invalid:"asset declaration or resource is invalid",aborted:"asset load was aborted",resolver:"asset resolver failed"};function an(e){return typeof e=="string"&&nr.has(e)}function on(e){return typeof e=="string"&&rr.has(e)}function We(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.id=="string"&&typeof t.ref=="string"&&on(t.code)&&typeof t.message=="string"}function F(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message&&e.message.length>0?e.message:ir[e.code]}}function ae(e,t){return{type:e==="ready"?Te:xe,kind:"state",payload:t}}function sn(e){if(!e?.aborted)return;let t=new Error("aborted");throw t.name="AbortError",t}function ar(e){return e instanceof Error&&e.name==="AbortError"||typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"}function pt(e){return e?{...e}:void 0}function X(e){let t={id:e.id,ref:e.ref,type:e.type,url:e.url};return e.integrity!==void 0&&(t.integrity=e.integrity),e.provenance&&(t.provenance=pt(e.provenance)),e.cors!==void 0&&(t.cors=e.cors),e.usedFallback&&(t.usedFallback=!0),e.managed&&(t.managed=!0),t}function Re(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message}}function or(e){if(e.state==="ready"){let t={state:"ready",resource:X(e.resource)};return e.failure&&(t.failure=Re(e.failure)),t}return e.state==="failed"?{state:"failed",failure:Re(e.failure)}:{state:e.state}}function sr(e){return/^https?:/i.test(e)}function dn(e){return e.endsWith("/")?e:`${e}/`}function un(e,t){let n=dn(t);if(/^(https?:|data:|blob:)/i.test(e))return e;let r=/^moltazine:post\/([^#]+)#(.+)$/.exec(e);if(r)return`${n}moltazine/${encodeURIComponent(r[1])}/${r[2]}`;let i=/^world:asset\/(.+)$/.exec(e);if(i)return`${n}world/${i[1]}`;let a=/^library:(.+)$/.exec(e);return a?`${n}library/${a[1]}`:`${n}${e.replace(/^\//,"")}`}function dr(e){return{async resolve(t,n){sn(n);let r=e[t.ref];if(!r)throw F({id:t.id,ref:t.ref,code:"not-found",message:`no fixture for ${t.ref}`});if("error"in r)throw F({id:t.id,ref:t.ref,code:r.error,message:r.message});return{id:t.id,ref:t.ref,type:t.type,url:r.url,integrity:r.integrity??t.integrity,cors:r.cors??"omit",provenance:r.provenance??t.provenance}}}}function ur(e){let t=dn(e.cdnBase);return{async resolve(n,r){sn(r);let i=e.failures?.[n.ref];if(i){let s=typeof i=="string"?i:i.code,u=typeof i=="string"?void 0:i.message;throw F({id:n.id,ref:n.ref,code:s,message:u})}let a=un(n.ref,t);return{id:n.id,ref:n.ref,type:n.type,url:a,integrity:n.integrity,cors:sr(a)?"anonymous":"omit",provenance:n.provenance}}}}function cr(e){if(!e||typeof e!="object")return F({id:"",ref:"",code:"invalid",message:"declaration is required"});if(typeof e.id!="string"||e.id.length===0)return F({id:typeof e.id=="string"?e.id:"",ref:typeof e.ref=="string"?e.ref:"",code:"invalid",message:"id is required"});if(typeof e.ref!="string"||e.ref.length===0)return F({id:e.id,ref:"",code:"invalid",message:"ref is required"});if(!an(e.type))return F({id:e.id,ref:e.ref,code:"invalid",message:`unsupported type ${String(e.type)}`});if(e.integrity!==void 0&&typeof e.integrity!="string")return F({id:e.id,ref:e.ref,code:"invalid",message:"integrity must be a string"});if(e.timeoutMs!==void 0&&(typeof e.timeoutMs!="number"||!Number.isFinite(e.timeoutMs)||e.timeoutMs<0))return F({id:e.id,ref:e.ref,code:"invalid",message:"timeoutMs must be a non-negative finite number"})}function Zt(e){return{id:e.id,ref:me,type:e.type,url:me,usedFallback:!0,cors:"omit"}}function en(e,t){return We(t)?{id:e.id,ref:e.ref,code:t.code,message:t.message}:ar(t)?F({id:e.id,ref:e.ref,code:"aborted"}):F({id:e.id,ref:e.ref,code:"resolver",message:t instanceof Error?t.message:String(t)})}function tn(e,t){if(!t||typeof t.url!="string"||t.url.length===0)throw F({id:e.id,ref:e.ref,code:"invalid",message:"resolver returned no url"});if(t.integrity&&e.integrity&&t.integrity!==e.integrity)throw F({id:e.id,ref:e.ref,code:"invalid",message:"integrity mismatch"});let n=X(t);return n.id=e.id,n.ref=t.ref||e.ref,n.type=e.type,!n.integrity&&e.integrity&&(n.integrity=e.integrity),!n.provenance&&e.provenance&&(n.provenance=pt(e.provenance)),n}function ft(e){if(typeof e?.resolver?.resolve!="function")throw new Error("createAssetPreloader: resolver is required");let t=e.emitEvents!==!1,n=e.wallClockTimeout!==!1,r=new Map,i=[],a=new Map,s=new Map,u=new Map,f=new Map,v=new Map,m=new Set,h=!1;function S(o){return o.code==="aborted"||o.code==="timeout"}function E(o,g,b){let k=en(o,b);return k.code==="timeout"?k:g.aborted?F({id:o.id,ref:o.ref,code:"aborted"}):k}function N(o,g){let b=v.get(o);b||(b=new Set,v.set(o,b)),b.add(g)}function l(o){if(o?.state==="ready")return`${o.resource.type}\0${o.resource.ref}`}function c(o,g){for(let[b,k]of v)if(b!==g&&k.has(o))return!0;for(let[b,k]of r)if(b!==g&&l(k)===o)return!0;return!1}function D(o,g){let b=new Set(v.get(o)),k=l(g);k&&b.add(k),v.delete(o);for(let H of b)c(H,o)||u.delete(H)}function x(){let o=0,g=0,b=0,k=0,H={};for(let[R,T]of r)H[R]=or(T),T.state==="pending"||T.state==="loading"?o+=1:T.state==="failed"?b+=1:(g+=1,(T.resource.usedFallback||T.failure)&&(k+=1));return{total:r.size,pending:o,ready:g,failed:b,fallbacks:k,items:H,failures:i.map(Re)}}function q(){if(m.size===0)return;let o=x();for(let g of m)g(o)}function I(o){i.push(Re(o))}function L(o){h||!t||!e.dispatch||e.dispatch(o)}function G(o){if(o?.managed&&o.url.startsWith("blob:")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(o.url)}catch{}}function P(o,g){if(h)return;let b=r.get(o);b?.state==="ready"&&G(b.resource),r.set(o,g),q()}function Q(o){if(o.fallback!==void 0)return o.fallback==="silent"?{id:`${o.id}::fallback`,ref:me,type:o.type}:typeof o.fallback=="string"?{id:`${o.id}::fallback`,ref:o.fallback,type:o.type}:{...o.fallback,id:typeof o.fallback.id=="string"&&o.fallback.id.length>0?o.fallback.id:`${o.id}::fallback`}}function _(o,g,b){let k=`${o.type}\0${o.ref}`,H=u.get(k);if(H)return g.aborted?Promise.reject(F({id:o.id,ref:o.ref,code:"aborted"})):(N(b,k),Promise.resolve(X(H.resource)));if(g.aborted)return Promise.reject(F({id:o.id,ref:o.ref,code:"aborted"}));let R=f.get(k);if(!R){let C=new AbortController,M={id:o.id,ref:o.ref,type:o.type};o.integrity!==void 0&&(M.integrity=o.integrity),o.provenance&&(M.provenance=pt(o.provenance)),R={promise:Promise.resolve().then(()=>e.resolver.resolve(M,C.signal)).then(O=>{let J=tn(o,O);if(C.signal.aborted)throw F({id:o.id,ref:o.ref,code:"aborted"});return u.set(k,{resource:X(J)}),J}).catch(O=>{throw en(o,O)}).finally(()=>{f.delete(k)}),controller:C,waiters:0},f.set(k,R)}let T=R;return T.waiters+=1,new Promise((C,M)=>{let Y=!1,O=(Z,et)=>{Y||(Y=!0,g.removeEventListener("abort",J),T.waiters-=1,et&&T.waiters<=0&&T.controller.abort(),Z())},J=()=>{O(()=>M(F({id:o.id,ref:o.ref,code:"aborted"})),!0)};if(g.aborted){J();return}g.addEventListener("abort",J,{once:!0}),T.promise.then(Z=>{if(!Y){if(g.aborted){J();return}N(b,k),O(()=>C(X(Z)),!1)}},Z=>{if(!Y){if(g.aborted){J();return}O(()=>M(Z),!1)}})})}function oe(o,g,b){if(g.aborted)return Promise.reject(F({id:o.id,ref:o.ref,code:"aborted"}));if(o.ref===me)return Promise.resolve(Zt(o));let k=new AbortController,H=()=>k.abort();g.addEventListener("abort",H,{once:!0});let R=o.timeoutMs??e.timeoutMs,T,C=!1;return n&&R!==void 0&&R>0&&Number.isFinite(R)&&(T=setTimeout(()=>{C=!0,k.abort()},R)),_(o,k.signal,b).then(M=>{let Y=tn(o,M);return Y.id=o.id,Y}).catch(M=>{throw C?F({id:o.id,ref:o.ref,code:"timeout"}):M}).finally(()=>{T!==void 0&&clearTimeout(T),g.removeEventListener("abort",H)})}async function Ee(o,g,b,k){try{return{resource:await oe(o,g,k)}}catch(H){let R=E(o,g,H);if(S(R)||g.aborted||b>=tr)throw R;let T=Q(o);if(!T)throw R;if(g.aborted)throw F({id:o.id,ref:o.ref,code:"aborted"});if(o.fallback==="silent"||T.ref===me)return{resource:Zt(o),failure:R};try{let C=await Ee(T,g,b+1,k);return{resource:{...X(C.resource),id:o.id,usedFallback:!0},failure:R}}catch(C){let M=We(C)&&!S(C)&&!g.aborted?C:E(o,g,C);throw!S(M)&&!g.aborted&&I(R),M}}}async function Ae(o,g){if(h)throw new Error(Qt);let b=r.get(o.id);if(b?.state==="ready"||b?.state==="failed")return;let k=a.get(o.id);if(k){await k;return}let H=(async()=>{let R=cr(o);if(R){P(o.id,{state:"failed",failure:R}),I(R),L(ae("failed",{id:o.id,ref:o.ref,failure:R}));return}P(o.id,{state:"loading"});let T=s.get(o.id)??new AbortController;s.has(o.id)||s.set(o.id,T);try{let C=await Ee(o,T.signal,g,o.id);if(h)return;if(T.signal.aborted){let M=F({id:o.id,ref:o.ref,code:"aborted"});P(o.id,{state:"failed",failure:M}),I(M),L(ae("failed",{id:o.id,ref:o.ref,failure:M}));return}if(C.resource.id=o.id,C.failure){P(o.id,{state:"ready",resource:C.resource,failure:C.failure}),I(C.failure),L(ae("failed",{id:o.id,ref:o.ref,failure:C.failure,resource:X(C.resource)})),L(ae("ready",{id:o.id,ref:C.resource.ref,resource:X(C.resource),failure:C.failure}));return}P(o.id,{state:"ready",resource:C.resource}),L(ae("ready",{id:o.id,ref:o.ref,resource:X(C.resource)}))}catch(C){if(h)return;let M=We(C)&&!S(C)&&!T.signal.aborted?{...Re(C),id:o.id}:E(o,T.signal,C);P(o.id,{state:"failed",failure:M}),I(M),L(ae("failed",{id:o.id,ref:o.ref,failure:M}))}finally{s.get(o.id)===T&&s.delete(o.id)}})();a.set(o.id,H);try{await H}finally{a.delete(o.id)}}return{async preload(o){if(h)throw new Error(Qt);let g=Array.isArray(o)?o:[];for(let b of g)b&&typeof b.id=="string"&&b.id.length>0&&(r.has(b.id)||r.set(b.id,{state:"pending"}),s.has(b.id)||s.set(b.id,new AbortController));return q(),await Promise.all(g.map(b=>Ae(b,0))),x()},get(o){let g=r.get(o);if(g?.state==="ready")return X(g.resource)},getProgress(){return x()},onProgress(o){return m.add(o),()=>{m.delete(o)}},abort(o){if(!h){if(o!==void 0){s.get(o)?.abort();return}for(let g of s.values())g.abort()}},forget(o){if(h)return;if(o===void 0){for(let b of r.values())b.state==="ready"&&G(b.resource);r.clear(),i.length=0,u.clear(),v.clear(),q();return}let g=r.get(o);g?.state==="ready"&&G(g.resource),D(o,g),r.delete(o);for(let b=i.length-1;b>=0;b--)i[b].id===o&&i.splice(b,1);q()},dispose(){if(!h){h=!0;for(let o of s.values())o.abort();s.clear();for(let o of r.values())o.state==="ready"&&G(o.resource);r.clear(),i.length=0,a.clear();for(let o of f.values())o.controller.abort();u.clear(),f.clear(),v.clear(),m.clear()}}}}function lr(e){xt();let{container:t,seed:n,captureKeyboard:r=!1,audio:i,deterministic:a,assets:s}=e,u=n===void 0?void 0:$e(n,a?"deterministic":"live"),f=new fe;if(s&&typeof s.resolver?.resolve!="function")throw new Error("createRuntime: assets.resolver is required");let v=s?ft({resolver:s.resolver,timeoutMs:s.timeoutMs,emitEvents:s.emitEvents??!a,wallClockTimeout:!a,dispatch:I=>f.dispatch(I)}):void 0,m=!1,h=null,S,E=!1,N=t.clientWidth||window.innerWidth,l=t.clientHeight||window.innerHeight,c=new Be(30,!1,N,l,!1,void 0,{container:t,seed:u,captureKeyboard:r,hostChannel:f,audio:i,deterministic:a}),D=()=>{let I=t.clientWidth||window.innerWidth,L=t.clientHeight||window.innerHeight;return I===c.containerWidth&&L===c.containerHeight?!1:(c.containerWidth=I,c.containerHeight=L,!0)},x=null;return!c.isDeterministic&&typeof ResizeObserver<"u"&&(x=new ResizeObserver(()=>{if(m||!h)return;D()&&E&&c.reinit()}),x.observe(t)),c.onError=(I,L)=>{S?.(I,L)},{get tokenData(){return c.tokenData},get hostChannel(){return f},get assets(){return v},get onError(){return S},set onError(I){S=I},mount(I,L={}){if(m)throw new Error("createRuntime: cannot mount on a destroyed runtime");h?.destroy(),E=!1,c.customState=L.initialState,c.setGameManager(L.gameManager);let G=L.onEvent?f.onEvent(L.onEvent):()=>{};if(!c.prepareCart(I))throw G(),new Error("createRuntime: failed to prepare cart");let P=!1,Q={async start(){if(!P){if(D()&&c.isPrepared&&(c.init(),c.unloadCart(),!c.prepareCart(I)))throw new Error("createRuntime: failed to prepare cart");c.needsAudio&&(await c.unlockAudio(),P)||(E=!0,c.beginPlayback())}},pause(){P||(c.paused=!0)},resume(){P||(c.paused=!1)},dispatch(_){P||f.dispatch(_)},snapshot(){if(P)return{seed:"",pngDataUrl:""};let _=c.canvas;return{seed:c.tokenData.hash,metadata:I.metadata,pngDataUrl:_?_.toDataURL("image/png"):""}},destroy(){P||(P=!0,E=!1,G(),f.clearInbound(),c.unloadCart(),h===Q&&(h=null))},reload(){if(!P){if(!E){if(c.isPrepared&&(c.unloadCart(),!c.prepareCart(I)))throw new Error("createRuntime: failed to prepare cart");return}c.reloadCart()}},reinit(_){if(!P){if(!E){D();return}c.reinit(_)}},getCartState(){return c.animation?.cartState},exportState(){return P?Promise.reject(new Error("Cart handle has been destroyed")):c.exportState()},exportStateJSON(){return P?Promise.reject(new Error("Cart handle has been destroyed")):c.exportStateJSON()},async importState(_,oe){if(P)throw new Error("Cart handle has been destroyed");await c.importState(_,oe)},peekExportedFramebuffer(){return P?null:c.peekExportedFramebuffer()},peekSeed(){if(!P)return c.peekSeed()},isGenerative(){return P?!1:c.isGenerative()},async step(_=1){if(P)throw new Error("Cart handle has been destroyed");await c.step(_)},async advance(_){if(P)throw new Error("Cart handle has been destroyed");await c.advance(_)},schedule(_){P||c.schedule(_)},getClock(){if(P)throw new Error("Cart handle has been destroyed");return c.getClock()},getRandomState(){if(P)throw new Error("Cart handle has been destroyed");return c.getRandomState()},getReplayMetadata(){return P?Promise.reject(new Error("Cart handle has been destroyed")):c.getReplayMetadata()},get canvas(){return c.canvas},get paused(){return c.paused},set paused(_){P||(c.paused=_)},get tokenData(){return c.tokenData},get isPrepared(){return c.isPrepared},get isLoopRunning(){return c.isLoopRunning},get needsAudio(){return c.needsAudio},get audioLibraries(){return c.audioLibraries}};return h=Q,Q},async unlockAudio(){await c.unlockAudio()},destroy(){m||(m=!0,h?.destroy(),h=null,x?.disconnect(),x=null,v?.dispose(),f.close(),c.destroy())}}}var he="cyberart.state.save",ye="cyberart.state.load";function pr(e,t,n={}){let r=n.persist,i=r?{persist:r}:void 0,a=()=>{t.emit({type:he,payload:i})},s=()=>{t.emit({type:ye,payload:i})};e.registerAction("w",a,!0),e.registerAction("W",a,!0),e.registerAction("e",s,!0),e.registerAction("E",s,!0)}function cn(e){if(e.type!==he&&e.type!==ye)return;let t=e.payload?.persist;return t==="localStorage"?t:void 0}var fr="cyberart-io",mr=1,ne="framebuffers";function mt(e,t){return`${e||"unknown"}:${t?ee(t):"none"}`}function pn(e,t){return`${e||"unknown"}:${t||"none"}`}function ht(){return new Promise((e,t)=>{let n=indexedDB.open(fr,mr);n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(ne)||r.createObjectStore(ne)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error??new Error("indexedDB open failed"))})}function hr(e){let t=e.data;return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function ln(e,t){return new Promise((n,r)=>{let a=e.transaction(ne,"readonly").objectStore(ne).get(t);a.onsuccess=()=>n(a.result),a.onerror=()=>r(a.error??new Error("indexedDB read failed"))})}async function fn(e,t,n){if(typeof indexedDB>"u")return;let r=await ht(),i={width:n.width,height:n.height,data:hr(n)};try{await new Promise((a,s)=>{let u=r.transaction(ne,"readwrite");u.oncomplete=()=>a(),u.onerror=()=>s(u.error??new Error("indexedDB write failed")),u.objectStore(ne).put(i,mt(e,t))})}finally{r.close()}}async function mn(e,t){if(typeof indexedDB>"u")return null;let n=await ht();try{let r=mt(e,t),i=pn(e,t),a=await ln(n,r)??(r===i?void 0:await ln(n,i));if(!a||!a.data||a.width<1||a.height<1)return null;let s=new ImageData(a.width,a.height);return s.data.set(new Uint8ClampedArray(a.data)),s}finally{n.close()}}async function hn(e,t){if(typeof indexedDB>"u")return;let n=await ht();try{await new Promise((r,i)=>{let a=n.transaction(ne,"readwrite");a.oncomplete=()=>r(),a.onerror=()=>i(a.error??new Error("indexedDB delete failed"));let s=a.objectStore(ne);s.delete(mt(e,t)),s.delete(pn(e,t))})}finally{n.close()}}var yt="cyberart.state.",yr="Saved state",gr="Loaded state",br="Failed to save state",vr="Failed to load state",Er="No saved state";function re(e,t){let n=e||"unknown";return t?yt+n+"."+ee(t):yt+n}function Ar(e,t,n){return r=>{if(cn(r)==="localStorage"){if(r.type===he){wr(e,t,n);return}r.type===ye&&Sr(e,t,n)}}}function ge(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(typeof n.savedAt=="number"&&n.bundle&&typeof n.bundle=="object")return{savedAt:n.savedAt,bundle:n.bundle};let r=t;return typeof r.seed=="string"&&typeof r.version=="number"?{savedAt:0,bundle:r}:null}catch{return null}}async function wr(e,t,n){let r=e();if(r)try{let i=await r.exportState(),a=i.cartId??t?.();i.generative===!0?(Dr(a),ze(re(a,i.seed),i)):ze(re(a),i);let s=r.peekExportedFramebuffer?.();if(s)try{await fn(a,i.seed,s)}catch(u){console.warn("Failed to save cart framebuffer",u)}n?.(yr,"transient")}catch(i){console.error("Failed to save cart state",i),n?.(br,"transient")}}async function Sr(e,t,n){let r=e();if(!r)return;let i=t?.(),a=r.peekSeed?.(),s=r.isGenerative?.()===!0,u=xr(i,s,a);if(!u){console.warn("No saved cart state for",i||"unknown",s&&a?`(hash ${a})`:""),n?.(Er,"transient");return}try{let f=await mn(i,u.bundle.seed).catch(()=>null);await r.importState(u.bundle,{framebuffer:f}),n?.(gr,"transient")}catch(f){console.error("Failed to load cart state",f),n?.(vr,"transient")}}function ze(e,t){let n=JSON.stringify({savedAt:Date.now(),bundle:t});Cr(e,n)}function Cr(e,t){for(;;)try{localStorage.setItem(e,t);return}catch(n){if(!kr(n)||!Pr(e))throw n}}function kr(e){if(!e||typeof e!="object")return!1;let t=e.name,n=e.code;return t==="QuotaExceededError"||t==="NS_ERROR_DOM_QUOTA_REACHED"||n===22||n===1014}function Pr(e){let t=null,n=1/0;for(let a of Tr()){if(a===e)continue;let s=localStorage.getItem(a);if(!s)continue;let f=ge(s)?.savedAt??0;f<n&&(n=f,t=a)}if(!t)return!1;let r=localStorage.getItem(t),i=r?ge(r):null;return localStorage.removeItem(t),i?.bundle&&hn(i.bundle.cartId,i.bundle.seed).catch(()=>{}),!0}function Tr(){let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&n.startsWith(yt)&&e.push(n)}return e}function xr(e,t,n){if(t&&n){let i=localStorage.getItem(re(e,n));if(i)return ge(i);let a=localStorage.getItem(re(e));if(!a)return null;let s=ge(a);if(!s||!Rr(s.bundle,n))return null;try{ze(re(e,n),s.bundle)}catch{}return s}let r=localStorage.getItem(re(e));return r?ge(r):null}function Rr(e,t){return typeof e.seed=="string"&&ee(e.seed)===ee(t)}function Dr(e){let t=re(e),n=localStorage.getItem(t);if(!n)return;let r=ge(n);if(r&&typeof r.bundle.seed=="string"){let i=re(e,r.bundle.seed);if(!localStorage.getItem(i))try{ze(i,r.bundle)}catch{return}}localStorage.removeItem(t)}var De=1,Ie="cyberart.diagnostic.rejected",Ge=8,Ir=new Set(["intent","state","diagnostic"]),Mr=new Set([he,ye]);function qe(e){return typeof e=="string"&&Ir.has(e)}function yn(e){if(e.kind!==void 0)return qe(e.kind)?e.kind:void 0;if(!(typeof e.type!="string"||e.type.length===0)){if(Mr.has(e.type))return"intent";for(let t of e.type.split("."))if(qe(t))return t}}function gn(e,t){let n=e.split("."),r=t.split(".");if(n.length!==r.length)return!1;for(let i=0;i<n.length;i++)if(n[i]!=="*"&&n[i]!==r[i])return!1;return!0}function ie(e,t){for(let n of e)if(gn(n,t))return!0;return!1}function be(e){if(e===void 0)return{ok:!0,value:void 0};try{return{ok:!0,value:JSON.parse(JSON.stringify(e))}}catch{return{ok:!1}}}function Ye(e,t){if(!e||typeof e.type!="string"||e.type.length===0)return{ok:!1,reason:"malformed",detail:"type is required"};if(e.schemaVersion!==void 0&&e.schemaVersion!==De)return{ok:!1,reason:"malformed",detail:`unsupported schemaVersion ${String(e.schemaVersion)}`};let n=yn(e);if(!n)return{ok:!1,reason:"malformed",detail:`cannot infer kind from type "${e.type}"`};let r=be(e.payload);if(!r.ok)return{ok:!1,reason:"malformed",detail:"payload is not JSON-serializable"};let i=t.createId(),a=typeof e.correlationId=="string"&&e.correlationId.length>0?e.correlationId:i,s=typeof e.causationId=="string"&&e.causationId.length>0?e.causationId:t.causationId,u=typeof e.target=="string"&&e.target.length>0?e.target:void 0,f=t.maxHops??Ge,v=t.parentHops===void 0?f:Math.max(0,t.parentHops-1),m=typeof e.idempotencyKey=="string"&&e.idempotencyKey.length>0?e.idempotencyKey:void 0,h={schemaVersion:De,type:e.type,kind:n,source:t.source,id:i,correlationId:a,seq:t.seq,hops:v};return u&&(h.target=u),s&&(h.causationId=s),m&&(h.idempotencyKey=m),r.value!==void 0&&(h.payload=r.value),{ok:!0,envelope:h}}var Fr=new Set(["rate-limited","storm-detected","hop-limit","loop-detected","not-subscribed"]),_r=8,Or=8,Lr=16,Vr=256,Nr=["*.intent.*"];function Hr(e={}){let t=e.hostSource??"host",n="router",r=e.maxPerTurn??_r,i=e.maxCausationDepth??Or,a=e.maxHops??Ge,s=e.maxCorrelationPerTurn??Lr,u=e.maxIndex??Vr,f=e.maxPerWindow,v=e.windowMs??1e3,m=e.now??Date.now,h=0,S=e.createId??(()=>`evt-${++h}`),E=new Map,N=[],l=new Map,c=new Map,D=new Map,x=0,q=0,I=[],L=!1;function G(d,p,A){for(d.set(p,A);d.size>u;){let w=d.keys().next().value;if(w===void 0)break;d.delete(w)}}function P(d){G(l,d.id,{type:d.type,source:d.source,causationId:d.causationId,hops:d.hops,correlationId:d.correlationId,idempotencyKey:d.idempotencyKey})}function Q(d,p){p&&(d.correlationId||(d.correlationId=p.correlationId),d.causationId||(d.causationId=p.id),!d.idempotencyKey&&p.idempotencyKey&&(d.idempotencyKey=`${p.idempotencyKey}::${d.type}`))}function _(d,p){if(d){let A=l.get(d);return A?A.hops:a}return p}function oe(d,p){return`${d}\0${p}`}function Ee(d,p){d.idempotencyKey&&G(D,oe(d.source,d.idempotencyKey),p)}function Ae(d,p){if(p)return D.get(oe(d,p))}function o(d){return Ae(d.source,d.idempotencyKey)}function g(d){return d.seq+=1,d.seq}function b(d,p){if(!(typeof p.causationId=="string"&&p.causationId.length>0))return d.lastDelivered}function k(d){let p=new Set,A=new Set([`${d.type}\0${d.source}`]),w=d.causationId,y=0;for(;w;){if(y+=1,y>i||p.has(w))return!0;p.add(w);let V=l.get(w);if(!V)break;let U=`${V.type}\0${V.source}`;if(A.has(U))return!0;A.add(U),w=V.causationId}return!1}function H(d){let p=(c.get(d)??0)+1;return c.set(d,p),p}function R(d,p){f!==void 0&&(d.emitTimestamps=d.emitTimestamps.filter(A=>p-A<v))}function T(d,p){return(p.kind==="state"||p.kind==="diagnostic")&&!d.authoritative?!1:ie(d.emit,p.type)}function C(d){for(let p of N)if(ie(p.patterns,d.type))try{p.listener(d)}catch{}}function M(d){if(d.target){let p=E.get(d.target);if(!p||!ie(p.subscribe,d.type))return;p.channel.dispatch(d),p.lastDelivered={id:d.id,hops:d.hops,correlationId:d.correlationId,idempotencyKey:d.idempotencyKey};return}for(let p of E.values())ie(p.subscribe,d.type)&&(p.channel.dispatch(d),p.lastDelivered={id:d.id,hops:d.hops,correlationId:d.correlationId,idempotencyKey:d.idempotencyKey})}function Y(d,p,A,w,y,V,U){let z={reason:w,eventType:p,source:A};y&&(z.detail=y),q+=1;let we=S(),se={schemaVersion:De,type:Ie,kind:"diagnostic",source:n,id:we,correlationId:V??we,seq:q,hops:0,payload:z};U&&(se.causationId=U),P(se);let Tt=E.get(d);Tt&&Tt.channel.dispatch(se),C(se)}function O(d,p,A,w,y){Y(d,y?.type??(typeof p.type=="string"?p.type:""),y?.source??d,A,w,y?.correlationId,y?.id),y?.idempotencyKey&&!Fr.has(A)&&Ee(y,{status:"rejected"})}function J(d){P(d),Ee(d,{status:"accepted",envelope:d}),H(d.correlationId),C(d),M(d)}function Z(d,p,A,w){if(!A.ok){O(d,p,"malformed",A.detail);return}let y=A.envelope,V=o(y);if(V)return V.status==="accepted"?V.envelope:void 0;if(y.hops<1){O(d,p,"hop-limit","no hops remaining",y);return}if(y.target&&y.target!==t){let U=E.get(y.target);if(!U){O(d,p,"unknown-target",`unknown target "${y.target}"`,y);return}if(!ie(U.subscribe,y.type)){O(d,p,"not-subscribed",`target "${y.target}" does not subscribe to ${y.type}`,y);return}}if(w){if(!T(w,y)){O(d,p,"unauthorized","source may not emit this event",y);return}if(w.emitsThisTurn+=1,w.emitsThisTurn>r){O(d,p,"rate-limited","maxPerTurn exceeded",y);return}if(f!==void 0){let z=m();if(R(w,z),w.emitTimestamps.push(z),w.emitTimestamps.length>f){O(d,p,"rate-limited","maxPerWindow exceeded",y);return}}if(k(y)){O(d,p,"loop-detected","causation chain cycle or depth exceeded",y);return}if((c.get(y.correlationId)??0)+1>s){O(d,p,"storm-detected","correlationId storm",y);return}if(e.validate){let z;try{z=e.validate(y)}catch(we){let se=we instanceof Error?we.message:"validate threw";O(d,p,"host-rejected",se,y);return}if(z!==!0){O(d,p,"host-rejected",z.detail,y);return}}}else{if(k(y)){O(d,p,"loop-detected","causation chain cycle or depth exceeded",y);return}if((c.get(y.correlationId)??0)+1>s){O(d,p,"storm-detected","correlationId storm",y);return}}return J(y),y}function et(d,p){let A=E.get(d);if(!A)return;let w={...p},y=b(A,w);if(Q(w,y),Ae(A.id,w.idempotencyKey))return;let U=g(A),z=Ye(w,{source:A.id,createId:S,seq:U,causationId:y?.id,maxHops:a,parentHops:_(w.causationId??y?.id,y?.hops)});Z(d,w,z,A)}function Dn(d,p){let A=p?.cause,w={...d};Q(w,A);let y=Ae(t,w.idempotencyKey);if(y)return y.status==="accepted"?y.envelope:void 0;x+=1;let V=Ye(w,{source:t,createId:S,seq:x,causationId:w.causationId,maxHops:a,parentHops:_(w.causationId,A?.hops)});return Z(t,w,V,void 0)}function In(){if(!L){L=!0;try{for(;I.length>0;){let d=I.shift();d&&(d.kind==="cart"?et(d.participantId,d.event):d.result=Dn(d.event,d.extras))}}finally{L=!1}}}function Pt(d){I.push(d),In()}return{attach(d,p,A={}){if(d===t||d===n)throw new Error(`createEventRouter: "${d}" is a reserved participant id`);for(let V of E.values())if(V.channel===p&&V.id!==d)throw new Error(`createEventRouter: channel already attached as "${V.id}"`);E.get(d)?.unsubscribe();let y={id:d,channel:p,emit:A.emit??Nr,subscribe:A.subscribe??[],authoritative:A.authoritative===!0,seq:0,emitsThisTurn:0,emitTimestamps:[],unsubscribe:()=>{}};y.unsubscribe=p.onEvent(V=>{Pt({kind:"cart",participantId:d,event:V})}),E.set(d,y)},detach(d){let p=E.get(d);p&&(p.unsubscribe(),E.delete(d))},publish(d,p){let A={kind:"publish",event:d,extras:p};return Pt(A),A.result},subscribe(d,p){let A={patterns:d,listener:p};return N.push(A),()=>{let w=N.indexOf(A);w>=0&&N.splice(w,1)}},turn(){c.clear();for(let d of E.values())d.emitsThisTurn=0,d.lastDelivered=void 0,f!==void 0&&R(d,m())}}}var Kr=new Set(["string","number","boolean","object","array"]);function K(e,t,n){return n?{code:e,detail:t,path:n}:{code:e,detail:t}}function bn(e){if(!(typeof e!="string"||e.length===0)){for(let t of e.split("."))if(qe(t))return t}}function vn(e){let t=e.split(".");return t.length===0?"*":(t[t.length-1]="*",t.join("."))}function gt(e){let t=[];if(!e||typeof e!="object")return[K("invalid-schema","payload schema is required")];if((typeof e.version!="number"||!Number.isInteger(e.version)||e.version<1)&&t.push(K("invalid-version","payload schema version must be an integer >= 1")),!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return t.push(K("invalid-fields","payload schema fields must be an object")),t;for(let[n,r]of Object.entries(e.fields)){if(!n){t.push(K("invalid-field","field name is required",n));continue}(!r||typeof r!="object"||!Kr.has(r.type))&&t.push(K("invalid-field-type",`field "${n}" type must be string | number | boolean | object | array`,n))}return t}function $r(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e=="string"?"string":typeof e=="number"&&Number.isFinite(e)?"number":typeof e=="boolean"?"boolean":typeof e=="object"?"object":"other"}function jr(e,t){if(t===void 0){let i=Object.entries(e.fields).filter(([,a])=>a.optional!==!0);return i.length===0?{ok:!0,payload:void 0}:{ok:!1,errors:i.map(([a])=>K("missing-field",`payload is missing required field "${a}"`,a))}}if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,errors:[K("invalid-payload","payload must be a JSON object")]};let n=t,r=[];for(let[i,a]of Object.entries(e.fields)){if(!(i in n)||n[i]===void 0){a.optional!==!0&&r.push(K("missing-field",`payload is missing required field "${i}"`,i));continue}let s=$r(n[i]);s!==a.type&&r.push(K("field-type",`payload.${i} expected ${a.type}, got ${s}`,i))}return r.length>0?{ok:!1,errors:r}:{ok:!0,payload:t}}function Ur(e,t,n){let r=vn(e);return{type:e,kind:t,payloadSchema:{version:n.version,fields:{...n.fields}},emitPattern:r,subscribePattern:r,toManifest(){let i={};for(let[a,s]of Object.entries(this.payloadSchema.fields))i[a]={type:s.type,optional:s.optional===!0};return{type:this.type,kind:this.kind,version:this.payloadSchema.version,fields:i,emitPattern:this.emitPattern,subscribePattern:this.subscribePattern}},validatePayload(i){return jr(this.payloadSchema,i)}}}function bt(e,t,n){let r=[];if(typeof t!="string"||t.length===0)r.push(K("invalid-type","event type is required"));else if(t.split(".").some(i=>i.length===0))r.push(K("invalid-type",`event type "${t}" has empty dotted segments`));else{let i=bn(t);i?i!==e&&r.push(K("kind-mismatch",`type "${t}" infers kind "${i}" but this helper defines "${e}"`)):r.push(K("kind-mismatch",`type "${t}" has no "${e}" segment; Adventure-style names like adventure.presentation.* need e.g. adventure.presentation.${e}.cue-started`))}return r.push(...gt(n)),r.length>0?{ok:!1,errors:r}:{ok:!0,contract:Ur(t,e,n)}}function Br(e,t){return bt("intent",e,t)}function Wr(e,t){return bt("state",e,t)}function zr(e,t){return bt("diagnostic",e,t)}function qr(e,t){let n=gt(e),r=gt(t);if(n.length>0||r.length>0||t.version<e.version)return"breaking";let i=Object.keys(e.fields),a=Object.keys(t.fields),s=new Set(i),u=new Set(a);for(let m of i){if(!u.has(m))return"breaking";let h=e.fields[m],S=t.fields[m];if(h.type!==S.type)return"breaking";let E=h.optional!==!0,N=S.optional===!0;if(E&&N||!E&&S.optional!==!0&&h.optional===!0)return"breaking"}let f=!1;for(let m of a)if(!s.has(m)){if(t.fields[m].optional!==!0)return"breaking";f=!0}let v=i.length===a.length&&i.every(m=>t.fields[m].type===e.fields[m].type&&t.fields[m].optional===!0==(e.fields[m].optional===!0));return v&&t.version===e.version?"identical":t.version>e.version&&(f||v)?"backward-compatible":t.version===e.version&&f?"breaking":v?"identical":"breaking"}function Gr(e,t){let n=[],r=[],i=new Set,a=new Set;for(let s of e)(t==="authoritative"||s.kind==="intent")&&!i.has(s.emitPattern)&&(i.add(s.emitPattern),n.push(s.emitPattern)),s.kind!=="intent"&&!a.has(s.subscribePattern)&&(a.add(s.subscribePattern),r.push(s.subscribePattern));return{emit:n,subscribe:r,authoritative:t==="authoritative"}}function Yr(e,t){let n=e.emit??["*.intent.*"],r=e.authoritative===!0,i=[];for(let a of t)ie(n,a.type)&&(a.kind==="state"||a.kind==="diagnostic")&&!r&&i.push(K("unauthorized-emit",`emit pattern allows ${a.kind} "${a.type}" but attach is not authoritative`,a.type));return i.length>0?{ok:!1,errors:i}:{ok:!0}}function Jr(e){let t=new Map;for(let i of e)t.set(i.type,i);let n=i=>{let a=t.get(i.type);return a?a.kind!==i.kind?{ok:!1,errors:[K("kind-mismatch",`envelope kind "${i.kind}" does not match contract "${a.kind}"`,i.type)]}:a.validatePayload(i.payload):{ok:!1,errors:[K("unknown-type",`no contract registered for "${i.type}"`,i.type)]}};return{get(i){return t.get(i)},manifest(){return[...t.values()].sort((i,a)=>i.type.localeCompare(a.type)).map(i=>i.toManifest())},validateEnvelope:n,asRouterValidate:i=>{let a=n(i);return a.ok?!0:{reason:"host-rejected",detail:a.errors.map(s=>s.detail).join("; ")}}}}var ve=1,Et="presentation.state.model",An="presentation.intent.unsupported",wn=["loading","ready","error","unsupported"],Xr=["presentation.state.*",Ie],Qr="Presentation adapter has been destroyed",Sn="Presentation adapter: model is invalid or not JSON-serializable",Zr=new Set(wn);function Cn(e){return typeof e=="string"&&Zr.has(e)}function At(e){if(e===null||typeof e!="object")return!1;let t=e;return!(t.contractVersion!==ve||!Cn(t.phase)||t.reason!==void 0&&typeof t.reason!="string"||t.view!==void 0&&(t.view===null||typeof t.view!="object"))}function vt(e,t){let n={type:Et,kind:"state",payload:e};return t?.correlationId&&(n.correlationId=t.correlationId),t?.causationId&&(n.causationId=t.causationId),t?.idempotencyKey&&(n.idempotencyKey=t.idempotencyKey),n}function wt(){return{contractVersion:ve,phase:"loading"}}function St(e){return{contractVersion:ve,phase:"unsupported",reason:e}}function Ct(e){let t=be(e);return t.ok?At(t.value)?{ok:!0,model:t.value}:t.value!==null&&typeof t.value=="object"&&"contractVersion"in t.value&&t.value.contractVersion!==ve?{ok:!1,reason:"unknown-contract-version",contractVersion:t.value.contractVersion}:{ok:!1,reason:"invalid-model"}:{ok:!1,reason:"model-not-serializable"}}function Je(e){let t=Ct(e);if(!t.ok)throw new Error(Sn);return t.model}function ei(e){let t=be(e);return t.ok&&At(t.value)?t.value:St("model-not-serializable")}function ti(e,t){if(e.type!==Et)return{model:t};let n=Ct(e.payload);return n.ok?{model:n.model}:{model:St(n.reason),rejected:{reason:n.reason,contractVersion:n.contractVersion}}}function ni(e){if(e===null||typeof e!="object"||!("regions"in e))return[];let t=e.regions;return Array.isArray(t)?t:[]}function ri(e,t,n){return e>=n.x&&e<n.x+n.width&&t>=n.y&&t<n.y+n.height}function ii(e,t){let n=t.intent;if(!n||typeof n.type!="string"||n.type.length===0)return;let r={type:n.type,kind:"intent"};if(n.payload!==void 0){let i=be(n.payload);if(!i.ok)return;r.payload=i.value}n.target&&(r.target=n.target),n.correlationId&&(r.correlationId=n.correlationId),n.idempotencyKey&&(r.idempotencyKey=n.idempotencyKey),e.emit(r)}function kn(e,t,n){let r={reason:t};if(n!==void 0){let i=be(n);i.ok&&(r.contractVersion=i.value)}e.emit({type:An,kind:"intent",payload:r})}function En(e,t,n){let r=t;for(let i of e){let a=ti(i,r);a.rejected&&n&&kn(n,a.rejected.reason,a.rejected.contractVersion),r=a.model}return r}function Pn(){return{metadata:{id:"cyberart.presentation.reference",name:"Reference presentation",frameRate:30},getDefaultState:(e,t,n,r,i,a,s,u,f)=>{let v=i?.model;if(v===void 0)return{model:wt()};let m=Ct(v);return m.ok?{model:m.model}:(f&&kn(f,m.reason,m.contractVersion),{model:St(m.reason)})},update:(e,t,n,r,i,a,s,u,f,v,m)=>{let h=En(m?.consume()??[],i.model,m);for(;s?.hasClick();){let S=s.consumeClick();if(!(!S||h.phase!=="ready"||!m)){for(let E of ni(h.view))if(ri(S.x,S.y,E)){ii(m,E);break}}}return m&&(h=En(m.consume(),h,m)),h===i.model?i:{...i,model:h}},render:(e,t,n,r,i,a)=>{let s=i.model.view?.background;a.fillStyle=s??"#111",a.fillRect(0,0,r.width,r.height)}}}function Tn(e,t={}){let n=e,r=t.model?Je(t.model):wt(),i=!1,a=t.present??t.model!==void 0,s=()=>{if(i)throw new Error(Qr)},u=f=>{s(),r=Je(f),n.dispatch(vt(r))};return a&&n.dispatch(vt(r)),{version:ve,get target(){return n},get model(){return ei(r)},get phase(){return r.phase},get paused(){return n.paused===!0},present:u,async start(){return s(),n.start()},pause(){s(),n.pause()},resume(){s(),n.resume()},retarget(f){s(),n=f},destroy(){i||(i=!0,n.destroy())}}}function ai(e,t={}){let n=t.model?Je(t.model):t.initialState?.model!==void 0?Je(t.initialState.model):wt(),r=t.cart??Pn(),i=e.mount(r,{initialState:{...t.initialState,model:n},onEvent:t.onEvent});return Tn(i,{model:n,present:!1})}var Me="cue.started",Qe="cue.completed",Fe="cue.cancelled",Ze="cue.replaced",oi=[Me,Qe,Fe,Ze];function si(e){return e===Me||e===Qe||e===Fe||e===Ze}function Rn(e,t){let n=e<0?0:e>1?1:e;return t==="ease-out"?1-(1-n)*(1-n):n}function xn(e){return{type:e.type,atFrame:e.atFrame,name:e.name,idempotencyKey:e.idempotencyKey,progress:e.progress}}function Xe(e){return{name:e.name,idempotencyKey:e.idempotencyKey,phase:e.phase,startFrame:e.startFrame,durationFrames:e.durationFrames,delayFrames:e.delayFrames,easing:e.easing,progress:e.progress,repeatIndex:e.repeatIndex}}function kt(e){return e.startFrame+e.delayFrames}function di(e,t){if(!e||typeof e!="object")return{ok:!1,reason:"invalid",detail:"spec is required"};if(typeof e.name!="string"||e.name.length===0)return{ok:!1,reason:"invalid",detail:"name is required"};if(typeof e.idempotencyKey!="string"||e.idempotencyKey.length===0)return{ok:!1,reason:"invalid",detail:"idempotencyKey is required"};if(typeof e.durationFrames!="number"||!Number.isFinite(e.durationFrames)||e.durationFrames<0)return{ok:!1,reason:"invalid",detail:"durationFrames must be a non-negative finite number"};let n=e.startFrame===void 0?t:e.startFrame;if(typeof n!="number"||!Number.isFinite(n))return{ok:!1,reason:"invalid",detail:"startFrame must be finite"};let r=e.delayFrames??0;if(typeof r!="number"||!Number.isFinite(r)||r<0)return{ok:!1,reason:"invalid",detail:"delayFrames must be a non-negative finite number"};let i=e.easing??"linear";if(i!=="linear"&&i!=="ease-out")return{ok:!1,reason:"invalid",detail:"unsupported easing"};let a=e.onDuplicate??"replace";if(a!=="ignore"&&a!=="replace"&&a!=="reject")return{ok:!1,reason:"invalid",detail:"unsupported onDuplicate"};let s=0;if(e.repeat)if("forever"in e.repeat&&e.repeat.forever)s="forever";else if("count"in e.repeat){if(typeof e.repeat.count!="number"||!Number.isFinite(e.repeat.count)||e.repeat.count<0)return{ok:!1,reason:"invalid",detail:"repeat.count must be >= 0"};s=Math.floor(e.repeat.count)}else return{ok:!1,reason:"invalid",detail:"unsupported repeat"};let u=e.reducedMotion??"complete";return u!=="skip"&&u!=="complete"&&(typeof u!="object"||typeof u.durationFrames!="number"||!Number.isFinite(u.durationFrames)||u.durationFrames<0)?{ok:!1,reason:"invalid",detail:"unsupported reducedMotion"}:{name:e.name,idempotencyKey:e.idempotencyKey,startFrame:n,durationFrames:e.durationFrames,delayFrames:r,easing:i,repeatRemaining:s,repeatIndex:0,reducedMotion:u,onDuplicate:a,phase:"scheduled",progress:0}}function ui(e,t){if(!t)return e;let n=e.reducedMotion;return n==="skip"||n==="complete"?{...e,durationFrames:0,delayFrames:0,startFrame:e.startFrame}:{...e,durationFrames:n.durationFrames}}function ci(e={}){let t=!!e.reducedMotion,n=e.originFrame??0,r=new Map,i=[];function a(l){i.push(l)}function s(l,c){let D=kt(l)-kt(c);return D!==0?D:l.name<c.name?-1:l.name>c.name?1:l.idempotencyKey<c.idempotencyKey?-1:l.idempotencyKey>c.idempotencyKey?1:0}function u(l,c){a({type:c,atFrame:n,name:l.name,idempotencyKey:l.idempotencyKey,progress:l.progress})}function f(l){if(l.phase="completed",l.progress=1,u(l,Qe),l.repeatRemaining==="forever"||l.repeatRemaining>0){if(typeof l.repeatRemaining=="number"&&(l.repeatRemaining-=1),l.repeatIndex+=1,l.phase="scheduled",l.progress=0,l.startFrame=n,l.delayFrames=0,l.durationFrames===0){r.delete(l.idempotencyKey);return}l.phase="active",u(l,Me)}else r.delete(l.idempotencyKey)}function v(l){if(l.phase==="cancelled"||l.phase==="completed")return;let c=kt(l);if(!(n<c)){if(l.phase==="scheduled"&&(l.phase="active",l.progress=l.durationFrames===0?1:0,u(l,Me),l.durationFrames===0)){f(l);return}if(l.phase==="active"){let D=n-c;D>=l.durationFrames?(l.progress=1,f(l)):l.progress=Rn(l.durationFrames===0?1:D/l.durationFrames,l.easing)}}}function m(){let l=[...r.values()].sort(s);for(let c of l)v(c)}function h(l){let c=di(l,n);if("ok"in c&&c.ok===!1)return c;let D=ui(c,t),x=r.get(D.idempotencyKey);if(x&&(x.phase==="scheduled"||x.phase==="active")){if(x.onDuplicate==="reject"||D.onDuplicate==="reject")return{ok:!1,reason:"duplicate",detail:`cue ${D.idempotencyKey} is already ${x.phase}`};if(x.onDuplicate==="ignore"||D.onDuplicate==="ignore")return{ok:!0,cue:Xe(x)};x.phase="cancelled",x.progress=x.progress,u(x,Ze),r.delete(x.idempotencyKey)}r.set(D.idempotencyKey,D),v(D);let q=r.get(D.idempotencyKey)??D;return{ok:!0,cue:Xe(q)}}function S(l){let c=r.get(l);return!c||c.phase==="completed"||c.phase==="cancelled"?!1:(c.phase="cancelled",u(c,Fe),r.delete(l),!0)}function E(){for(let l of[...r.values()].sort(s))(l.phase==="scheduled"||l.phase==="active")&&(l.phase="cancelled",u(l,Fe));r.clear(),i.length=0,n=e.originFrame??0}function N(l=1){let c=Number.isFinite(l)?Math.max(0,Math.floor(l)):0,D=i.length;for(let x=0;x<c;x++)n+=1,m();return i.slice(D).map(xn)}return{play:h,step:N,cancel:S,reset:E,snapshot(){return{frame:n,reducedMotion:t,cues:[...r.values()].sort(s).map(Xe),events:i.map(xn)}},get(l){let c=r.get(l);return c?Xe(c):void 0},get frame(){return n},get reducedMotion(){return t}}}export{xe as ASSET_FAILED_EVENT,rn as ASSET_FAILURE_CODES,nn as ASSET_KINDS,Te as ASSET_READY_EVENT,Fe as CUE_CANCELLED_EVENT,Qe as CUE_COMPLETED_EVENT,oi as CUE_LIFECYCLE_EVENTS,Ze as CUE_REPLACED_EVENT,Me as CUE_STARTED_EVENT,_e as CYBERART_CANVAS_ATTR,Ge as DEFAULT_MAX_HOPS,De as EVENT_ENVELOPE_VERSION,fe as HostChannel,Sn as INVALID_PRESENTATION_MODEL_MESSAGE,$ as IncompatibleCartStateError,Oe as KeyboardManager,ve as PRESENTATION_ADAPTER_VERSION,Et as PRESENTATION_MODEL_EVENT,wn as PRESENTATION_PHASES,Xr as PRESENTATION_SUBSCRIBE_PATTERNS,An as PRESENTATION_UNSUPPORTED_EVENT,Le as PointerManager,Ie as REJECTED_EVENT_TYPE,Se as Random,me as SILENT_ASSET_FALLBACK_REF,Rn as applyCueEasing,ae as assetStatusEvent,Ar as attachCartStatePersistence,Tn as attachPresentationAdapter,Ke as canonicalizeSeed,qr as comparePayloadSchemas,F as createAssetFailure,ft as createAssetPreloader,Jr as createContractRegistry,Hr as createEventRouter,dr as createFixtureAssetResolver,ur as createHostedAssetResolver,vt as createPresentationModelEvent,ci as createPresentationTimeline,Pn as createReferencePresentationCart,lr as createRuntime,Ve as createVirtualClock,ce as createWallClock,zr as defineDiagnostic,Br as defineIntent,Wr as defineStateEvent,Gr as deriveAttachOptions,Jt as describeReplayMismatch,vn as familyPatternForType,yn as inferEventKind,We as isAssetFailure,on as isAssetFailureCode,an as isAssetKind,si as isCueLifecycleType,At as isPresentationModel,Cn as isPresentationPhase,bn as kindSegmentInType,gn as matchEventPattern,ai as mountPresentationAdapter,Ye as normalizeEvent,pr as registerCartStateHotkeys,$e as resolveRuntimeSeed,un as rewriteHostedAssetRef,Yr as verifyAttachOptions};
8
+ var Jr=(e,t)=>()=>(e&&(t=e(e=0)),t);var oi={};function ii(e,t){let n=e.indexOf(An);if(n===-1)return null;let r=n+An.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 wt,et,ri,Ne,An,Rn=Jr(()=>{"use strict";wt=/AudioWorkletProcessor with name:\s*["'`][^"'`]+["'`]\s+is already registered/i,et="__cyberartWorkletPatchApplied";typeof window<"u"&&!window[et]&&(window.addEventListener("error",e=>{let t=e?.message??"";wt.test(t)&&(e.preventDefault(),e.stopImmediatePropagation())},!0),window.addEventListener("unhandledrejection",e=>{let t=e?.reason,n=typeof t=="string"?t:t?.message??"";wt.test(n)&&e.preventDefault()}),window[et]=!0);ri=!1,Ne=(...e)=>{ri&&console.log("[workletPatch]",...e)},An="((AudioWorkletProcessor,registerProcessor)=>{";if(typeof AudioWorklet<"u"&&!AudioWorklet.prototype[et]){let e=new WeakMap,t=/registerProcessor\s*\(\s*['"`]([^'"`]+)['"`]/g,n=AudioWorklet.prototype.addModule,r=0;AudioWorklet.prototype.addModule=async function(o,a){let s=++r,d=e.get(this);d||(d=new Set,e.set(this,d)),Ne(`#${s} addModule`,{url:o.slice(0,64),isBlob:o.startsWith("blob:"),knownBefore:[...d]});let E=o,g=null;if(o.startsWith("blob:")){let v=null;try{v=await(await fetch(o)).text()}catch(C){Ne(`#${s} blob fetch failed`,C)}if(v!==null){let C=new Set;for(let x of v.matchAll(t))C.add(x[1]);if(C.size>0){let x=[...C].filter(p=>d.has(p)),T=[...C].filter(p=>!d.has(p));if(x.length>0&&T.length===0){Ne(`#${s} short-circuit \u2014 all processors already registered`,x);return}if(x.length>0&&T.length>0){let p=ii(v,x);if(p!==null){let m=new Blob([p],{type:"application/javascript"});g=URL.createObjectURL(m),E=g,Ne(`#${s} rewrote blob; skipping`,x,"allowing",T)}else Ne(`#${s} blob rewrite failed; passing original through`)}T.forEach(p=>d.add(p))}}}return n.call(this,E,a).then(()=>{g&&URL.revokeObjectURL(g)},v=>{g&&URL.revokeObjectURL(g);let C=(v&&v.message)??"";if(!(wt.test(C)||/already registered/i.test(C)))throw v})},AudioWorklet.prototype[et]=!0}});var pn=()=>{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"]},ee=window.devicePixelRatio||1,Ee=/Headless/i.test(navigator.userAgent),Ha=/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)||/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform);function mn(){return Math.min(window.innerWidth,window.innerHeight)}var ze="data-cyberart-canvas",we=class{constructor(t,n,r=1,i={}){this.width=t,this.height=n;let o=i.container,a=i.adoptFromDocument??!o,s=o?o.querySelector(`canvas[${ze}]`)??o.querySelector("canvas"):null;if(s)this.canvas=s,this.adopted=!0;else if(a){let d=document.getElementById("canvas")??document.querySelector("canvas");d?(this.canvas=d,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(ze)||this.canvas.setAttribute(ze,""),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/ee}px`,this.canvas.style.height=`${n/ee}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 fn(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 hn(e,t=window.innerWidth,n=window.innerHeight){let r=mn(),i,o;return n<t?e>1?t>=r*e?(i=r*e,o=r):(i=t,o=i/e):(i=r*e,o=r):e>1?(i=r,o=r/e):n<r/e?(o=n,i=o*e):(i=r,o=r/e),[i,o]}var qe=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={}}},yn=qe;var We=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))}},gn=We;function Ce(){return{now:()=>performance.now()}}function Ye(e=0){let t=e;return{now:()=>t,set(n){t=n},advance(n){t+=n}}}var bn=(e,t,n,r)=>({now:e,startTime:t,elapsedSinceStart:e-t,deltaSinceLastUpdate:n===null?0:e-n,deltaSinceLastRender:r===null?0:e-r}),Je=class{constructor(t,n,r,i,o,a={}){this.startTime=0;this.lastUpdateAt=null;this.lastRenderAt=null;this.clockOffsetMs=0;this.pauseStartedAt=null;this.renderAnimation=this.renderAnimation.bind(this),this.dimensionContext=fn(t,n),this.R=r,this.gameManager=a.gameManager,this.hostChannel=a.hostChannel,this.clock=a.clock??Ce(),this.canvas=new we(this.dimensionContext.width,this.dimensionContext.height,1,a.canvasMount),this.drawingContext=this.canvas.ctx,this.keyboardManager=new yn(!1,a.captureKeyboard??!0),this.pointerManager=new gn(this.canvas.canvas,{listen:a.listenToPointer!==!1}),this.animationCart=o;let s=a.customState;this.featureState=o.getDefaultFeatureState?.(this.R,this.dimensionContext,i,this.keyboardManager,s,this.pointerManager,this.gameManager,this.hostChannel),this.cartState=o.getDefaultState(this.R,this.dimensionContext,i,this.keyboardManager,s,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),o=bn(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,o,this.featureState,this.hostChannel),this.lastUpdateAt=i}async renderAnimation(t,n,r=this.clock.now()){let i=this.resolveNow(r),o=bn(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,o,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 Xe=class extends we{constructor(t,n,r=1,i=!0,o={}){if(super(t,n,r,o),this.adopted)return;let a=o.container;if(a){this.canvas.parentNode!==a&&a.appendChild(this.canvas);return}if(i){let s=document.getElementById("canvas");s&&s!==this.canvas&&s.parentNode===document.body&&document.body.removeChild(s),document.body.appendChild(this.canvas)}}};function vn(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 _e=class{constructor(t){this.seed=t.hash,this.useA=!1,this.genA=vn(t.hash.substring(2,32)),this.genB=vn(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 wn="bafybeicjwcq5lxxtfnyj4p2ugcr7ctyb5wl62cbcechj6tsabdq5whcs7u",En="https://ipfs.io/ipfs/";function Xr(e){return e.endsWith("/")?e:`${e}/`}var Le=null;function Qr(e){return[...Array(e)].map(()=>Math.floor(Math.random()*16).toString(16)).join("")}function Zr(e){return e&&e.length>0?e:[{cid:wn}]}function ei(e){return e.startsWith("0x")?e:`0x${e}`}var Cn=/^(0[xX])?[0-9a-fA-F]{64}$/;function ti(e){let t="",n=2166136261,r=522970236;for(let i=0;t.length<64;i++){for(let o=0;o<e.length;o++)n^=e.charCodeAt(o)+i,n=Math.imul(n,16777619),r^=e.charCodeAt(o)+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 Qe(e){let t=typeof e=="number"?String(e):e;return Cn.test(t)?`0x${(t.startsWith("0x")||t.startsWith("0X")?t.slice(2):t).toLowerCase()}`:ti(t)}function Ze(e,t){if(typeof e=="number"||t==="deterministic")return Qe(e);let n=String(e);return Cn.test(n)?Qe(n):n.startsWith("0x")||n.startsWith("0X")?n:`0x${n}`}function ni(e){if(!e&&typeof tokenData<"u"&&tokenData?.hash)return{hash:tokenData.hash,tokenId:String(tokenData.tokenId),externalAssetDependencies:Zr(tokenData.externalAssetDependencies),preferredIPFSGateway:Xr(tokenData.preferredIPFSGateway||En),preferredArweaveGateway:tokenData.preferredArweaveGateway};let t=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams;return{hash:e?ei(e):t.get("hash")||`0x${Qr(64)}`,tokenId:"18009999",externalAssetDependencies:[{cid:wn}],preferredIPFSGateway:En}}function Et(e){let t=e?.useCache!==!1;if(t&&Le&&!e?.hash)return Le;let n=ni(e?.hash);return t?Le=n:Le||(Le=n),n}function Sn(e){return new Array(32).fill(null).map((t,n)=>parseInt(e.hash.slice(2+n*2,4+n*2),16))}async function Ct(){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 Pn={id:"tone",async load(){await Promise.resolve().then(()=>(Rn(),oi))},async unlock(){await Pn.load(),await(await Ct()).start()},async resumeIfSuspended(){let e=await Ct();e.context.state==="suspended"&&await e.context.resume()},async suspendIfRunning(){let t=(await Ct()).context.rawContext;"suspend"in t&&t.state==="running"&&await t.suspend()}},xn={tone:Pn};function St(e){if(!e)return[];let t=Array.isArray(e)?e:[e],n=[];for(let r of t){if(!(r in xn)){console.warn(`Unknown audio library "${r}"`);continue}let i=r;n.includes(i)||n.push(i)}return n}function At(e){return e.map(t=>xn[t])}var tt="$cyberartTa",Q=class extends Error{constructor(t){super(t),this.name="IncompatibleCartStateError"}},Rt={Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array};function ai(e){for(let t of Object.keys(Rt))if(e instanceof Rt[t])return t}function kn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function re(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Pt(e){return re(e)?typeof e[tt]=="string"&&Array.isArray(e.d):!1}function si(e){return e==null?!1:typeof e=="function"?!0:!(typeof e!="object"||Array.isArray(e)||kn(e)||re(e))}var ci=new Set(["audioContextStarted","midiSynths","keepRatioPrimed","audioInitStarted","musicSeekApplied"]);function Tn(e){return e===null?"null":Pt(e)?String(e[tt]):Array.isArray(e)?"array":re(e)?"object":typeof e}function di(e,t){return e===t||e==="null"||t==="null"}function ue(e){return e.trim().toLowerCase().replace(/^0x/,"")}function In(e,t,n,r){if(!(!n&&!r)&&ue(e)!==ue(t))throw new Q(`Generative cart state is for seed "${t}", but the live token is "${e}"`)}function Se(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Mn(e,t){let n=e.dimensions;if(n&&Se(n.width)&&Se(n.height))return n;if(t&&Se(t.width)&&Se(t.height))return{width:t.width,height:t.height};if(re(e.state)){let r=e.state.containerWidth,i=e.state.containerHeight;if(Se(r)&&Se(i))return{width:r,height:i}}return null}function Ae(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(kn(e)){let n=ai(e);return n?{[tt]:n,d:Array.from(e)}:void 0}if(typeof e=="object"&&!t.has(e)){t.add(e);try{if(Array.isArray(e)){let i=[],o=0;for(let a of e){let s=Ae(a,t);s!==void 0&&(i.push(s),o++)}return e.length>0&&o===0?void 0:i}if(!re(e)||si(e))return;let n=Object.keys(e),r={};for(let i of n){if(ci.has(i))continue;let o=Ae(e[i],t);o!==void 0&&(r[i]=o)}return n.length>0&&Object.keys(r).length===0?void 0:r}finally{t.delete(e)}}}}function Fe(e){if(Pt(e)){let t=Rt[e[tt]];return t?new t(e.d.map(n=>Number(n))):e}if(Array.isArray(e))return e.map(t=>Fe(t));if(re(e)){let t={};for(let n of Object.keys(e))t[n]=Fe(e[n]);return t}return e}function xt(e,t,n,r,i=!0){if(i&&n&&r&&n!==r)throw new Q(`Cart state is for "${r}", but the live cart is "${n}"`);if(!re(t)){if(i)throw new Q("Cart state snapshot is empty");return}let o=Object.keys(t);if(o.length===0){if(i)throw new Q("Cart state snapshot is empty");return}let a=Ae(e);if(!re(a)||Object.keys(a).length===0){if(i)throw new Q("Live cart has no serializable state");return}let s=o.filter(d=>d in a);if(s.length===0){if(i)throw new Q("Cart state snapshot does not overlap the live cart shape");return}for(let d of s){let E=Tn(a[d]),g=Tn(t[d]);if(!di(E,g))throw new Q(`Cart state field "${d}" has type ${g}, live cart expects ${E}`);if(E==="object"){let v=t[d],C=e[d];re(v)&&!Pt(v)&&xt(C,v,void 0,void 0,!1)}}}function Dn(e,t){if(!re(e)||!re(t))return;let n=Ae(e);if(re(n))for(let r of Object.keys(t))r in n&&(e[r]=Fe(t[r]))}function On(e){let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object")throw new Q("Cart state bundle is not an object");if(t.version!==1)throw new Q(`Unsupported cart state version ${String(t.version)}`);if(typeof t.seed!="string"||typeof t.framesElapsed!="number")throw new Q("Cart state bundle is missing seed or framesElapsed");return t}var ye="cyberart.asset.ready",ge="cyberart.asset.failed";function le(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function ie(e){try{return JSON.stringify(e)}catch{return String(e)}}function Tt(e,t,n){let r=t??[],i=n??[],o=Math.max(r.length,i.length);for(let a=0;a<o;a++)if(ie(r[a])!==ie(i[a]))return`${e}[${a}]: ${ie(r[a])} vs ${ie(i[a])}`}function _n(e,t){let n=[];e.seed!==t.seed&&n.push(`seed: ${e.seed} vs ${t.seed}`),e.clock.framesElapsed!==t.clock.framesElapsed&&n.push(`framesElapsed: ${e.clock.framesElapsed} vs ${t.clock.framesElapsed}`),e.clock.now!==t.clock.now&&n.push(`now: ${e.clock.now} vs ${t.clock.now}`),e.clock.frameRate!==t.clock.frameRate&&n.push(`frameRate: ${e.clock.frameRate} vs ${t.clock.frameRate}`),ie(e.rng)!==ie(t.rng)&&n.push(`rng: ${ie(e.rng)} vs ${ie(t.rng)}`);let r=Tt("actions",e.actions,t.actions);r&&n.push(r);let i=Tt("applied",e.applied,t.applied);i&&n.push(i);let o=Tt("events",e.events,t.events);return o&&n.push(o),ie(e.state)!==ie(t.state)&&n.push(`state: ${ie(e.state)} vs ${ie(t.state)}`),n}function Ln(e){return{type:e.status==="ready"?ye:ge,kind:"state",payload:e.detail===void 0?{id:e.id}:{id:e.id,detail:e.detail}}}function li(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 pi(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),o=Math.max(0,window.outerHeight-window.innerHeight);try{window.resizeTo(n+i,r+o)}catch{return!1}return Math.abs(window.innerWidth-n)<=8&&Math.abs(window.innerHeight-r)<=8}var mi=[[0,0],[16,9],[9,16],[4,3],[3,4],[2,1],[1,2],[3,1],[1,3],[1,1]],It=mi[0],fi=It[0]/It[1],kt=30,hi=120,yi=3840/2160,gi=2160/3840,nt=class{constructor(t=kt,n=!1,r=window.innerWidth,i=window.innerHeight,o=!0,a,s={}){this.framesElapsed=0;this.frameRate=kt;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=s.container,this.seed=s.seed,this.captureKeyboard=s.captureKeyboard??!0,this.customState=s.customState,this.hostChannel=s.hostChannel,this.fallbackAudio=St(s.audio),this.audioLibrariesInternal=this.fallbackAudio;let d=s.deterministic;this.deterministic=!!d;let E=d&&typeof d=="object"?d:{};if(this.deterministic){if(s.clock){let g=s.clock;if(typeof g.advance!="function")throw new Error("deterministic mode requires a virtual clock with advance()");this.virtualClock=g,this.clock=g}else this.virtualClock=Ye(E.origin??0),this.clock=this.virtualClock;this.initialScriptedActions=le(E.actions??[]),this.scriptedActions=le(this.initialScriptedActions)}else this.clock=s.clock??Ce();this.isBodyCanvas=this.container?!1:o,this.autoMode=n,this.aspectRatio=fi,this.selectedAsp=It,this.isFullscreen=!!document.fullscreenElement,this.updateFrameRate(t),this.tempUnpause=!1,this.synchronous=Ee,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?Et({hash:this.seed,useCache:!1}):Et(),this.rawParams=Sn(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]=hn(n,this.containerWidth,this.containerHeight);r*=ee,i*=ee,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 Xe(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 _e(this.tokenData),o=new Je(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=o,this.animationCart=t,this.paused=!1,this.framesElapsed=0,this.outboundEvents=[],this.scriptedActions=le(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,o),this.resolveAudioLibraries(t),this.prepared=!0,!0}catch(n){return console.error(n),!1}}applyCartFrameRate(t,n){let r=t.metadata,i=r?.frameRate??kt,o=n.cartState?.visualMode??n.featureState?.visualMode,a=o&&r?.frameRateByVisualMode?r.frameRateByVisualMode[o]: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=St(t.metadata?.audio)}async unlockAudio(){if(this.audioLibrariesInternal.length===0)return;let t=At(this.audioLibrariesInternal);if(Ee){for(let n of t)await n.load();return}for(let n of t)await n.unlock()}async resumeAudioLibraries(){if(!(this.paused||Ee))for(let t of At(this.audioLibrariesInternal))try{await t.resumeIfSuspended()}catch(n){console.error(`Failed to resume audio library "${t.id}" after reload`,n)}}beginPlayback(){!this.prepared||this.loopRunning||(this.prepared=!1,this.loopRunning=!0,this.consecutiveErrorCount=0,!this.deterministic&&(this.requestedAnimationFrame=requestAnimationFrame(this.drawLoop)))}get isPrepared(){return this.prepared}get isLoopRunning(){return this.loopRunning}get isDeterministic(){return this.deterministic}getClock(){return{now:this.clock.now(),framesElapsed:this.framesElapsed,frameRate:this.frameRate}}getRandomState(){return this.requirePreparedAnimation().getRandomState()}schedule(t){this.scriptedActions.push(le(t))}async getReplayMetadata(){let t=await this.exportState();return{seed:this.tokenData.hash,clock:this.getClock(),rng:this.getRandomState(),actions:le(this.scriptedActions),applied:le(this.appliedActions),events:le(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(Ln(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:ee},state:Ae(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=On(t),o=this._paused,a=this.loopRunning;this.paused=!0,await this.waitUntilUpdateIdle(),xt(r.cartState,i.state,this.animationCart?.metadata?.id,i.cartId),In(this.tokenData.hash,i.seed,this.animationCart?.metadata?.generative,i.generative),clearTimeout(this.reinitTimeout),this.reinitPending=!1,this.importing=!0;let s=Mn(i,n?.framebuffer??this.lastExportedFramebuffer);if(s){this.pinOutputSize(s);let g=s.cssWidth??s.width/ee,v=s.cssHeight??s.height/ee;pi(g,v),this.syncContainerFromDom(),this.pinViewportAtImport={w:this.containerWidth,h:this.containerHeight}}let d=this.customState,E=!1;try{if(this.customState=Fe(i.state),this.unloadCart(),!this.prepareCart(this.animationCart))throw new Error("Failed to prepare cart while loading state");this.animation.cartState!==this.customState&&Dn(this.animation.cartState,i.state),this.framesElapsed=i.framesElapsed;let g=this.animation,v=g.cartState,C=typeof i.elapsedSinceStart=="number"?i.elapsedSinceStart:li(v);g.restoreClock(C,typeof v?.startTime=="number"?v.startTime:void 0),o&&g.setPaused(!0);let x=n?.framebuffer??this.lastExportedFramebuffer;x&&g.restoreFramebuffer(x)?v.keepRatioPrimed=!0:await g.renderAnimation(this.framesElapsed,this.rawParams),this.fitPinnedCanvas(),E=!0}catch(g){throw this.clearPinnedOutput(),this.customState=d,this.paused=o,this.animationCart&&(this.syncContainerFromDom(),this.init(),this.reloadCart()),g}finally{this.importing=!1,E&&(this.customState=d,this.paused=o,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&&!Ee&&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/ee,h:t.cssHeight??t.height/ee}}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,o=t.width/ee,a=t.height/ee;if(o<1||a<1||r<1||i<1)return;let s=Math.min(r/o,i/a),d=o*s,E=a*s;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=`${d}px`,n.style.height=`${E}px`,n.style.imageRendering=Math.abs(s-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 o=!1,a,s="update";try{if(r||!this.paused||this.tempUnpause){if(!Ee&&!r&&this.tuneFramerate(t),!this.animation)return;if(s="update",this.updateInProgress=!0,await this.animation.updateAnimationState(this.framesElapsed,this.rawParams,t),this.updateInProgress=!1,s="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 g=localStorage.getItem("goodones"),v=JSON.stringify(g?[...JSON.parse(g),this.tokenData.hash]:[this.tokenData.hash]);localStorage.setItem("goodones",v),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)}s="draw",this.drawIt()}catch(d){o=!0,a=d,this.handleFrameError(d,s)}finally{this.updateInProgress=!1}o?(this.consecutiveErrorCount++,this.consecutiveErrorCount>=hi&&(this.loopRunning=!1,this.onError?.(a,{phase:s,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,o=r/i;this.aspectRatio=Math.min(yi,Math.max(gi,o))}else this.aspectRatio=t[0]/t[1]}};var bi="HostChannel has been destroyed",Re=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(bi)}};var Bn=["image","audio","font","spritesheet"],Kn=["timeout","cors","not-found","invalid","aborted","resolver"],Pe="cyberart:fallback/silent",Nn="Asset preloader has been destroyed",vi=4,Ei=new Set(Bn),wi=new Set(Kn),Ci={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 $n(e){return typeof e=="string"&&Ei.has(e)}function Gn(e){return typeof e=="string"&&wi.has(e)}function rt(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.id=="string"&&typeof t.ref=="string"&&Gn(t.code)&&typeof t.message=="string"}function Y(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message&&e.message.length>0?e.message:Ci[e.code]}}function be(e,t){return{type:e==="ready"?ye:ge,kind:"state",payload:t}}function jn(e){if(!e?.aborted)return;let t=new Error("aborted");throw t.name="AbortError",t}function Si(e){return e instanceof Error&&e.name==="AbortError"||typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"}function Mt(e){return e?{...e}:void 0}function ae(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=Mt(e.provenance)),e.cors!==void 0&&(t.cors=e.cors),e.usedFallback&&(t.usedFallback=!0),e.managed&&(t.managed=!0),t}function He(e){return{id:e.id,ref:e.ref,code:e.code,message:e.message}}function Ai(e){if(e.state==="ready"){let t={state:"ready",resource:ae(e.resource)};return e.failure&&(t.failure=He(e.failure)),t}return e.state==="failed"?{state:"failed",failure:He(e.failure)}:{state:e.state}}function Ri(e){return/^https?:/i.test(e)}function Un(e){return e.endsWith("/")?e:`${e}/`}function zn(e,t){let n=Un(t);if(/^(https?:|data:|blob:)/i.test(e))return e;let r=/^moltazine:post\/([^#]+)#(.+)$/.exec(e);if(r)return`${n}moltazine/${encodeURIComponent(r[1])}/${r[2]}`;let i=/^world:asset\/(.+)$/.exec(e);if(i)return`${n}world/${i[1]}`;let o=/^library:(.+)$/.exec(e);return o?`${n}library/${o[1]}`:`${n}${e.replace(/^\//,"")}`}function Pi(e){return{async resolve(t,n){jn(n);let r=e[t.ref];if(!r)throw Y({id:t.id,ref:t.ref,code:"not-found",message:`no fixture for ${t.ref}`});if("error"in r)throw Y({id:t.id,ref:t.ref,code:r.error,message:r.message});return{id:t.id,ref:t.ref,type:t.type,url:r.url,integrity:r.integrity??t.integrity,cors:r.cors??"omit",provenance:r.provenance??t.provenance}}}}function xi(e){let t=Un(e.cdnBase);return{async resolve(n,r){jn(r);let i=e.failures?.[n.ref];if(i){let a=typeof i=="string"?i:i.code,s=typeof i=="string"?void 0:i.message;throw Y({id:n.id,ref:n.ref,code:a,message:s})}let o=zn(n.ref,t);return{id:n.id,ref:n.ref,type:n.type,url:o,integrity:n.integrity,cors:Ri(o)?"anonymous":"omit",provenance:n.provenance}}}}function Ti(e){if(!e||typeof e!="object")return Y({id:"",ref:"",code:"invalid",message:"declaration is required"});if(typeof e.id!="string"||e.id.length===0)return Y({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 Y({id:e.id,ref:"",code:"invalid",message:"ref is required"});if(!$n(e.type))return Y({id:e.id,ref:e.ref,code:"invalid",message:`unsupported type ${String(e.type)}`});if(e.integrity!==void 0&&typeof e.integrity!="string")return Y({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 Y({id:e.id,ref:e.ref,code:"invalid",message:"timeoutMs must be a non-negative finite number"})}function Fn(e){return{id:e.id,ref:Pe,type:e.type,url:Pe,usedFallback:!0,cors:"omit"}}function Hn(e,t){return rt(t)?{id:e.id,ref:e.ref,code:t.code,message:t.message}:Si(t)?Y({id:e.id,ref:e.ref,code:"aborted"}):Y({id:e.id,ref:e.ref,code:"resolver",message:t instanceof Error?t.message:String(t)})}function Vn(e,t){if(!t||typeof t.url!="string"||t.url.length===0)throw Y({id:e.id,ref:e.ref,code:"invalid",message:"resolver returned no url"});if(t.integrity&&e.integrity&&t.integrity!==e.integrity)throw Y({id:e.id,ref:e.ref,code:"invalid",message:"integrity mismatch"});let n=ae(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=Mt(e.provenance)),n}function Dt(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=[],o=new Map,a=new Map,s=new Map,d=new Map,E=new Map,g=new Set,v=!1;function C(l){return l.code==="aborted"||l.code==="timeout"}function x(l,w,S){let L=Hn(l,S);return L.code==="timeout"?L:w.aborted?Y({id:l.id,ref:l.ref,code:"aborted"}):L}function T(l,w){let S=E.get(l);S||(S=new Set,E.set(l,S)),S.add(w)}function p(l){if(l?.state==="ready")return`${l.resource.type}\0${l.resource.ref}`}function m(l,w){for(let[S,L]of E)if(S!==w&&L.has(l))return!0;for(let[S,L]of r)if(S!==w&&p(L)===l)return!0;return!1}function _(l,w){let S=new Set(E.get(l)),L=p(w);L&&S.add(L),E.delete(l);for(let U of S)m(U,l)||s.delete(U)}function M(){let l=0,w=0,S=0,L=0,U={};for(let[G,D]of r)U[G]=Ai(D),D.state==="pending"||D.state==="loading"?l+=1:D.state==="failed"?S+=1:(w+=1,(D.resource.usedFallback||D.failure)&&(L+=1));return{total:r.size,pending:l,ready:w,failed:S,fallbacks:L,items:U,failures:i.map(He)}}function W(){if(g.size===0)return;let l=M();for(let w of g)w(l)}function b(l){i.push(He(l))}function y(l){v||!t||!e.dispatch||e.dispatch(l)}function c(l){if(l?.managed&&l.url.startsWith("blob:")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(l.url)}catch{}}function f(l,w){if(v)return;let S=r.get(l);S?.state==="ready"&&c(S.resource),r.set(l,w),W()}function P(l){if(l.fallback!==void 0)return l.fallback==="silent"?{id:`${l.id}::fallback`,ref:Pe,type:l.type}:typeof l.fallback=="string"?{id:`${l.id}::fallback`,ref:l.fallback,type:l.type}:{...l.fallback,id:typeof l.fallback.id=="string"&&l.fallback.id.length>0?l.fallback.id:`${l.id}::fallback`}}function F(l,w,S){let L=`${l.type}\0${l.ref}`,U=s.get(L);if(U)return w.aborted?Promise.reject(Y({id:l.id,ref:l.ref,code:"aborted"})):(T(S,L),Promise.resolve(ae(U.resource)));if(w.aborted)return Promise.reject(Y({id:l.id,ref:l.ref,code:"aborted"}));let G=d.get(L);if(!G){let V=new AbortController,z={id:l.id,ref:l.ref,type:l.type};l.integrity!==void 0&&(z.integrity=l.integrity),l.provenance&&(z.provenance=Mt(l.provenance)),G={promise:Promise.resolve().then(()=>e.resolver.resolve(z,V.signal)).then(B=>{let K=Vn(l,B);if(V.signal.aborted)throw Y({id:l.id,ref:l.ref,code:"aborted"});return s.set(L,{resource:ae(K)}),K}).catch(B=>{throw Hn(l,B)}).finally(()=>{d.delete(L)}),controller:V,waiters:0},d.set(L,G)}let D=G;return D.waiters+=1,new Promise((V,z)=>{let A=!1,B=($,te)=>{A||(A=!0,w.removeEventListener("abort",K),D.waiters-=1,te&&D.waiters<=0&&D.controller.abort(),$())},K=()=>{B(()=>z(Y({id:l.id,ref:l.ref,code:"aborted"})),!0)};if(w.aborted){K();return}w.addEventListener("abort",K,{once:!0}),D.promise.then($=>{if(!A){if(w.aborted){K();return}T(S,L),B(()=>V(ae($)),!1)}},$=>{if(!A){if(w.aborted){K();return}B(()=>z($),!1)}})})}function O(l,w,S){if(w.aborted)return Promise.reject(Y({id:l.id,ref:l.ref,code:"aborted"}));if(l.ref===Pe)return Promise.resolve(Fn(l));let L=new AbortController,U=()=>L.abort();w.addEventListener("abort",U,{once:!0});let G=l.timeoutMs??e.timeoutMs,D,V=!1;return n&&G!==void 0&&G>0&&Number.isFinite(G)&&(D=setTimeout(()=>{V=!0,L.abort()},G)),F(l,L.signal,S).then(z=>{let A=Vn(l,z);return A.id=l.id,A}).catch(z=>{throw V?Y({id:l.id,ref:l.ref,code:"timeout"}):z}).finally(()=>{D!==void 0&&clearTimeout(D),w.removeEventListener("abort",U)})}async function j(l,w,S,L){try{return{resource:await O(l,w,L)}}catch(U){let G=x(l,w,U);if(C(G)||w.aborted||S>=vi)throw G;let D=P(l);if(!D)throw G;if(w.aborted)throw Y({id:l.id,ref:l.ref,code:"aborted"});if(l.fallback==="silent"||D.ref===Pe)return{resource:Fn(l),failure:G};try{let V=await j(D,w,S+1,L);return{resource:{...ae(V.resource),id:l.id,usedFallback:!0},failure:G}}catch(V){let z=rt(V)&&!C(V)&&!w.aborted?V:x(l,w,V);throw!C(z)&&!w.aborted&&b(G),z}}}async function q(l,w){if(v)throw new Error(Nn);let S=r.get(l.id);if(S?.state==="ready"||S?.state==="failed")return;let L=o.get(l.id);if(L){await L;return}let U=(async()=>{let G=Ti(l);if(G){f(l.id,{state:"failed",failure:G}),b(G),y(be("failed",{id:l.id,ref:l.ref,failure:G}));return}f(l.id,{state:"loading"});let D=a.get(l.id)??new AbortController;a.has(l.id)||a.set(l.id,D);try{let V=await j(l,D.signal,w,l.id);if(v)return;if(D.signal.aborted){let z=Y({id:l.id,ref:l.ref,code:"aborted"});f(l.id,{state:"failed",failure:z}),b(z),y(be("failed",{id:l.id,ref:l.ref,failure:z}));return}if(V.resource.id=l.id,V.failure){f(l.id,{state:"ready",resource:V.resource,failure:V.failure}),b(V.failure),y(be("failed",{id:l.id,ref:l.ref,failure:V.failure,resource:ae(V.resource)})),y(be("ready",{id:l.id,ref:V.resource.ref,resource:ae(V.resource),failure:V.failure}));return}f(l.id,{state:"ready",resource:V.resource}),y(be("ready",{id:l.id,ref:l.ref,resource:ae(V.resource)}))}catch(V){if(v)return;let z=rt(V)&&!C(V)&&!D.signal.aborted?{...He(V),id:l.id}:x(l,D.signal,V);f(l.id,{state:"failed",failure:z}),b(z),y(be("failed",{id:l.id,ref:l.ref,failure:z}))}finally{a.get(l.id)===D&&a.delete(l.id)}})();o.set(l.id,U);try{await U}finally{o.delete(l.id)}}return{async preload(l){if(v)throw new Error(Nn);let w=Array.isArray(l)?l:[];for(let S of w)S&&typeof S.id=="string"&&S.id.length>0&&(r.has(S.id)||r.set(S.id,{state:"pending"}),a.has(S.id)||a.set(S.id,new AbortController));return W(),await Promise.all(w.map(S=>q(S,0))),M()},get(l){let w=r.get(l);if(w?.state==="ready")return ae(w.resource)},getProgress(){return M()},onProgress(l){return g.add(l),()=>{g.delete(l)}},abort(l){if(!v){if(l!==void 0){a.get(l)?.abort();return}for(let w of a.values())w.abort()}},forget(l){if(v)return;if(l===void 0){for(let S of r.values())S.state==="ready"&&c(S.resource);r.clear(),i.length=0,s.clear(),E.clear(),W();return}let w=r.get(l);w?.state==="ready"&&c(w.resource),_(l,w),r.delete(l);for(let S=i.length-1;S>=0;S--)i[S].id===l&&i.splice(S,1);W()},dispose(){if(!v){v=!0;for(let l of a.values())l.abort();a.clear();for(let l of r.values())l.state==="ready"&&c(l.resource);r.clear(),i.length=0,o.clear();for(let l of d.values())l.controller.abort();s.clear(),d.clear(),E.clear(),g.clear()}}}}function Ot(e){pn();let{container:t,seed:n,captureKeyboard:r=!1,audio:i,deterministic:o,assets:a}=e,s=n===void 0?void 0:Ze(n,o?"deterministic":"live"),d=new Re;if(a&&typeof a.resolver?.resolve!="function")throw new Error("createRuntime: assets.resolver is required");let E=a?Dt({resolver:a.resolver,timeoutMs:a.timeoutMs,emitEvents:a.emitEvents??!o,wallClockTimeout:!o,dispatch:b=>d.dispatch(b)}):void 0,g=!1,v=null,C,x=!1,T=t.clientWidth||window.innerWidth,p=t.clientHeight||window.innerHeight,m=new nt(30,!1,T,p,!1,void 0,{container:t,seed:s,captureKeyboard:r,hostChannel:d,audio:i,deterministic:o}),_=()=>{let b=t.clientWidth||window.innerWidth,y=t.clientHeight||window.innerHeight;return b===m.containerWidth&&y===m.containerHeight?!1:(m.containerWidth=b,m.containerHeight=y,!0)},M=null;return!m.isDeterministic&&typeof ResizeObserver<"u"&&(M=new ResizeObserver(()=>{if(g||!v)return;_()&&x&&m.reinit()}),M.observe(t)),m.onError=(b,y)=>{C?.(b,y)},{get tokenData(){return m.tokenData},get hostChannel(){return d},get assets(){return E},get onError(){return C},set onError(b){C=b},mount(b,y={}){if(g)throw new Error("createRuntime: cannot mount on a destroyed runtime");v?.destroy(),x=!1,m.customState=y.initialState,m.setGameManager(y.gameManager);let c=y.onEvent?d.onEvent(y.onEvent):()=>{};if(!m.prepareCart(b))throw c(),new Error("createRuntime: failed to prepare cart");let f=!1,P={async start(){if(!f){if(_()&&m.isPrepared&&(m.init(),m.unloadCart(),!m.prepareCart(b)))throw new Error("createRuntime: failed to prepare cart");m.needsAudio&&(await m.unlockAudio(),f)||(x=!0,m.beginPlayback())}},pause(){f||(m.paused=!0)},resume(){f||(m.paused=!1)},dispatch(F){f||d.dispatch(F)},snapshot(){if(f)return{seed:"",pngDataUrl:""};let F=m.canvas;return{seed:m.tokenData.hash,metadata:b.metadata,pngDataUrl:F?F.toDataURL("image/png"):""}},destroy(){f||(f=!0,x=!1,c(),d.clearInbound(),m.unloadCart(),v===P&&(v=null))},reload(){if(!f){if(!x){if(m.isPrepared&&(m.unloadCart(),!m.prepareCart(b)))throw new Error("createRuntime: failed to prepare cart");return}m.reloadCart()}},reinit(F){if(!f){if(!x){_();return}m.reinit(F)}},getCartState(){return m.animation?.cartState},exportState(){return f?Promise.reject(new Error("Cart handle has been destroyed")):m.exportState()},exportStateJSON(){return f?Promise.reject(new Error("Cart handle has been destroyed")):m.exportStateJSON()},async importState(F,O){if(f)throw new Error("Cart handle has been destroyed");await m.importState(F,O)},peekExportedFramebuffer(){return f?null:m.peekExportedFramebuffer()},peekSeed(){if(!f)return m.peekSeed()},isGenerative(){return f?!1:m.isGenerative()},async step(F=1){if(f)throw new Error("Cart handle has been destroyed");await m.step(F)},async advance(F){if(f)throw new Error("Cart handle has been destroyed");await m.advance(F)},schedule(F){f||m.schedule(F)},getClock(){if(f)throw new Error("Cart handle has been destroyed");return m.getClock()},getRandomState(){if(f)throw new Error("Cart handle has been destroyed");return m.getRandomState()},getReplayMetadata(){return f?Promise.reject(new Error("Cart handle has been destroyed")):m.getReplayMetadata()},get canvas(){return m.canvas},get paused(){return m.paused},set paused(F){f||(m.paused=F)},get tokenData(){return m.tokenData},get isPrepared(){return m.isPrepared},get isLoopRunning(){return m.isLoopRunning},get needsAudio(){return m.needsAudio},get audioLibraries(){return m.audioLibraries}};return v=P,P},async unlockAudio(){await m.unlockAudio()},destroy(){g||(g=!0,v?.destroy(),v=null,M?.disconnect(),M=null,E?.dispose(),d.close(),m.destroy())}}}var xe="cyberart.state.save",Te="cyberart.state.load";function ki(e,t,n={}){let r=n.persist,i=r?{persist:r}:void 0,o=()=>{t.emit({type:xe,payload:i})},a=()=>{t.emit({type:Te,payload:i})};e.registerAction("w",o,!0),e.registerAction("W",o,!0),e.registerAction("e",a,!0),e.registerAction("E",a,!0)}function qn(e){if(e.type!==xe&&e.type!==Te)return;let t=e.payload?.persist;return t==="localStorage"?t:void 0}var Ii="cyberart-io",Mi=1,pe="framebuffers";function _t(e,t){return`${e||"unknown"}:${t?ue(t):"none"}`}function Yn(e,t){return`${e||"unknown"}:${t||"none"}`}function Lt(){return new Promise((e,t)=>{let n=indexedDB.open(Ii,Mi);n.onupgradeneeded=()=>{let r=n.result;r.objectStoreNames.contains(pe)||r.createObjectStore(pe)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error??new Error("indexedDB open failed"))})}function Di(e){let t=e.data;return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}function Wn(e,t){return new Promise((n,r)=>{let o=e.transaction(pe,"readonly").objectStore(pe).get(t);o.onsuccess=()=>n(o.result),o.onerror=()=>r(o.error??new Error("indexedDB read failed"))})}async function Jn(e,t,n){if(typeof indexedDB>"u")return;let r=await Lt(),i={width:n.width,height:n.height,data:Di(n)};try{await new Promise((o,a)=>{let s=r.transaction(pe,"readwrite");s.oncomplete=()=>o(),s.onerror=()=>a(s.error??new Error("indexedDB write failed")),s.objectStore(pe).put(i,_t(e,t))})}finally{r.close()}}async function Xn(e,t){if(typeof indexedDB>"u")return null;let n=await Lt();try{let r=_t(e,t),i=Yn(e,t),o=await Wn(n,r)??(r===i?void 0:await Wn(n,i));if(!o||!o.data||o.width<1||o.height<1)return null;let a=new ImageData(o.width,o.height);return a.data.set(new Uint8ClampedArray(o.data)),a}finally{n.close()}}async function Qn(e,t){if(typeof indexedDB>"u")return;let n=await Lt();try{await new Promise((r,i)=>{let o=n.transaction(pe,"readwrite");o.oncomplete=()=>r(),o.onerror=()=>i(o.error??new Error("indexedDB delete failed"));let a=o.objectStore(pe);a.delete(_t(e,t)),a.delete(Yn(e,t))})}finally{n.close()}}var Nt="cyberart.state.",Oi="Saved state",_i="Loaded state",Li="Failed to save state",Ni="Failed to load state",Fi="No saved state";function me(e,t){let n=e||"unknown";return t?Nt+n+"."+ue(t):Nt+n}function Hi(e,t,n){return r=>{if(qn(r)==="localStorage"){if(r.type===xe){Vi(e,t,n);return}r.type===Te&&Bi(e,t,n)}}}function ke(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(typeof n.savedAt=="number"&&n.bundle&&typeof n.bundle=="object")return{savedAt:n.savedAt,bundle:n.bundle};let r=t;return typeof r.seed=="string"&&typeof r.version=="number"?{savedAt:0,bundle:r}:null}catch{return null}}async function Vi(e,t,n){let r=e();if(r)try{let i=await r.exportState(),o=i.cartId??t?.();i.generative===!0?(qi(o),it(me(o,i.seed),i)):it(me(o),i);let a=r.peekExportedFramebuffer?.();if(a)try{await Jn(o,i.seed,a)}catch(s){console.warn("Failed to save cart framebuffer",s)}n?.(Oi,"transient")}catch(i){console.error("Failed to save cart state",i),n?.(Li,"transient")}}async function Bi(e,t,n){let r=e();if(!r)return;let i=t?.(),o=r.peekSeed?.(),a=r.isGenerative?.()===!0,s=Ui(i,a,o);if(!s){console.warn("No saved cart state for",i||"unknown",a&&o?`(hash ${o})`:""),n?.(Fi,"transient");return}try{let d=await Xn(i,s.bundle.seed).catch(()=>null);await r.importState(s.bundle,{framebuffer:d}),n?.(_i,"transient")}catch(d){console.error("Failed to load cart state",d),n?.(Ni,"transient")}}function it(e,t){let n=JSON.stringify({savedAt:Date.now(),bundle:t});Ki(e,n)}function Ki(e,t){for(;;)try{localStorage.setItem(e,t);return}catch(n){if(!$i(n)||!Gi(e))throw n}}function $i(e){if(!e||typeof e!="object")return!1;let t=e.name,n=e.code;return t==="QuotaExceededError"||t==="NS_ERROR_DOM_QUOTA_REACHED"||n===22||n===1014}function Gi(e){let t=null,n=1/0;for(let o of ji()){if(o===e)continue;let a=localStorage.getItem(o);if(!a)continue;let d=ke(a)?.savedAt??0;d<n&&(n=d,t=o)}if(!t)return!1;let r=localStorage.getItem(t),i=r?ke(r):null;return localStorage.removeItem(t),i?.bundle&&Qn(i.bundle.cartId,i.bundle.seed).catch(()=>{}),!0}function ji(){let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&n.startsWith(Nt)&&e.push(n)}return e}function Ui(e,t,n){if(t&&n){let i=localStorage.getItem(me(e,n));if(i)return ke(i);let o=localStorage.getItem(me(e));if(!o)return null;let a=ke(o);if(!a||!zi(a.bundle,n))return null;try{it(me(e,n),a.bundle)}catch{}return a}let r=localStorage.getItem(me(e));return r?ke(r):null}function zi(e,t){return typeof e.seed=="string"&&ue(e.seed)===ue(t)}function qi(e){let t=me(e),n=localStorage.getItem(t);if(!n)return;let r=ke(n);if(r&&typeof r.bundle.seed=="string"){let i=me(e,r.bundle.seed);if(!localStorage.getItem(i))try{it(i,r.bundle)}catch{return}}localStorage.removeItem(t)}var Ve=1,se="cyberart.diagnostic.rejected",at=8,Wi=new Set(["intent","state","diagnostic"]),Yi=new Set([xe,Te]);function ot(e){return typeof e=="string"&&Wi.has(e)}function Zn(e){if(e.kind!==void 0)return ot(e.kind)?e.kind:void 0;if(!(typeof e.type!="string"||e.type.length===0)){if(Yi.has(e.type))return"intent";for(let t of e.type.split("."))if(ot(t))return t}}function er(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 fe(e,t){for(let n of e)if(er(n,t))return!0;return!1}function Ie(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 st(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!==Ve)return{ok:!1,reason:"malformed",detail:`unsupported schemaVersion ${String(e.schemaVersion)}`};let n=Zn(e);if(!n)return{ok:!1,reason:"malformed",detail:`cannot infer kind from type "${e.type}"`};let r=Ie(e.payload);if(!r.ok)return{ok:!1,reason:"malformed",detail:"payload is not JSON-serializable"};let i=t.createId(),o=typeof e.correlationId=="string"&&e.correlationId.length>0?e.correlationId:i,a=typeof e.causationId=="string"&&e.causationId.length>0?e.causationId:t.causationId,s=typeof e.target=="string"&&e.target.length>0?e.target:void 0,d=t.maxHops??at,E=t.parentHops===void 0?d:Math.max(0,t.parentHops-1),g=typeof e.idempotencyKey=="string"&&e.idempotencyKey.length>0?e.idempotencyKey:void 0,v={schemaVersion:Ve,type:e.type,kind:n,source:t.source,id:i,correlationId:o,seq:t.seq,hops:E};return s&&(v.target=s),a&&(v.causationId=a),g&&(v.idempotencyKey=g),r.value!==void 0&&(v.payload=r.value),{ok:!0,envelope:v}}var Ji=new Set(["rate-limited","storm-detected","hop-limit","loop-detected","not-subscribed"]),Xi=8,Qi=8,Zi=16,eo=256,to=256,no=["*.intent.*"];function Ft(e={}){let t=e.hostSource??"host",n="router",r=e.maxPerTurn??Xi,i=e.maxCausationDepth??Qi,o=e.maxHops??at,a=e.maxCorrelationPerTurn??Zi,s=e.maxIndex??eo,d=e.maxDecisions??to,E=e.maxPerWindow,g=e.windowMs??1e3,v=e.now??Date.now,C=0,x=e.createId??(()=>`evt-${++C}`),T=new Map,p=[],m=[],_=new Map,M=new Map,W=new Map,b=[],y=0,c=0,f=0;function P(u){try{return JSON.parse(JSON.stringify(u))}catch{return u}}function F(u){for(b.push(u);b.length>d;)b.shift();for(let h of m)try{h(P(u))}catch{}}function O(u,h){let R={outcome:h.outcome,source:h.source,type:u.type,kind:u.kind,envelopeId:u.id,deliveredTo:h.deliveredTo,hops:u.hops,seq:u.seq,correlationId:u.correlationId,schemaVersion:u.schemaVersion,turn:f,time:v()};return h.reason&&(R.reason=h.reason),h.detail&&(R.detail=h.detail),h.priorEnvelopeId&&(R.priorEnvelopeId=h.priorEnvelopeId),u.target&&(R.target=u.target),u.causationId&&(R.causationId=u.causationId),u.idempotencyKey&&(R.idempotencyKey=u.idempotencyKey),u.payload!==void 0&&(R.payload=P(u.payload)),R}let j=[],q=!1;function l(u,h,R){for(u.set(h,R);u.size>s;){let k=u.keys().next().value;if(k===void 0)break;u.delete(k)}}function w(u){l(_,u.id,{type:u.type,source:u.source,causationId:u.causationId,hops:u.hops,correlationId:u.correlationId,idempotencyKey:u.idempotencyKey})}function S(u,h){h&&(u.correlationId||(u.correlationId=h.correlationId),u.causationId||(u.causationId=h.id),!u.idempotencyKey&&h.idempotencyKey&&(u.idempotencyKey=`${h.idempotencyKey}::${u.type}`))}function L(u,h){if(u){let R=_.get(u);return R?R.hops:o}return h}function U(u,h){return`${u}\0${h}`}function G(u,h){u.idempotencyKey&&l(W,U(u.source,u.idempotencyKey),h)}function D(u,h){if(h)return W.get(U(u,h))}function V(u){return D(u.source,u.idempotencyKey)}function z(u){return u.seq+=1,u.seq}function A(u,h){if(!(typeof h.causationId=="string"&&h.causationId.length>0))return u.lastDelivered}function B(u){let h=new Set,R=new Set([`${u.type}\0${u.source}`]),k=u.causationId,I=0;for(;k;){if(I+=1,I>i||h.has(k))return!0;h.add(k);let H=_.get(k);if(!H)break;let ne=`${H.type}\0${H.source}`;if(R.has(ne))return!0;R.add(ne),k=H.causationId}return!1}function K(u){let h=(M.get(u)??0)+1;return M.set(u,h),h}function $(u,h){E!==void 0&&(u.emitTimestamps=u.emitTimestamps.filter(R=>h-R<g))}function te(u,h){return(h.kind==="state"||h.kind==="diagnostic")&&!u.authoritative?!1:fe(u.emit,h.type)}function je(u){for(let h of p)if(fe(h.patterns,u.type))try{h.listener(u)}catch{}}function Ue(u){let h=[];if(u.target){let R=T.get(u.target);return!R||!fe(R.subscribe,u.type)||(R.channel.dispatch(u),R.lastDelivered={id:u.id,hops:u.hops,correlationId:u.correlationId,idempotencyKey:u.idempotencyKey},h.push(R.id)),h}for(let R of T.values())fe(R.subscribe,u.type)&&(R.channel.dispatch(u),R.lastDelivered={id:u.id,hops:u.hops,correlationId:u.correlationId,idempotencyKey:u.idempotencyKey},h.push(R.id));return h}function Ur(u,h,R,k,I,H,ne){let oe={reason:k,eventType:h,source:R};I&&(oe.detail=I),c+=1;let Oe=x(),ve={schemaVersion:Ve,type:se,kind:"diagnostic",source:n,id:Oe,correlationId:H??Oe,seq:c,hops:0,payload:oe};ne&&(ve.causationId=ne),w(ve);let ln=T.get(u);ln&&ln.channel.dispatch(ve),je(ve)}function Z(u,h,R,k,I){if(Ur(u,I?.type??(typeof h.type=="string"?h.type:""),I?.source??u,R,k,I?.correlationId,I?.id),I?.idempotencyKey&&!Ji.has(R)&&G(I,{status:"rejected"}),I)F(O(I,{outcome:"rejected",reason:R,detail:k,source:u,deliveredTo:[]}));else{let H={outcome:"rejected",reason:R,source:u,type:typeof h.type=="string"?h.type:"",deliveredTo:[],turn:f,time:v()};k&&(H.detail=k),typeof h.idempotencyKey=="string"&&(H.idempotencyKey=h.idempotencyKey),F(H)}}function zr(u,h){w(u),G(u,{status:"accepted",envelope:u}),K(u.correlationId),je(u);let R=Ue(u);F(O(u,{outcome:"accepted",source:h,deliveredTo:R}))}function vt(u,h,R,k){let I=k?.type??(typeof h.type=="string"?h.type:""),H={outcome:"duplicate",reason:"duplicate",detail:R.status==="accepted"?"idempotent accepted":"idempotent rejected",source:u,type:I,deliveredTo:[],turn:f,time:v()};k?(H.kind=k.kind,H.envelopeId=k.id,H.hops=k.hops,H.seq=k.seq,H.correlationId=k.correlationId,H.schemaVersion=k.schemaVersion,k.target&&(H.target=k.target),k.causationId&&(H.causationId=k.causationId),k.idempotencyKey&&(H.idempotencyKey=k.idempotencyKey),k.payload!==void 0&&(H.payload=P(k.payload))):typeof h.idempotencyKey=="string"&&(H.idempotencyKey=h.idempotencyKey),R.status==="accepted"&&(H.priorEnvelopeId=R.envelope.id,H.envelopeId||(H.envelopeId=R.envelope.id)),F(H)}function dn(u,h,R,k){if(!R.ok){Z(u,h,"malformed",R.detail);return}let I=R.envelope,H=V(I);if(H)return vt(u,h,H,I),H.status==="accepted"?H.envelope:void 0;if(I.hops<1){Z(u,h,"hop-limit","no hops remaining",I);return}if(I.target&&I.target!==t){let ne=T.get(I.target);if(!ne){Z(u,h,"unknown-target",`unknown target "${I.target}"`,I);return}if(!fe(ne.subscribe,I.type)){Z(u,h,"not-subscribed",`target "${I.target}" does not subscribe to ${I.type}`,I);return}}if(k){if(!te(k,I)){Z(u,h,"unauthorized","source may not emit this event",I);return}if(k.emitsThisTurn+=1,k.emitsThisTurn>r){Z(u,h,"rate-limited","maxPerTurn exceeded",I);return}if(E!==void 0){let oe=v();if($(k,oe),k.emitTimestamps.push(oe),k.emitTimestamps.length>E){Z(u,h,"rate-limited","maxPerWindow exceeded",I);return}}if(B(I)){Z(u,h,"loop-detected","causation chain cycle or depth exceeded",I);return}if((M.get(I.correlationId)??0)+1>a){Z(u,h,"storm-detected","correlationId storm",I);return}if(e.validate){let oe;try{oe=e.validate(I)}catch(Oe){let ve=Oe instanceof Error?Oe.message:"validate threw";Z(u,h,"host-rejected",ve,I);return}if(oe!==!0){Z(u,h,"host-rejected",oe.detail,I);return}}}else{if(B(I)){Z(u,h,"loop-detected","causation chain cycle or depth exceeded",I);return}if((M.get(I.correlationId)??0)+1>a){Z(u,h,"storm-detected","correlationId storm",I);return}}return zr(I,u),I}function qr(u,h){let R=T.get(u);if(!R)return;let k={...h},I=A(R,k);S(k,I);let H=D(R.id,k.idempotencyKey);if(H){vt(u,k,H);return}let ne=z(R),oe=st(k,{source:R.id,createId:x,seq:ne,causationId:I?.id,maxHops:o,parentHops:L(k.causationId??I?.id,I?.hops)});dn(u,k,oe,R)}function Wr(u,h){let R=h?.cause,k={...u};S(k,R);let I=D(t,k.idempotencyKey);if(I)return vt(t,k,I),I.status==="accepted"?I.envelope:void 0;y+=1;let H=st(k,{source:t,createId:x,seq:y,causationId:k.causationId,maxHops:o,parentHops:L(k.causationId,R?.hops)});return dn(t,k,H,void 0)}function Yr(){if(!q){q=!0;try{for(;j.length>0;){let u=j.shift();u&&(u.kind==="cart"?qr(u.participantId,u.event):u.result=Wr(u.event,u.extras))}}finally{q=!1}}}function un(u){j.push(u),Yr()}return{attach(u,h,R={}){if(u===t||u===n)throw new Error(`createEventRouter: "${u}" is a reserved participant id`);for(let H of T.values())if(H.channel===h&&H.id!==u)throw new Error(`createEventRouter: channel already attached as "${H.id}"`);T.get(u)?.unsubscribe();let I={id:u,channel:h,emit:R.emit??no,subscribe:R.subscribe??[],authoritative:R.authoritative===!0,seq:0,emitsThisTurn:0,emitTimestamps:[],unsubscribe:()=>{}};I.unsubscribe=h.onEvent(H=>{un({kind:"cart",participantId:u,event:H})}),T.set(u,I)},detach(u){let h=T.get(u);h&&(h.unsubscribe(),T.delete(u))},publish(u,h){let R={kind:"publish",event:u,extras:h};return un(R),R.result},subscribe(u,h){let R={patterns:u,listener:h};return p.push(R),()=>{let k=p.indexOf(R);k>=0&&p.splice(k,1)}},subscribeDecision(u){return m.push(u),()=>{let h=m.indexOf(u);h>=0&&m.splice(h,1)}},inspectParticipants(){return[...T.values()].map(u=>({id:u.id,emit:u.emit.slice(),subscribe:u.subscribe.slice(),authoritative:u.authoritative}))},inspectDecisions(){return b.map(u=>P(u))},turn(){f+=1,M.clear();for(let u of T.values())u.emitsThisTurn=0,u.lastDelivered=void 0,E!==void 0&&$(u,v())}}}var ro=new Set(["string","number","boolean","object","array"]);function J(e,t,n){return n?{code:e,detail:t,path:n}:{code:e,detail:t}}function tr(e){if(!(typeof e!="string"||e.length===0)){for(let t of e.split("."))if(ot(t))return t}}function nr(e){let t=e.split(".");return t.length===0?"*":(t[t.length-1]="*",t.join("."))}function Ht(e){let t=[];if(!e||typeof e!="object")return[J("invalid-schema","payload schema is required")];if((typeof e.version!="number"||!Number.isInteger(e.version)||e.version<1)&&t.push(J("invalid-version","payload schema version must be an integer >= 1")),!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return t.push(J("invalid-fields","payload schema fields must be an object")),t;for(let[n,r]of Object.entries(e.fields)){if(!n){t.push(J("invalid-field","field name is required",n));continue}(!r||typeof r!="object"||!ro.has(r.type))&&t.push(J("invalid-field-type",`field "${n}" type must be string | number | boolean | object | array`,n))}return t}function io(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e=="string"?"string":typeof e=="number"&&Number.isFinite(e)?"number":typeof e=="boolean"?"boolean":typeof e=="object"?"object":"other"}function oo(e,t){if(t===void 0){let i=Object.entries(e.fields).filter(([,o])=>o.optional!==!0);return i.length===0?{ok:!0,payload:void 0}:{ok:!1,errors:i.map(([o])=>J("missing-field",`payload is missing required field "${o}"`,o))}}if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,errors:[J("invalid-payload","payload must be a JSON object")]};let n=t,r=[];for(let[i,o]of Object.entries(e.fields)){if(!(i in n)||n[i]===void 0){o.optional!==!0&&r.push(J("missing-field",`payload is missing required field "${i}"`,i));continue}let a=io(n[i]);a!==o.type&&r.push(J("field-type",`payload.${i} expected ${o.type}, got ${a}`,i))}return r.length>0?{ok:!1,errors:r}:{ok:!0,payload:t}}function ao(e,t,n){let r=nr(e);return{type:e,kind:t,payloadSchema:{version:n.version,fields:{...n.fields}},emitPattern:r,subscribePattern:r,toManifest(){let i={};for(let[o,a]of Object.entries(this.payloadSchema.fields))i[o]={type:a.type,optional:a.optional===!0};return{type:this.type,kind:this.kind,version:this.payloadSchema.version,fields:i,emitPattern:this.emitPattern,subscribePattern:this.subscribePattern}},validatePayload(i){return oo(this.payloadSchema,i)}}}function Vt(e,t,n){let r=[];if(typeof t!="string"||t.length===0)r.push(J("invalid-type","event type is required"));else if(t.split(".").some(i=>i.length===0))r.push(J("invalid-type",`event type "${t}" has empty dotted segments`));else{let i=tr(t);i?i!==e&&r.push(J("kind-mismatch",`type "${t}" infers kind "${i}" but this helper defines "${e}"`)):r.push(J("kind-mismatch",`type "${t}" has no "${e}" segment; dotted names like host.presentation.* need e.g. host.presentation.${e}.cue-started`))}return r.push(...Ht(n)),r.length>0?{ok:!1,errors:r}:{ok:!0,contract:ao(t,e,n)}}function so(e,t){return Vt("intent",e,t)}function co(e,t){return Vt("state",e,t)}function uo(e,t){return Vt("diagnostic",e,t)}function lo(e,t){let n=Ht(e),r=Ht(t);if(n.length>0||r.length>0||t.version<e.version)return"breaking";let i=Object.keys(e.fields),o=Object.keys(t.fields),a=new Set(i),s=new Set(o);for(let g of i){if(!s.has(g))return"breaking";let v=e.fields[g],C=t.fields[g];if(v.type!==C.type)return"breaking";let x=v.optional!==!0,T=C.optional===!0;if(x&&T||!x&&C.optional!==!0&&v.optional===!0)return"breaking"}let d=!1;for(let g of o)if(!a.has(g)){if(t.fields[g].optional!==!0)return"breaking";d=!0}let E=i.length===o.length&&i.every(g=>t.fields[g].type===e.fields[g].type&&t.fields[g].optional===!0==(e.fields[g].optional===!0));return E&&t.version===e.version?"identical":t.version>e.version&&(d||E)?"backward-compatible":t.version===e.version&&d?"breaking":E?"identical":"breaking"}function po(e,t){let n=[],r=[],i=new Set,o=new Set;for(let a of e)(t==="authoritative"||a.kind==="intent")&&!i.has(a.emitPattern)&&(i.add(a.emitPattern),n.push(a.emitPattern)),a.kind!=="intent"&&!o.has(a.subscribePattern)&&(o.add(a.subscribePattern),r.push(a.subscribePattern));return{emit:n,subscribe:r,authoritative:t==="authoritative"}}function mo(e,t){let n=e.emit??["*.intent.*"],r=e.authoritative===!0,i=[];for(let o of t)fe(n,o.type)&&(o.kind==="state"||o.kind==="diagnostic")&&!r&&i.push(J("unauthorized-emit",`emit pattern allows ${o.kind} "${o.type}" but attach is not authoritative`,o.type));return i.length>0?{ok:!1,errors:i}:{ok:!0}}function fo(e){let t=new Map;for(let i of e)t.set(i.type,i);let n=i=>{let o=t.get(i.type);return o?o.kind!==i.kind?{ok:!1,errors:[J("kind-mismatch",`envelope kind "${i.kind}" does not match contract "${o.kind}"`,i.type)]}:o.validatePayload(i.payload):{ok:!1,errors:[J("unknown-type",`no contract registered for "${i.type}"`,i.type)]}};return{get(i){return t.get(i)},manifest(){return[...t.values()].sort((i,o)=>i.type.localeCompare(o.type)).map(i=>i.toManifest())},validateEnvelope:n,asRouterValidate:i=>{let o=n(i);return o.ok?!0:{reason:"host-rejected",detail:o.errors.map(a=>a.detail).join("; ")}}}}var Me=1,Kt="presentation.state.model",ir="presentation.intent.unsupported",or=["loading","ready","error","unsupported"],ho=["presentation.state.*",se],yo="Presentation adapter has been destroyed",ar="Presentation adapter: model is invalid or not JSON-serializable",go=new Set(or);function sr(e){return typeof e=="string"&&go.has(e)}function $t(e){if(e===null||typeof e!="object")return!1;let t=e;return!(t.contractVersion!==Me||!sr(t.phase)||t.reason!==void 0&&typeof t.reason!="string"||t.view!==void 0&&(t.view===null||typeof t.view!="object"))}function Bt(e,t){let n={type:Kt,kind:"state",payload:e};return t?.correlationId&&(n.correlationId=t.correlationId),t?.causationId&&(n.causationId=t.causationId),t?.idempotencyKey&&(n.idempotencyKey=t.idempotencyKey),n}function Gt(){return{contractVersion:Me,phase:"loading"}}function jt(e){return{contractVersion:Me,phase:"unsupported",reason:e}}function Ut(e){let t=Ie(e);return t.ok?$t(t.value)?{ok:!0,model:t.value}:t.value!==null&&typeof t.value=="object"&&"contractVersion"in t.value&&t.value.contractVersion!==Me?{ok:!1,reason:"unknown-contract-version",contractVersion:t.value.contractVersion}:{ok:!1,reason:"invalid-model"}:{ok:!1,reason:"model-not-serializable"}}function ct(e){let t=Ut(e);if(!t.ok)throw new Error(ar);return t.model}function bo(e){let t=Ie(e);return t.ok&&$t(t.value)?t.value:jt("model-not-serializable")}function vo(e,t){if(e.type!==Kt)return{model:t};let n=Ut(e.payload);return n.ok?{model:n.model}:{model:jt(n.reason),rejected:{reason:n.reason,contractVersion:n.contractVersion}}}function Eo(e){if(e===null||typeof e!="object"||!("regions"in e))return[];let t=e.regions;return Array.isArray(t)?t:[]}function wo(e,t,n){return e>=n.x&&e<n.x+n.width&&t>=n.y&&t<n.y+n.height}function Co(e,t){let n=t.intent;if(!n||typeof n.type!="string"||n.type.length===0)return;let r={type:n.type,kind:"intent"};if(n.payload!==void 0){let i=Ie(n.payload);if(!i.ok)return;r.payload=i.value}n.target&&(r.target=n.target),n.correlationId&&(r.correlationId=n.correlationId),n.idempotencyKey&&(r.idempotencyKey=n.idempotencyKey),e.emit(r)}function cr(e,t,n){let r={reason:t};if(n!==void 0){let i=Ie(n);i.ok&&(r.contractVersion=i.value)}e.emit({type:ir,kind:"intent",payload:r})}function rr(e,t,n){let r=t;for(let i of e){let o=vo(i,r);o.rejected&&n&&cr(n,o.rejected.reason,o.rejected.contractVersion),r=o.model}return r}function dr(){return{metadata:{id:"cyberart.presentation.reference",name:"Reference presentation",frameRate:30},getDefaultState:(e,t,n,r,i,o,a,s,d)=>{let E=i?.model;if(E===void 0)return{model:Gt()};let g=Ut(E);return g.ok?{model:g.model}:(d&&cr(d,g.reason,g.contractVersion),{model:jt(g.reason)})},update:(e,t,n,r,i,o,a,s,d,E,g)=>{let v=rr(g?.consume()??[],i.model,g);for(;a?.hasClick();){let C=a.consumeClick();if(!(!C||v.phase!=="ready"||!g)){for(let x of Eo(v.view))if(wo(C.x,C.y,x)){Co(g,x);break}}}return g&&(v=rr(g.consume(),v,g)),v===i.model?i:{...i,model:v}},render:(e,t,n,r,i,o)=>{let a=i.model.view?.background;o.fillStyle=a??"#111",o.fillRect(0,0,r.width,r.height)}}}function ur(e,t={}){let n=e,r=t.model?ct(t.model):Gt(),i=!1,o=t.present??t.model!==void 0,a=()=>{if(i)throw new Error(yo)},s=d=>{a(),r=ct(d),n.dispatch(Bt(r))};return o&&n.dispatch(Bt(r)),{version:Me,get target(){return n},get model(){return bo(r)},get phase(){return r.phase},get paused(){return n.paused===!0},present:s,async start(){return a(),n.start()},pause(){a(),n.pause()},resume(){a(),n.resume()},retarget(d){a(),n=d},destroy(){i||(i=!0,n.destroy())}}}function So(e,t={}){let n=t.model?ct(t.model):t.initialState?.model!==void 0?ct(t.initialState.model):Gt(),r=t.cart??dr(),i=e.mount(r,{initialState:{...t.initialState,model:n},onEvent:t.onEvent});return ur(i,{model:n,present:!1})}var Be="cue.started",ut="cue.completed",Ke="cue.cancelled",lt="cue.replaced",Ao=[Be,ut,Ke,lt];function Ro(e){return e===Be||e===ut||e===Ke||e===lt}function pr(e,t){let n=e<0?0:e>1?1:e;return t==="ease-out"?1-(1-n)*(1-n):n}function lr(e){return{type:e.type,atFrame:e.atFrame,name:e.name,idempotencyKey:e.idempotencyKey,progress:e.progress}}function dt(e){return{name:e.name,idempotencyKey:e.idempotencyKey,phase:e.phase,startFrame:e.startFrame,durationFrames:e.durationFrames,delayFrames:e.delayFrames,easing:e.easing,progress:e.progress,repeatIndex:e.repeatIndex}}function zt(e){return e.startFrame+e.delayFrames}function Po(e,t){if(!e||typeof e!="object")return{ok:!1,reason:"invalid",detail:"spec is required"};if(typeof e.name!="string"||e.name.length===0)return{ok:!1,reason:"invalid",detail:"name is required"};if(typeof e.idempotencyKey!="string"||e.idempotencyKey.length===0)return{ok:!1,reason:"invalid",detail:"idempotencyKey is required"};if(typeof e.durationFrames!="number"||!Number.isFinite(e.durationFrames)||e.durationFrames<0)return{ok:!1,reason:"invalid",detail:"durationFrames must be a non-negative finite number"};let n=e.startFrame===void 0?t:e.startFrame;if(typeof n!="number"||!Number.isFinite(n))return{ok:!1,reason:"invalid",detail:"startFrame must be finite"};let r=e.delayFrames??0;if(typeof r!="number"||!Number.isFinite(r)||r<0)return{ok:!1,reason:"invalid",detail:"delayFrames must be a non-negative finite number"};let i=e.easing??"linear";if(i!=="linear"&&i!=="ease-out")return{ok:!1,reason:"invalid",detail:"unsupported easing"};let o=e.onDuplicate??"replace";if(o!=="ignore"&&o!=="replace"&&o!=="reject")return{ok:!1,reason:"invalid",detail:"unsupported onDuplicate"};let a=0;if(e.repeat)if("forever"in e.repeat&&e.repeat.forever)a="forever";else if("count"in e.repeat){if(typeof e.repeat.count!="number"||!Number.isFinite(e.repeat.count)||e.repeat.count<0)return{ok:!1,reason:"invalid",detail:"repeat.count must be >= 0"};a=Math.floor(e.repeat.count)}else return{ok:!1,reason:"invalid",detail:"unsupported repeat"};let s=e.reducedMotion??"complete";return s!=="skip"&&s!=="complete"&&(typeof s!="object"||typeof s.durationFrames!="number"||!Number.isFinite(s.durationFrames)||s.durationFrames<0)?{ok:!1,reason:"invalid",detail:"unsupported reducedMotion"}:{name:e.name,idempotencyKey:e.idempotencyKey,startFrame:n,durationFrames:e.durationFrames,delayFrames:r,easing:i,repeatRemaining:a,repeatIndex:0,reducedMotion:s,onDuplicate:o,phase:"scheduled",progress:0}}function xo(e,t){if(!t)return e;let n=e.reducedMotion;return n==="skip"||n==="complete"?{...e,durationFrames:0,delayFrames:0,startFrame:e.startFrame}:{...e,durationFrames:n.durationFrames}}function To(e={}){let t=!!e.reducedMotion,n=e.originFrame??0,r=new Map,i=[];function o(p){i.push(p)}function a(p,m){let _=zt(p)-zt(m);return _!==0?_:p.name<m.name?-1:p.name>m.name?1:p.idempotencyKey<m.idempotencyKey?-1:p.idempotencyKey>m.idempotencyKey?1:0}function s(p,m){o({type:m,atFrame:n,name:p.name,idempotencyKey:p.idempotencyKey,progress:p.progress})}function d(p){if(p.phase="completed",p.progress=1,s(p,ut),p.repeatRemaining==="forever"||p.repeatRemaining>0){if(typeof p.repeatRemaining=="number"&&(p.repeatRemaining-=1),p.repeatIndex+=1,p.phase="scheduled",p.progress=0,p.startFrame=n,p.delayFrames=0,p.durationFrames===0){r.delete(p.idempotencyKey);return}p.phase="active",s(p,Be)}else r.delete(p.idempotencyKey)}function E(p){if(p.phase==="cancelled"||p.phase==="completed")return;let m=zt(p);if(!(n<m)){if(p.phase==="scheduled"&&(p.phase="active",p.progress=p.durationFrames===0?1:0,s(p,Be),p.durationFrames===0)){d(p);return}if(p.phase==="active"){let _=n-m;_>=p.durationFrames?(p.progress=1,d(p)):p.progress=pr(p.durationFrames===0?1:_/p.durationFrames,p.easing)}}}function g(){let p=[...r.values()].sort(a);for(let m of p)E(m)}function v(p){let m=Po(p,n);if("ok"in m&&m.ok===!1)return m;let _=xo(m,t),M=r.get(_.idempotencyKey);if(M&&(M.phase==="scheduled"||M.phase==="active")){if(M.onDuplicate==="reject"||_.onDuplicate==="reject")return{ok:!1,reason:"duplicate",detail:`cue ${_.idempotencyKey} is already ${M.phase}`};if(M.onDuplicate==="ignore"||_.onDuplicate==="ignore")return{ok:!0,cue:dt(M)};M.phase="cancelled",M.progress=M.progress,s(M,lt),r.delete(M.idempotencyKey)}r.set(_.idempotencyKey,_),E(_);let W=r.get(_.idempotencyKey)??_;return{ok:!0,cue:dt(W)}}function C(p){let m=r.get(p);return!m||m.phase==="completed"||m.phase==="cancelled"?!1:(m.phase="cancelled",s(m,Ke),r.delete(p),!0)}function x(){for(let p of[...r.values()].sort(a))(p.phase==="scheduled"||p.phase==="active")&&(p.phase="cancelled",s(p,Ke));r.clear(),i.length=0,n=e.originFrame??0}function T(p=1){let m=Number.isFinite(p)?Math.max(0,Math.floor(p)):0,_=i.length;for(let M=0;M<m;M++)n+=1,g();return i.slice(_).map(lr)}return{play:v,step:T,cancel:C,reset:x,snapshot(){return{frame:n,reducedMotion:t,cues:[...r.values()].sort(a).map(dt),events:i.map(lr)}},get(p){let m=r.get(p);return m?dt(m):void 0},get frame(){return n},get reducedMotion(){return t}}}var ko=1,fr=["loading","ready","error","unsupported"],hr=["keyboard","pointer","audio","assets","hostChannel"],yr=["image","audio","font","spritesheet"],gr=["tone","midi"],mt=["source-over","screen"],ft=["transparent","opaque"],Io=new Set(fr),br=new Set(hr),mr=new Set(yr),vr=new Set(gr),Mo=new Set(["version","id","runtime","phases","managers","assets","acceptedEvents","emittedEvents","permissions","integrations","surface","layers"]),Do=new Set(["minContractVersion","features"]),Oo=new Set(["kinds","declarations"]),_o=new Set(["id","kind"]),Lo=new Set(["emit","subscribe","authoritative"]),Er=new Set(["alpha","clearPolicy"]),wr=new Set(["compositor","blend"]),Cr=new Set(mt),Sr=new Set(ft),No=new Set(["contractVersion","features","integrations","managers","emit","subscribe","surface","layers"]);function N(e,t,n){return n?{code:e,detail:t,path:n}:{code:e,detail:t}}function ce(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function de(e,t,n){let r=[];for(let i of Object.keys(e))t.has(i)||r.push(N("unknown-field",`unknown field "${i}"`,n?`${n}.${i}`:i));return r}function Fo(e){if(typeof e!="string"||e.length===0)return!1;let t=e.split(".");return t.some(n=>n.length===0)?!1:t.every(n=>n==="*"||/^[a-z0-9][a-z0-9-]*$/i.test(n))}function Ho(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 pt(e,t){for(let n of t)if(e===n||Ho(n,e))return!0;return!1}function $e(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function qt(e,t,n){if(!Array.isArray(e))return{ok:!1,errors:[N("invalid-field",`${t} must be an array`,t)]};let r=[],i=[];return e.forEach((o,a)=>{let s=`${t}[${a}]`;if(typeof o!="string"||o.length===0){r.push(N("invalid-field",`${t} entries must be non-empty strings`,s));return}let d=n(o,s);d?r.push(d):i.push(o)}),r.length>0?{ok:!1,errors:r}:{ok:!0,values:i}}function De(e,t){return qt(e,t,(n,r)=>Fo(n)?void 0:N("invalid-pattern",`invalid event pattern "${n}"`,r))}function he(e,t,n,r,i){return qt(e,t,(o,a)=>n.has(o)?void 0:N(r,`invalid ${i} "${o}"`,a))}function Ar(e,t){return qt(e,t,(n,r)=>/^[a-z0-9][a-z0-9.-]*$/i.test(n)?void 0:N("invalid-feature",`invalid feature tag "${n}"`,r))}function Vo(e){if(!ce(e))return[N("invalid-manifest","capability manifest must be a JSON object")];let t=[...de(e,Mo,"")];if(e.version!==void 0&&e.version!==1&&t.push(N("invalid-version","capability manifest version must be 1","version")),(typeof e.id!="string"||e.id.length===0)&&t.push(N("invalid-id","id is required","id")),!ce(e.runtime))t.push(N("invalid-runtime","runtime is required","runtime"));else{t.push(...de(e.runtime,Do,"runtime"));let s=e.runtime.minContractVersion;(typeof s!="number"||!Number.isInteger(s)||s<1)&&t.push(N("invalid-runtime","runtime.minContractVersion must be an integer >= 1","runtime.minContractVersion"));let d=Ar(e.runtime.features,"runtime.features");d.ok||t.push(...d.errors)}let n=he(e.phases,"phases",Io,"invalid-phase","phase");n.ok||t.push(...n.errors);let r=he(e.managers,"managers",br,"invalid-manager","manager");if(r.ok||t.push(...r.errors),!ce(e.assets))t.push(N("invalid-assets","assets is required","assets"));else{t.push(...de(e.assets,Oo,"assets"));let s=he(e.assets.kinds,"assets.kinds",mr,"invalid-asset-kind","asset kind");s.ok||t.push(...s.errors),Array.isArray(e.assets.declarations)?e.assets.declarations.forEach((d,E)=>{let g=`assets.declarations[${E}]`;if(!ce(d)){t.push(N("invalid-assets","asset declaration must be an object",g));return}t.push(...de(d,_o,g)),(typeof d.id!="string"||d.id.length===0)&&t.push(N("invalid-assets","asset declaration id is required",`${g}.id`)),(typeof d.kind!="string"||!mr.has(d.kind))&&t.push(N("invalid-asset-kind",`invalid asset kind "${String(d.kind)}"`,`${g}.kind`))}):t.push(N("invalid-assets","assets.declarations must be an array","assets.declarations"))}let i=De(e.acceptedEvents,"acceptedEvents");i.ok||t.push(...i.errors);let o=De(e.emittedEvents,"emittedEvents");if(o.ok||t.push(...o.errors),!ce(e.permissions))t.push(N("invalid-permissions","permissions is required","permissions"));else{t.push(...de(e.permissions,Lo,"permissions"));let s=De(e.permissions.emit,"permissions.emit");s.ok||t.push(...s.errors);let d=De(e.permissions.subscribe,"permissions.subscribe");d.ok||t.push(...d.errors),e.permissions.authoritative!==void 0&&typeof e.permissions.authoritative!="boolean"&&t.push(N("invalid-permissions","permissions.authoritative must be a boolean","permissions.authoritative"))}let a=he(e.integrations,"integrations",vr,"invalid-integration","integration");if(a.ok||t.push(...a.errors),e.surface!==void 0&&(ce(e.surface)?(t.push(...de(e.surface,Er,"surface")),e.surface.alpha!==void 0&&typeof e.surface.alpha!="boolean"&&t.push(N("invalid-surface","surface.alpha must be a boolean","surface.alpha")),e.surface.clearPolicy!==void 0&&(typeof e.surface.clearPolicy!="string"||!Sr.has(e.surface.clearPolicy))&&t.push(N("invalid-clear-policy",`invalid clear policy "${String(e.surface.clearPolicy)}"`,"surface.clearPolicy"))):t.push(N("invalid-surface","surface must be an object","surface"))),e.layers!==void 0){if(!ce(e.layers))t.push(N("invalid-layers","layers must be an object","layers"));else if(t.push(...de(e.layers,wr,"layers")),e.layers.compositor!==void 0&&typeof e.layers.compositor!="boolean"&&t.push(N("invalid-layers","layers.compositor must be a boolean","layers.compositor")),e.layers.blend!==void 0){let s=he(e.layers.blend,"layers.blend",Cr,"invalid-blend","blend mode");s.ok||t.push(...s.errors)}}return t}function Bo(e){let t=[];return e.emittedEvents.forEach((n,r)=>{pt(n,e.permissions.emit)||t.push(N("undeclared-permission",`emitted event "${n}" is not covered by permissions.emit`,`emittedEvents[${r}]`))}),e.acceptedEvents.forEach((n,r)=>{pt(n,e.permissions.subscribe)||t.push(N("undeclared-permission",`accepted event "${n}" is not covered by permissions.subscribe`,`acceptedEvents[${r}]`))}),t}function Ko(e){let t=$e(e.assets.kinds),n=e.assets.declarations.map(o=>({id:o.id,kind:o.kind})),r={emit:[...e.permissions.emit],subscribe:[...e.permissions.subscribe]};e.permissions.authoritative===!0&&(r.authoritative=!0);let i={version:1,id:e.id,runtime:{minContractVersion:e.runtime.minContractVersion,features:[...e.runtime.features]},phases:$e(e.phases),managers:$e(e.managers),assets:{kinds:t,declarations:n},acceptedEvents:[...e.acceptedEvents],emittedEvents:[...e.emittedEvents],permissions:r,integrations:$e(e.integrations)};if(e.surface){let o={};e.surface.alpha===!0&&(o.alpha=!0),e.surface.clearPolicy&&(o.clearPolicy=e.surface.clearPolicy),(o.alpha!==void 0||o.clearPolicy!==void 0)&&(i.surface=o)}if(e.layers){let o={};e.layers.compositor===!0&&(o.compositor=!0),e.layers.blend&&e.layers.blend.length>0&&(o.blend=$e(e.layers.blend)),(o.compositor!==void 0||o.blend!==void 0)&&(i.layers=o)}return i}function Wt(e){let t=Vo(e);if(t.length>0)return{ok:!1,errors:t};let n=Ko(e);return t.push(...Bo(n)),t.length>0?{ok:!1,errors:t}:{ok:!0,manifest:n}}function $o(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return{ok:!1,errors:[N("invalid-json","capability manifest JSON is not parseable")]}}return Wt(t)}function Go(e){return JSON.parse(JSON.stringify(e))}function jo(e,t){let n=Wt(e),r=n.ok?[]:[...n.errors];if(!ce(t))return{ok:!1,errors:[N("invalid-host","host capabilities must be a JSON object")]};r.push(...de(t,No,"host")),typeof t.contractVersion!="number"||!Number.isInteger(t.contractVersion)||t.contractVersion<1?r.push(N("invalid-host","host.contractVersion must be an integer >= 1","host.contractVersion")):n.ok&&t.contractVersion<n.manifest.runtime.minContractVersion&&r.push(N("unsupported-runtime",`host contract version ${t.contractVersion} is below required ${n.manifest.runtime.minContractVersion}`,"runtime.minContractVersion"));let i=Ar(t.features,"host.features");if(!i.ok)r.push(...i.errors);else if(n.ok){let a=new Set(i.values);n.manifest.runtime.features.forEach((s,d)=>{a.has(s)||r.push(N("unsupported-feature",`host does not support required feature "${s}"`,`runtime.features[${d}]`))})}let o=he(t.integrations,"host.integrations",vr,"invalid-integration","integration");if(!o.ok)r.push(...o.errors);else if(n.ok){let a=new Set(o.values);n.manifest.integrations.forEach((s,d)=>{a.has(s)||r.push(N("missing-integration",`host does not provide required integration "${s}"`,`integrations[${d}]`))})}if(t.managers!==void 0){let a=he(t.managers,"host.managers",br,"invalid-manager","manager");if(!a.ok)r.push(...a.errors);else if(n.ok){let s=new Set(a.values);n.manifest.managers.forEach((d,E)=>{s.has(d)||r.push(N("missing-manager",`host does not provide required manager "${d}"`,`managers[${E}]`))})}}if(t.emit!==void 0){let a=De(t.emit,"host.emit");a.ok?n.ok&&n.manifest.permissions.emit.forEach((s,d)=>{pt(s,a.values)||r.push(N("unknown-permission",`host does not allow emit permission "${s}"`,`permissions.emit[${d}]`))}):r.push(...a.errors)}if(t.subscribe!==void 0){let a=De(t.subscribe,"host.subscribe");a.ok?n.ok&&n.manifest.permissions.subscribe.forEach((s,d)=>{pt(s,a.values)||r.push(N("unknown-permission",`host does not allow subscribe permission "${s}"`,`permissions.subscribe[${d}]`))}):r.push(...a.errors)}if(t.surface!==void 0&&(ce(t.surface)?(r.push(...de(t.surface,Er,"host.surface")),t.surface.alpha!==void 0&&typeof t.surface.alpha!="boolean"&&r.push(N("invalid-host","host.surface.alpha must be a boolean","host.surface.alpha")),t.surface.clearPolicy!==void 0&&(Array.isArray(t.surface.clearPolicy)?t.surface.clearPolicy:[t.surface.clearPolicy]).forEach((s,d)=>{(typeof s!="string"||!Sr.has(s))&&r.push(N("invalid-clear-policy",`invalid clear policy "${String(s)}"`,Array.isArray(t.surface?.clearPolicy)?`host.surface.clearPolicy[${d}]`:"host.surface.clearPolicy"))})):r.push(N("invalid-host","host.surface must be an object","host.surface"))),t.layers!==void 0){if(!ce(t.layers))r.push(N("invalid-host","host.layers must be an object","host.layers"));else if(r.push(...de(t.layers,wr,"host.layers")),t.layers.compositor!==void 0&&typeof t.layers.compositor!="boolean"&&r.push(N("invalid-host","host.layers.compositor must be a boolean","host.layers.compositor")),t.layers.blend!==void 0){let a=he(t.layers.blend,"host.layers.blend",Cr,"invalid-blend","blend mode");a.ok||r.push(...a.errors)}}if(n.ok&&n.manifest.surface){let a=n.manifest.surface,s=t.surface;a.alpha===!0&&s?.alpha!==!0&&r.push(N("unsupported-surface","host does not provide an alpha-capable surface","surface.alpha")),a.clearPolicy&&((Array.isArray(s?.clearPolicy)?s.clearPolicy:s?.clearPolicy?[s.clearPolicy]:[]).includes(a.clearPolicy)||r.push(N("unsupported-surface",`host does not provide clear policy "${a.clearPolicy}"`,"surface.clearPolicy")))}if(n.ok&&n.manifest.layers){let a=n.manifest.layers,s=t.layers;if(a.compositor===!0&&s?.compositor!==!0&&r.push(N("unsupported-layer","host does not provide a compositor","layers.compositor")),a.blend){let d=new Set(s?.blend??[]);a.blend.forEach((E,g)=>{d.has(E)||r.push(N("unsupported-layer",`host does not provide blend mode "${E}"`,`layers.blend[${g}]`))})}}return r.length>0?{ok:!1,errors:r}:{ok:!0}}var Uo=1,zo=1e-6,qo=.5,Wo=["normalized","asset","canvas","css","viewport"],Yo=["center","top-left","top-right","bottom-left","bottom-right","top","bottom","left","right"],Jo={center:{x:.5,y:.5},"top-left":{x:0,y:0},"top-right":{x:1,y:0},"bottom-left":{x:0,y:1},"bottom-right":{x:1,y:1},top:{x:.5,y:0},bottom:{x:.5,y:1},left:{x:0,y:.5},right:{x:1,y:.5}};function Xo(e){let t=Jo[e];return{x:t.x,y:t.y}}function Yt(e){let t=e.devicePixelRatio??1,{contentWidth:n,contentHeight:r,viewportWidth:i,viewportHeight:o,mode:a}=e,s=i/n,d=o/r,E=a==="contain"?Math.min(s,d):Math.max(s,d),g=n*E,v=r*E,C=(i-g)/2,x=(o-v)/2,T=ht(-C/g),p=ht(-x/v),m=ht(i/g),_=ht(o/v);return{mode:a,contentWidth:n,contentHeight:r,viewportWidth:i,viewportHeight:o,devicePixelRatio:t,scale:E,offsetX:C,offsetY:x,canvasWidth:i*t,canvasHeight:o*t,visibleNormalizedRect:{x:T,y:p,width:Math.min(m,1-T),height:Math.min(_,1-p)}}}function Qo(e,t){return{x:e.x*t.contentWidth,y:e.y*t.contentHeight}}function Zo(e,t){return{x:e.x/t.contentWidth,y:e.y/t.contentHeight}}function Jt(e,t){return{x:t.offsetX+e.x*t.contentWidth*t.scale,y:t.offsetY+e.y*t.contentHeight*t.scale}}function Xt(e,t){return{x:(e.x-t.offsetX)/(t.contentWidth*t.scale),y:(e.y-t.offsetY)/(t.contentHeight*t.scale)}}function Pr(e,t){return{x:e.x*t.devicePixelRatio,y:e.y*t.devicePixelRatio}}function xr(e,t){return{x:e.x/t.devicePixelRatio,y:e.y/t.devicePixelRatio}}function ea(e,t){return Pr(Jt(e,t),t)}function Tr(e,t){return Xt(xr(e,t),t)}function Qt(e,t){let n=Jt({x:e.x,y:e.y},t);return{x:n.x,y:n.y,width:e.width*t.contentWidth*t.scale,height:e.height*t.contentHeight*t.scale}}function kr(e,t){let n=Qt(e,t),r=t.devicePixelRatio;return{x:n.x*r,y:n.y*r,width:n.width*r,height:n.height*r}}function Zt(e,t,n,r){let o=(r?.space??"canvas")==="css"?Xt(e,t):Tr(e,t);for(let a of n.regions)if(ca(a,o))return a}function en(e,t){let n=Ge(e);if(n)return Qt(n,t)}function ta(e){let t=new Map,n=r=>{if(t.has(r.id))return{ok:!1,error:"duplicate-id",id:r.id};let i={id:r.id,point:{x:r.point.x,y:r.point.y},...r.origin!==void 0?{origin:r.origin}:{}};return t.set(i.id,i),{ok:!0,landmark:i}};if(e)for(let r of e){let i=n(r);if(!i.ok)throw new Error(`Duplicate landmark id: ${i.id}`)}return{register:n,get:r=>t.get(r),list:()=>[...t.values()]}}function na(e){let t=[];e.version!==1&&t.push({code:"version-mismatch",detail:`expected version 1, got ${String(e.version)}`});let n=new Set,r=i=>{if(n.has(i)){t.push({code:"duplicate-id",id:i,detail:`duplicate id ${i}`});return}n.add(i)};for(let i of e.landmarks)r(i.id),Rr(i.point)||t.push({code:"out-of-bounds",id:i.id,detail:`landmark ${i.id} is outside 0\u20131`});for(let i of e.regions){r(i.id);let o=Ge(i);if(!i.rect&&!i.polygon){t.push({code:"invalid-shape",id:i.id,detail:`region ${i.id} has neither rect nor polygon`});continue}if(i.polygon&&i.polygon.length<3&&t.push({code:"invalid-shape",id:i.id,detail:`region ${i.id} polygon needs at least 3 points`}),o&&!aa(o)&&t.push({code:"out-of-bounds",id:i.id,detail:`region ${i.id} is outside 0\u20131`}),i.polygon){for(let a of i.polygon)if(!Rr(a)){t.push({code:"out-of-bounds",id:i.id,detail:`region ${i.id} has a vertex outside 0\u20131`});break}}}for(let i=0;i<e.regions.length;i+=1){let o=e.regions[i],a=Ge(o);if(a)for(let s=i+1;s<e.regions.length;s+=1){let d=e.regions[s],E=Ge(d);E&&sa(a,E)&&t.push({code:"overlap",id:o.id,with:d.id,detail:`region ${o.id} overlaps ${d.id}`})}}return{ok:t.length===0,diagnostics:t}}function ra(e,t,n,r=[]){let i=[],o=(a,s,d)=>{i.push({method:a,id:d,args:s})};for(let a of n.regions){let s=Ge(a);if(!s)continue;let d=kr(s,t);e.fillStyle="rgba(0, 180, 255, 0.15)",e.strokeStyle="#00b4ff",e.fillRect&&e.fillRect(d.x,d.y,d.width,d.height),o("fillRect",[d.x,d.y,d.width,d.height],a.id),e.strokeRect&&e.strokeRect(d.x,d.y,d.width,d.height),o("strokeRect",[d.x,d.y,d.width,d.height],a.id),e.font="12px sans-serif";let E=a.id;e.fillText&&e.fillText(E,d.x+4,d.y+14),o("fillText",[E,d.x+4,d.y+14],a.id)}for(let a of r){let s=a.id?`${a.id}: ${a.code}`:a.code,d=16+i.filter(E=>E.method==="fillText").length*14;e.fillText&&e.fillText(s,8,d),o("fillText",[s,8,d],a.id)}return i}function ia(e){return JSON.stringify(e)}function oa(e){return JSON.parse(e)}function ht(e){return e<=0?0:e>=1?1:e}function Rr(e){return e.x>=0&&e.x<=1&&e.y>=0&&e.y<=1}function aa(e){return e.x>=0&&e.y>=0&&e.width>=0&&e.height>=0&&e.x+e.width<=1&&e.y+e.height<=1}function sa(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function Ge(e){if(e.rect)return e.rect;if(!e.polygon||e.polygon.length===0)return;let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let o of e.polygon)t=Math.min(t,o.x),n=Math.min(n,o.y),r=Math.max(r,o.x),i=Math.max(i,o.y);return{x:t,y:n,width:r-t,height:i-n}}function ca(e,t){return e.polygon&&e.polygon.length>=3?da(t,e.polygon):e.rect?t.x>=e.rect.x&&t.x<e.rect.x+e.rect.width&&t.y>=e.rect.y&&t.y<e.rect.y+e.rect.height:!1}function da(e,t){let n=!1;for(let r=0,i=t.length-1;r<t.length;i=r,r+=1){let o=t[r],a=t[i];o.y>e.y!=a.y>e.y&&e.x<(a.x-o.x)*(e.y-o.y)/(a.y-o.y)+o.x&&(n=!n)}return n}var Mr=320,Dr=180,ua=1024,la="Runtime group has been destroyed";function pa(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 ma(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 Or(e){let t=e.capability,n={},r=e.emit??t?.emit,i=e.subscribe??t?.subscribe,o=e.authoritative??t?.authoritative;return r&&(n.emit=r),i&&(n.subscribe=i),o!==void 0&&(n.authoritative=o),n}function Ir(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function fa(e){let t=new Set([se,"*.*","*.*.*","*.*.*.*","*.*.*.*.*"]);for(let n of e){let r=Or(n);for(let i of r.emit??[])t.add(i);for(let i of r.subscribe??[])t.add(i)}return[...t]}function tn(e){if(!e.participants.length)throw new Error("createRuntimeGroup: at least one participant is required");let t=new Set;for(let c of e.participants){if(!c.id)throw new Error("createRuntimeGroup: participant id is required");if(t.has(c.id))throw new Error(`createRuntimeGroup: duplicate participant id "${c.id}"`);t.add(c.id)}let n=e.origin??0,r=e.width??Mr,i=e.height??Dr,o=e.maxTrace??ua,a=[...e.participants].sort((c,f)=>c.id.localeCompare(f.id)),s=[],d=new Map,E=0,g=e.createId??e.router?.createId??(()=>`evt-${++E}`),v=e.now??e.router?.now??(()=>{let c=s[0];if(!c)return n;try{return c.cart.getClock().now}catch{return n}}),C=Ft({...e.router,createId:g,now:v,validate:e.validate??e.router?.validate}),x=[],T=!1,p=!1,m=()=>{},_=c=>f=>{c.events.push(f),c.userOnEvent?.(f)},M=()=>{if(p)throw new Error(la)},W=()=>{m();for(let c of s){try{C.detach(c.id)}catch{}try{c.runtime.destroy()}catch{}c.ownsContainer&&c.container.remove()}s.length=0,d.clear()};try{for(let c of a){let f=c.width??r,P=c.height??i,F=!c.container,O=c.container??ma(f,P),j=Ot({container:O,seed:c.seed??pa(c.id),deterministic:{origin:n}}),q={id:c.id,kind:c.kind??"render",cartDef:c.cart,initialState:c.initialState,gameManager:c.gameManager,userOnEvent:c.onEvent,runtime:j,container:O,ownsContainer:F,cart:void 0,events:[],errors:[]};j.onError=(l,w)=>{q.errors.push({error:l,info:w})},C.attach(c.id,j.hostChannel,Or(c)),q.cart=j.mount(c.cart,{initialState:c.initialState,gameManager:c.gameManager,onEvent:_(q)}),s.push(q),d.set(q.id,q)}m=C.subscribe(fa(a),c=>{for(x.push(Ir(c));x.length>o;)x.shift()})}catch(c){throw W(),c}let b=c=>({id:c.id,kind:c.kind,runtime:c.runtime,container:c.container,get events(){return c.events.slice()},get errors(){return c.errors.slice()},get cart(){return c.cart}});return{router:C,origin:n,get paused(){return T},participant(c){M();let f=d.get(c);if(!f)throw new Error(`createRuntimeGroup: unknown participant "${c}"`);return b(f)},async step(c=1){if(M(),T)return;let f=Math.max(0,Math.floor(c));for(let P=0;P<f;P++){C.turn();for(let F of s)try{await F.cart.step(1)}catch(O){F.errors.push({error:O,info:{phase:"update",consecutive:F.errors.length+1,stopped:!1}})}}},pause(){M(),T=!0;for(let c of s)c.cart.pause()},resume(){M(),T=!1;for(let c of s)c.cart.resume()},reset(){M(),x.length=0;for(let c of s)c.events.length=0,c.errors.length=0,c.cart=c.runtime.mount(c.cartDef,{initialState:c.initialState,gameManager:c.gameManager,onEvent:_(c)});C.turn()},resize(c,f){M();let P=Math.max(1,c|0),F=Math.max(1,f|0);for(let O of s){Object.defineProperty(O.container,"clientWidth",{value:P,configurable:!0}),Object.defineProperty(O.container,"clientHeight",{value:F,configurable:!0});let j=O.cart.canvas;j&&(j.width=P,j.height=F)}},detach(c){M();let f=d.get(c);if(!f)throw new Error(`createRuntimeGroup: unknown participant "${c}"`);try{C.detach(f.id)}catch{}try{f.runtime.destroy()}catch{}f.ownsContainer&&f.container.remove();let P=s.indexOf(f);P>=0&&s.splice(P,1),d.delete(c)},dispatch(c,f){M();let P=d.get(c);if(!P)throw new Error(`createRuntimeGroup: unknown participant "${c}"`);P.cart.dispatch(f)},publish(c,f){return M(),C.publish(c,f)},inspectParticipants(){M();let c=new Map(s.map(f=>[f.id,f.kind]));return C.inspectParticipants().map(f=>({...f,kind:c.get(f.id)??"render"}))},async inspect(){M();let c={},f={},P=new Map(C.inspectParticipants().map(O=>[O.id,O]));for(let O of s){let j=await O.cart.getReplayMetadata(),q=O.cart.getClock();f[O.id]=q;let l=P.get(O.id);c[O.id]={state:j.state,events:O.events.slice(),errors:O.errors.slice(),kind:O.kind,clock:q,emit:l?.emit.slice()??[],subscribe:l?.subscribe.slice()??[],authoritative:l?.authoritative===!0}}let F=x.map(O=>Ir(O));return{participants:c,trace:F,diagnostics:{paused:T,participantIds:s.map(O=>O.id),clocks:f,rejections:F.filter(O=>O.type===se).map(O=>O.payload)}}},destroy(){if(!p){p=!0,T=!1;try{W()}finally{x.length=0}}}}}var yt=1,Fr=512,Hr="[REDACTED]",ha=new Set([ye,ge]);function X(e){try{return JSON.parse(JSON.stringify(e))}catch{return e}}function gt(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(i=>gt(i,t));if(typeof e!="object")return e;let n=e,r={};for(let[i,o]of Object.entries(n))r[i]=t.has(i)?Hr:gt(o,t);return r}function ya(e){return e instanceof Error&&typeof e.message=="string"?e.message:"error"}function ga(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 _r(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 ba(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=_r(e[n]),i=_r(t[n]);if(r!==i)return{ok:!1,detail:`record ${n} differs`}}return{ok:!0}}function Lr(e){let t=new Map,n=[];for(let o of e){if(o.outcome==="duplicate"){n.push(void 0);continue}let a={envelopeId:o.envelopeId,type:o.type,source:o.source,outcome:o.outcome,children:[]};o.reason&&(a.reason=o.reason),n.push(a),o.envelopeId&&!t.has(o.envelopeId)&&t.set(o.envelopeId,a)}let r=new Set;for(let o=0;o<e.length;o++){let a=e[o],s=n[o];if(!s)continue;let d=a.causationId?t.get(a.causationId):void 0;d&&d!==s&&(d.children.push(s),r.add(s))}let i=[];for(let o of n)o&&!r.has(o)&&i.push(o);return i}function Nr(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 va(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:X(t.clock),state:gt(t.state,n),errorCount:t.errors.length};return r&&(i.lastError=ya(r.error)),i}function Vr(e={}){let t=new Set(e.redactedKeys??[]),n=e.maxRecords??Fr,r=e.registry,i=0,o=0,a=!1,s=[],d=[],E,g=[],v=0,C=[],x={},T=()=>{},p=()=>{if(a)throw new Error("Replay inspector has been destroyed")},m=b=>{let y=r?.get(b.type),c={index:o,turn:b.turn,time:b.time,outcome:b.outcome,source:b.source,type:b.type,deliveredTo:b.deliveredTo.slice(),payload:gt(b.payload,t)};for(o+=1,b.reason&&(c.reason=b.reason),b.detail&&(c.detail=b.detail),b.target&&(c.target=b.target),b.kind&&(c.kind=b.kind),b.envelopeId&&(c.envelopeId=b.envelopeId),b.priorEnvelopeId&&(c.priorEnvelopeId=b.priorEnvelopeId),b.correlationId&&(c.correlationId=b.correlationId),b.causationId&&(c.causationId=b.causationId),b.hops!==void 0&&(c.hops=b.hops),b.seq!==void 0&&(c.seq=b.seq),b.idempotencyKey&&(c.idempotencyKey=b.idempotencyKey),b.schemaVersion!==void 0&&(c.schemaVersion=b.schemaVersion),y&&(c.payloadSchemaVersion=y.payloadSchema.version),s.push(c);s.length>n;)s.shift(),i+=1},_=b=>s.filter(y=>ga(y,b)).map(y=>X(y)),M=b=>b?b.inspectParticipants().map(y=>Nr(y,y.kind)):C.map(y=>X(y)),W={watchRouter(b){if(p(),T(),C=b.inspectParticipants().map(c=>Nr(c)),s.length===0)for(let c of b.inspectDecisions())m(c);let y=b.subscribeDecision(c=>m(c));return T=()=>{y(),T=()=>{}},d.push(T),T},bind(b){p(),E&&T(),E=b,v=b.origin,W.watchRouter(b.router),C=M(b);let y={publish(c,f){p();let P={kind:"publish",event:X(c)};return f?.cause&&(P.extras={cause:X(f.cause)}),g.push(P),b.publish(c,f)},dispatch(c,f){p();let P=X(f);typeof P.type=="string"&&ha.has(P.type)?g.push({kind:"asset",participantId:c,event:P}):g.push({kind:"dispatch",participantId:c,event:P}),b.dispatch(c,f)},async step(c=1){p(),g.push({kind:"step",frames:c}),await b.step(c)},async report(){p();let c=await b.inspect(),f=[];for(let P of Object.keys(c.participants).sort())f.push(va(P,c.participants[P],t));C=f,x={};for(let P of f)x[P.id]=X(P.state);return W.report()},async exportTrace(c){return await y.report(),W.exportTrace(c)},unbind(){T(),E=void 0}};return y},importTrace(b){p();let y=typeof b=="string"?JSON.parse(b):b;if(y.schemaVersion!==yt)throw new Error("Replay inspector: unsupported export schemaVersion");i=0,o=0,s.length=0,g=X(y.tape??[]),v=y.origin??0,C=X(y.participants??[]),x=X(y.snapshots??{});for(let c of y.records??[])m({outcome:c.outcome,reason:c.reason,detail:c.detail,source:c.source,type:c.type,kind:c.kind,envelopeId:c.envelopeId,priorEnvelopeId:c.priorEnvelopeId,target:c.target,deliveredTo:c.deliveredTo,hops:c.hops,seq:c.seq,correlationId:c.correlationId,causationId:c.causationId,idempotencyKey:c.idempotencyKey,schemaVersion:c.schemaVersion,payload:c.payload,turn:c.turn,time:c.time})},exportTrace(b){return p(),{schemaVersion:yt,origin:v,redactedKeys:[...t],participants:X(C),tape:X(g),records:_(b),snapshots:X(x)}},report(b){p();let y=_(b);return{schemaVersion:yt,participants:X(C),records:y,trees:Lr(y),dropped:i}},causationTree(b){p();let y=_(b?{correlationId:b}:void 0);return Lr(y)},records(){return p(),s.map(b=>X(b))},reset(){p(),s.length=0,g=[],i=0,o=0,x={},E&&(C=M(E))},destroy(){if(!a){for(a=!0,T();d.length>0;)d.pop()?.();s.length=0,g=[],C=[],x={},E=void 0}}};return W}async function Ea(e,t,n={}){let r=Vr({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 o=await i.report();return{inspector:r,report:o}}catch(o){throw r.destroy(),o}}var wa=mt,Ca=ft,Sa="Compositor has been destroyed";function Aa(e){return Number.isFinite(e)?e<0?0:e>1?1:e:1}function Ra(e){let t=e.trim().toLowerCase();if(t[0]!=="#")throw new Error(`createCompositor: host.color must be #rgb or #rrggbb, got "${e}"`);let n=t.slice(1);if(n.length===3)return{r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:255};if(n.length===6)return{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16),a:255};throw new Error(`createCompositor: host.color must be #rgb or #rrggbb, got "${e}"`)}function Br(e,t){if(!e.id)throw new Error("createCompositor: layer id is required");if(!Number.isFinite(e.order))throw new Error(`createCompositor: layer "${e.id}" order is required`);let n=e.blend??"source-over";if(n!=="source-over"&&n!=="screen")throw new Error(`createCompositor: layer "${e.id}" blend must be source-over or screen`);let r=e.pointerEvents??"auto";if(r!=="auto"&&r!=="none")throw new Error(`createCompositor: layer "${e.id}" pointerEvents must be auto or none`);let i=e.clearPolicy??t;if(i!=="transparent"&&i!=="opaque")throw new Error(`createCompositor: layer "${e.id}" clearPolicy is invalid`);return{id:e.id,order:e.order,visible:e.visible!==!1,opacity:Aa(e.opacity??1),blend:n,clip:e.clip?{...e.clip}:null,pointerEvents:r,clearPolicy:i}}function Pa(e){return[...e].sort((t,n)=>t.order-n.order||t.id.localeCompare(n.id))}function nn(e,t){return 255-Math.round((255-e)*(255-t)/255)}function xa(e,t,n,r,i,o,a,s){let d=o/255*a;if(d<=0)return;let E=e[t],g=e[t+1],v=e[t+2],C=e[t+3]/255,x=n,T=r,p=i;s==="screen"&&(x=nn(E,n),T=nn(g,r),p=nn(v,i));let m=d+C*(1-d);if(m<=0){e[t]=0,e[t+1]=0,e[t+2]=0,e[t+3]=0;return}e[t]=Math.round((x*d+E*C*(1-d))/m),e[t+1]=Math.round((T*d+g*C*(1-d))/m),e[t+2]=Math.round((p*d+v*C*(1-d))/m),e[t+3]=Math.round(m*255)}function Ta(e,t,n){if(e.width===t&&e.height===n)return{data:new Uint8ClampedArray(e.data),width:t,height:n,colorSpace:e.colorSpace??"srgb"};let r=new Uint8ClampedArray(t*n*4);for(let i=0;i<n;i++){let o=Math.min(e.height-1,Math.floor(i*e.height/n));for(let a=0;a<t;a++){let s=Math.min(e.width-1,Math.floor(a*e.width/t)),d=(o*e.width+s)*4,E=(i*t+a)*4;r[E]=e.data[d],r[E+1]=e.data[d+1],r[E+2]=e.data[d+2],r[E+3]=e.data[d+3]}}return{data:r,width:t,height:n,colorSpace:e.colorSpace??"srgb"}}function ka(e,t){for(let n=0;n<e.length;n+=4)e[n]=t.r,e[n+1]=t.g,e[n+2]=t.b,e[n+3]=t.a}function Kr(e,t,n){return e?t>=e.x&&n>=e.y&&t<e.x+e.width&&n<e.y+e.height:!0}function Ia(e){let t=e.getContext("2d");if(!t)throw new Error("createCompositor: layer canvas has no 2d context");return t.getImageData(0,0,e.width,e.height)}function rn(e,t){e&&(e.style.zIndex=String(t.order),e.style.pointerEvents=t.pointerEvents==="none"?"none":"auto",e.style.visibility=t.visible?"visible":"hidden")}function on(e){if(!e.layers.length)throw new Error("createCompositor: at least one layer is required");let t=new Set,n=e.clearPolicy??"transparent";if(n!=="transparent"&&n!=="opaque")throw new Error("createCompositor: clearPolicy must be transparent or opaque");let r=new Map;for(let y of e.layers){let c=Br(y,n);if(t.has(c.id))throw new Error(`createCompositor: duplicate layer id "${c.id}"`);t.add(c.id),r.set(c.id,c)}let i=e.group,o=e.dpr&&e.dpr>0?e.dpr:1,a=Math.max(1,(e.width??320)|0),s=Math.max(1,(e.height??180)|0),d=o,E=e.offscreen!==!1,g=!e.target;if(!E&&!e.target)throw new Error("createCompositor: target canvas is required when offscreen is false");let v=e.target??document.createElement("canvas"),C=v.getContext("2d",{alpha:!0});if(!C)throw new Error("createCompositor: host canvas has no 2d context");let x=!1,T=()=>{if(x)throw new Error(Sa)},p=()=>({width:Math.max(1,Math.round(a*d)),height:Math.max(1,Math.round(s*d))}),m=()=>{let y=p();v.width!==y.width&&(v.width=y.width),v.height!==y.height&&(v.height=y.height),v.style.width=`${a}px`,v.style.height=`${s}px`},_=()=>Pa([...r.values()]).map(y=>({...y,clip:y.clip?{...y.clip}:null})),M=(y,c,f)=>{if(y.fill(0),n==="opaque"&&!e.host?.image&&!e.host?.color&&y.fill(0),e.host?.image){let P=Ta(e.host.image,c,f);y.set(P.data);return}e.host?.color&&ka(y,Ra(e.host.color))},W=()=>{let{width:y,height:c}=p();m();let f=C.createImageData(y,c);M(f.data,y,c);for(let P of _()){if(!P.visible||P.opacity<=0)continue;let F;try{F=i.participant(P.id)}catch{continue}let O=F.cart.canvas;if(!O)continue;rn(O,P);let j;try{j=Ia(O)}catch{continue}let q=P.clearPolicy==="transparent",l=Math.min(y,j.width),w=Math.min(c,j.height);for(let S=0;S<w;S++)for(let L=0;L<l;L++){if(!Kr(P.clip,L,S))continue;let U=(S*j.width+L)*4,G=j.data[U],D=j.data[U+1],V=j.data[U+2],z=j.data[U+3];q&&G===0&&D===0&&V===0||z<=0||xa(f.data,(S*y+L)*4,G,D,V,z,P.opacity,P.blend)}}return C.putImageData(f,0,0),f};m();for(let y of _())try{rn(i.participant(y.id).cart.canvas,y)}catch{}return{get canvas(){return v},get width(){return a},get height(){return s},get dpr(){return d},compose(){return T(),W()},captureComposedFrame(){T();let y=W();return{imageData:y,pngDataUrl:v.toDataURL("image/png"),width:y.width,height:y.height,declaredOrder:_()}},resize(y,c,f){T(),a=Math.max(1,y|0),s=Math.max(1,c|0),f!==void 0&&(d=f>0?f:1);let P=p();i.resize(P.width,P.height),m()},setLayer(y,c){T();let f=r.get(y);if(!f)throw new Error(`createCompositor: unknown layer "${y}"`);let P=Br({id:y,order:c.order??f.order,visible:c.visible??f.visible,opacity:c.opacity??f.opacity,blend:c.blend??f.blend,clip:c.clip===void 0?f.clip??void 0:c.clip,pointerEvents:c.pointerEvents??f.pointerEvents,clearPolicy:c.clearPolicy??f.clearPolicy},n);r.set(y,P);try{rn(i.participant(y).cart.canvas,P)}catch{}},layer(y){T();let c=r.get(y);if(!c)throw new Error(`createCompositor: unknown layer "${y}"`);return{...c,clip:c.clip?{...c.clip}:null}},layers(){return T(),_()},pointerTarget(y,c){T();let f=y|0,P=c|0,F=[..._()].reverse();for(let O of F)if(!(!O.visible||O.pointerEvents==="none")&&Kr(O.clip,f,P)){try{i.participant(O.id)}catch{continue}return O.id}},unmountLayer(y){if(T(),!r.has(y))throw new Error(`createCompositor: unknown layer "${y}"`);r.delete(y),i.detach(y)},inspect(){T();let y=_();return{viewport:{width:a,height:s,dpr:d},clearPolicy:n,layers:y,declaredOrder:y.map(c=>c.id)}},destroy(){x||(x=!0,g&&v.parentNode&&v.remove())}}}var bt={width:320,height:180,deviceScaleFactor:1},Ma="Browser harness has been destroyed";function Da(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([\0-\x1f\x7f!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function an(e){return{...e,visibleNormalizedRect:{...e.visibleNormalizedRect}}}function sn(e,t,n){Object.defineProperty(e,"clientWidth",{value:t,configurable:!0}),Object.defineProperty(e,"clientHeight",{value:n,configurable:!0})}function cn(e,t,n,r,i){let o={x:t,y:n,width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,toJSON(){return this}};e.getBoundingClientRect=()=>o}function $r(e){return!e||!(e instanceof HTMLElement)||e===document.body?{tag:"body",id:"",role:null,name:""}:{tag:e.tagName.toLowerCase(),id:e.id,role:e.getAttribute("role"),name:e.getAttribute("aria-label")??e.textContent?.trim()??""}}function Oa(e){return e.querySelector("[aria-live]")?.textContent??""}function Gr(e,t,n){let r={bubbles:!0,cancelable:!0,clientX:t,clientY:n},i=globalThis.PointerEvent;typeof i=="function"?(e.dispatchEvent(new i("pointerdown",{...r,pointerId:1,pointerType:"mouse",buttons:1})),e.dispatchEvent(new i("pointerup",{...r,pointerId:1,pointerType:"mouse",buttons:0}))):(e.dispatchEvent(new MouseEvent("mousedown",r)),e.dispatchEvent(new MouseEvent("mouseup",r))),e.dispatchEvent(new MouseEvent("click",r))}function _a(e,t,n){let r=Array.from(e.querySelectorAll("*")),i=null,o=Number.POSITIVE_INFINITY;for(let a of r){if(!(a instanceof HTMLElement))continue;let s=a.getBoundingClientRect();if(t>=s.left&&t<s.right&&n>=s.top&&n<s.bottom){let d=Math.max(1,s.width*s.height);d<=o&&(i=a,o=d)}}return i??e}function jr(e){let t=window.matchMedia;return window.matchMedia=n=>({matches:e&&/prefers-reduced-motion:\s*reduce/i.test(n),media:n,onchange:null,addListener(){},removeListener(){},addEventListener(){},removeEventListener(){},dispatchEvent(){return!1}}),()=>{window.matchMedia=t}}function La(e={}){let t=e.seed??`0x${"00".repeat(32)}`,n=e.geometry,r=e.viewport?.width??bt.width,i=e.viewport?.height??bt.height,o=e.viewport?.deviceScaleFactor??bt.deviceScaleFactor,a=e.reducedMotion===!0,s=e.inputModality??"pointer",d=e.origin??0,E=e.fit??"contain",g=Object.getOwnPropertyDescriptor(window,"devicePixelRatio"),v=Object.getOwnPropertyDescriptor(window,"innerWidth"),C=Object.getOwnPropertyDescriptor(window,"innerHeight"),x=jr(a),T=()=>{Object.defineProperty(window,"devicePixelRatio",{value:o,configurable:!0}),Object.defineProperty(window,"innerWidth",{value:r,configurable:!0}),Object.defineProperty(window,"innerHeight",{value:i,configurable:!0})};T();let p=document.createElement("div");p.setAttribute("data-cyberart-browser-harness",""),p.style.position="relative",p.style.overflow="auto",p.tabIndex=-1,document.body.appendChild(p);let m=[],_=[],M=!1,W=0,b=e.createId??(()=>`br-${++W}`),y=()=>Yt({contentWidth:e.contentWidth??r,contentHeight:e.contentHeight??i,viewportWidth:r,viewportHeight:i,mode:E,devicePixelRatio:o}),c=y(),f=()=>Math.max(1,Math.round(r*o)),P=()=>Math.max(1,Math.round(i*o)),F=(A,B)=>{let K=n?.regions.find(te=>te.id===A);if(!K)return;let $=en(K,c);if($)return B.style.position=B.style.position||"absolute",B.style.left=`${$.x}px`,B.style.top=`${$.y}px`,B.style.width=`${$.width}px`,B.style.height=`${$.height}px`,cn(B,$.x,$.y,$.width,$.height),{...$}},O=()=>{c=y(),p.style.width=`${r}px`,p.style.height=`${i}px`,sn(p,r,i),cn(p,0,0,r,i),p.dataset.inputModality=s,p.dataset.reducedMotion=a?"true":"false",T()};O();let j=()=>({root:p,get layout(){return an(c)},get reducedMotion(){return a},get inputModality(){return s},placeRegion:F}),q=e.mount?.(j())??{},l=q.participants??[],w,S,L=()=>{};if(l.length>0){for(let A of l)A.container&&sn(A.container,f(),P());w=tn({origin:d,width:f(),height:P(),createId:b,now:()=>d,participants:l.map(A=>({...A,seed:A.seed??t,width:A.width??f(),height:A.height??P()}))}),L=w.router.subscribe(["*.*","*.*.*","*.*.*.*","*.*.*.*.*",se],A=>{_.push(A)}),q.compositor&&(S=on({...q.compositor,group:w,width:r,height:i,dpr:o}))}let U=()=>({...j(),group:w,compositor:S,publish(A){if(!w)throw new Error("Browser harness: publish requires mounted carts");return w.publish(A)}}),G=()=>{if(O(),w){let A=f(),B=P();for(let K of l){K.container&&(sn(K.container,A,B),K.container.style.width=`${r}px`,K.container.style.height=`${i}px`);try{let $=w.participant(K.id).cart.canvas;$&&($.style.width=`${r}px`,$.style.height=`${i}px`,cn($,0,0,r,i))}catch{}}}},D=()=>{if(M)throw new Error(Ma)};G(),q.ready?.(U());let V=(A,B,K)=>{if(m.push({type:"click",x:A,y:B,...K?{selector:K}:{}}),K){let Ue=p.querySelector(K);if(!(Ue instanceof HTMLElement))throw new Error(`No element matches ${K}`);Gr(Ue,A,B);return}let $=n!==void 0?Zt({x:A,y:B},c,n,{space:"css"}):void 0,je=($?p.querySelector(`#${Da($.id)}`):null)??_a(p,A,B);Gr(je,A,B)};return{root:p,get group(){return w},get compositor(){return S},get layout(){return an(c)},get events(){return _.slice()},goto(){D()},setViewport(A,B,K){D(),r=Math.max(1,A|0),i=Math.max(1,B|0),K!==void 0&&(o=K>0?K:1),m.push({type:"viewport",width:r,height:i,dpr:o}),S?S.resize(r,i,o):w&&w.resize(f(),P()),G(),q.relayout?.(U())},setReducedMotion(A){D(),a=A,x(),x=jr(a),m.push({type:"reducedMotion",value:A}),G(),q.relayout?.(U())},setInputModality(A){D(),s=A,m.push({type:"inputModality",value:A}),G()},click(A,B){if(D(),typeof A=="string"){let K=p.querySelector(A);if(!(K instanceof HTMLElement))throw new Error(`No element matches ${A}`);let $=K.getBoundingClientRect();V($.left+$.width/2,$.top+$.height/2,A);return}if(B===void 0)throw new Error("click(x, y) requires a y coordinate");V(A,B)},key(A){D(),m.push({type:"key",key:A}),(document.activeElement instanceof HTMLElement?document.activeElement:p).dispatchEvent(new KeyboardEvent("keydown",{key:A,bubbles:!0,cancelable:!0}))},focus(A){D();let B=p.querySelector(A);if(!(B instanceof HTMLElement))throw new Error(`No element matches ${A}`);B.focus()},async step(A=1){D(),m.push({type:"step",frames:A}),w&&await w.step(A)},async advance(A){D(),m.push({type:"advance",ms:A}),w&&await w.step(Math.max(0,Math.round(A/1e3*30)))},screenshot(){if(D(),S){let A=S.captureComposedFrame();return{imageData:A.imageData,pngDataUrl:A.pngDataUrl,html:p.outerHTML,declaredOrder:A.declaredOrder.map(B=>B.id)}}return{imageData:null,pngDataUrl:null,html:p.outerHTML,declaredOrder:[]}},accessibilitySnapshot(){return D(),{focus:$r(document.activeElement),live:Oa(p),html:p.outerHTML}},async inspect(){D();let A={},B={},K=0;if(w){let $=await w.inspect();for(let te of $.diagnostics.participantIds)A[te]=w.participant(te).events.slice(),B[te]=$.participants[te]?.state,K=$.diagnostics.clocks[te]?.framesElapsed??K}return{host:q.hostState?.()??null,layout:an(c),events:_.slice(),participantEvents:A,state:B,focus:$r(document.activeElement),scrollTop:p.scrollTop,clock:{framesElapsed:K}}},reproduction(){return D(),{seed:t,viewport:{width:r,height:i,dpr:o},reducedMotion:a,inputModality:s,actions:m.map(A=>({...A}))}},captureComposedFrame(){if(D(),!S)throw new Error("Browser harness: captureComposedFrame requires a compositor");return S.captureComposedFrame()},destroy(){if(!M){M=!0,L(),document.activeElement instanceof HTMLElement&&p.contains(document.activeElement)&&document.activeElement.blur();try{q.destroy?.()}finally{try{S?.destroy()}finally{try{w?.destroy()}finally{p.remove(),x(),g&&Object.defineProperty(window,"devicePixelRatio",g),v&&Object.defineProperty(window,"innerWidth",v),C&&Object.defineProperty(window,"innerHeight",C)}}}}}}}function Na(e){return{async goto(){e.goto()},async setViewportSize(t){e.setViewport(t.width,t.height,t.deviceScaleFactor)},async click(t){e.click(t)},async screenshot(){return e.screenshot()},keyboard:{async press(t){e.key(t)}},locator(t){return{async click(){e.click(t)},async focus(){e.focus(t)}}},async close(){e.destroy()}}}export{Yo as ANCHOR_ORIGINS,ge as ASSET_FAILED_EVENT,Kn as ASSET_FAILURE_CODES,Bn as ASSET_KINDS,ye as ASSET_READY_EVENT,yr as CAPABILITY_ASSET_KINDS,mt as CAPABILITY_BLEND_MODES,ft as CAPABILITY_CLEAR_POLICIES,gr as CAPABILITY_INTEGRATIONS,hr as CAPABILITY_MANAGERS,ko as CAPABILITY_MANIFEST_VERSION,fr as CAPABILITY_PHASES,wa as COMPOSITOR_BLEND_MODES,Ca as COMPOSITOR_CLEAR_POLICIES,Wo as COORDINATE_SPACES,Ke as CUE_CANCELLED_EVENT,ut as CUE_COMPLETED_EVENT,Ao as CUE_LIFECYCLE_EVENTS,lt as CUE_REPLACED_EVENT,Be as CUE_STARTED_EVENT,ze as CYBERART_CANVAS_ATTR,bt as DEFAULT_BROWSER_VIEWPORT,Dr as DEFAULT_GROUP_HEIGHT,Mr as DEFAULT_GROUP_WIDTH,at as DEFAULT_MAX_HOPS,Fr as DEFAULT_MAX_INSPECTOR_RECORDS,Ve as EVENT_ENVELOPE_VERSION,Uo as GEOMETRY_CONTRACT_VERSION,Re as HostChannel,ar as INVALID_PRESENTATION_MODEL_MESSAGE,Q as IncompatibleCartStateError,qe as KeyboardManager,Me as PRESENTATION_ADAPTER_VERSION,Kt as PRESENTATION_MODEL_EVENT,or as PRESENTATION_PHASES,ho as PRESENTATION_SUBSCRIBE_PATTERNS,ir as PRESENTATION_UNSUPPORTED_EVENT,We as PointerManager,Hr as REDACTED_VALUE,se as REJECTED_EVENT_TYPE,yt as REPLAY_INSPECTOR_SCHEMA_VERSION,zo as ROUND_TRIP_TOLERANCE,qo as ROUND_TRIP_TOLERANCE_CANVAS_PX,_e as Random,Pe as SILENT_ASSET_FALLBACK_REF,pr as applyCueEasing,be as assetStatusEvent,Zo as assetToNormalized,Hi as attachCartStatePersistence,ur as attachPresentationAdapter,Qe as canonicalizeSeed,xr as canvasToCss,Tr as canvasToNormalized,Go as capabilityManifestToJSON,lo as comparePayloadSchemas,ba as compareReplayTraces,Y as createAssetFailure,Dt as createAssetPreloader,La as createBrowserHarness,on as createCompositor,fo as createContractRegistry,Ft as createEventRouter,Pi as createFixtureAssetResolver,xi as createHostedAssetResolver,ta as createLandmarkRegistry,Na as createPlaywrightCompatibleAdapter,Yt as createPresentationLayout,Bt as createPresentationModelEvent,To as createPresentationTimeline,dr as createReferencePresentationCart,Vr as createReplayInspector,Ot as createRuntime,tn as createRuntimeGroup,Ye as createVirtualClock,Ce as createWallClock,Pr as cssToCanvas,Xt as cssToNormalized,Wt as defineCapabilityManifest,uo as defineDiagnostic,so as defineIntent,co as defineStateEvent,po as deriveAttachOptions,_n as describeReplayMismatch,ra as drawGeometryDebug,nr as familyPatternForType,Zn as inferEventKind,rt as isAssetFailure,Gn as isAssetFailureCode,$n as isAssetKind,Ro as isCueLifecycleType,$t as isPresentationModel,sr as isPresentationPhase,tr as kindSegmentInType,er as matchEventPattern,So as mountPresentationAdapter,st as normalizeEvent,Qo as normalizedToAsset,ea as normalizedToCanvas,Jt as normalizedToCss,$o as parseCapabilityManifest,oa as parseGeometry,Xo as pointFromOrigin,Zt as pointerToRegion,kr as rectToCanvas,Qt as rectToCss,en as regionToViewport,ki as registerCartStateHotkeys,Ea as replayExportedTrace,Ze as resolveRuntimeSeed,zn as rewriteHostedAssetRef,ia as serializeGeometry,jo as validateCapabilityManifest,na as validateGeometry,mo as verifyAttachOptions};
@@ -1,6 +1,6 @@
1
1
  # Asset resolver / preloader
2
2
 
3
- Host-owned URL policy. The engine caches, dedupes, tracks progress, applies timeouts and fallbacks, and (in live mode) dispatches `ASSET_READY_EVENT` / `ASSET_FAILED_EVENT`. Authored carts keep logical refs (`moltazine:post/<id>#primary-image`, `world:asset/…`, `library:…`, or ordinary URLs). Adventure Kit, Cyberart, and a local preview each supply a different `AssetResolver`.
3
+ Host-owned URL policy. The engine caches, dedupes, tracks progress, applies timeouts and fallbacks, and (in live mode) dispatches `ASSET_READY_EVENT` / `ASSET_FAILED_EVENT`. Authored carts keep logical refs (`moltazine:post/<id>#primary-image`, `world:asset/…`, `library:…`, or ordinary URLs). the host, Cyberart, and a local preview each supply a different `AssetResolver`.
4
4
 
5
5
  Deterministic timing: [deterministic mode](deterministic-mode.md). CI: [headless harness](headless-harness.md). Event mailbox: [events](events.md).
6
6
 
@@ -43,7 +43,7 @@ const runtime = createRuntime({
43
43
  });
44
44
 
45
45
  await runtime.assets!.preload([
46
- { id: 'room-bg', ref: 'moltazine:post/porch-1#primary-image', type: 'image' },
46
+ { id: 'backdrop', ref: 'moltazine:post/porch-1#primary-image', type: 'image' },
47
47
  {
48
48
  id: 'ambience',
49
49
  ref: 'world:asset/stream-loop',
@@ -69,7 +69,7 @@ Under `deterministic`, emit and wall-clock timeout are off so scripted `{ type:
69
69
  import type { AssetDeclaration } from '@cyberart-io/engine';
70
70
 
71
71
  const roomBg: AssetDeclaration = {
72
- id: 'room-bg',
72
+ id: 'backdrop',
73
73
  ref: 'moltazine:post/porch-1#primary-image',
74
74
  type: 'image', // 'image' | 'audio' | 'font' | 'spritesheet'
75
75
  integrity: 'sha256-…', // optional; mismatch → `invalid`
@@ -135,7 +135,7 @@ const runtime = createRuntime({
135
135
  seed: 42,
136
136
  deterministic: {
137
137
  actions: [
138
- { type: 'asset', atFrame: 2, id: 'room-bg', status: 'ready' },
138
+ { type: 'asset', atFrame: 2, id: 'backdrop', status: 'ready' },
139
139
  {
140
140
  type: 'asset',
141
141
  atFrame: 3,