@mica-js/widget 0.2.3 → 0.3.0

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
@@ -1,6 +1,7 @@
1
- import { CANVAS_VERSION, applyCanvasCommand, assertCanvasBindings, parseCanvas, parseDeliveryKind, parsePayloadType, validateCanvasBindings } from "@mica-js/core/canvas";
2
- import { createRpc, defineRpcService } from "@mica-js/core/rpc";
1
+ import { parseDeliveryKind, parsePayloadType } from "@mica-js/document/canvas";
2
+ import { timePs } from "@mica-js/core";
3
3
  import { Emitter } from "@mica-js/core/lifecycle";
4
+ import { createRpc, defineRpcService } from "@mica-js/core/rpc";
4
5
  import { loggerService } from "@mica-js/core/logging";
5
6
  import { SandboxWorker } from "@mica-js/sandbox";
6
7
  //#region src/errors.ts
@@ -557,6 +558,45 @@ function resolveHostUri(baseUri, reference) {
557
558
  return compose(base.scheme, base.authority, path, query, target.fragment);
558
559
  }
559
560
  //#endregion
561
+ //#region src/guest/widget/props.ts
562
+ function isPlainObject(value) {
563
+ if (typeof value !== "object" || value === null) return false;
564
+ const prototype = Object.getPrototypeOf(value);
565
+ return prototype === Object.prototype || prototype === null;
566
+ }
567
+ /**
568
+ * Deep-copies plain data and freezes every container on the way back up. Typed arrays and other
569
+ * objects are returned untouched: they are not part of the JSON-shaped property format, and
570
+ * freezing a typed array with elements throws.
571
+ */
572
+ function cloneFrozen(value) {
573
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => cloneFrozen(item)));
574
+ if (isPlainObject(value)) {
575
+ const entries = [];
576
+ for (const key of Object.keys(value)) entries.push([key, cloneFrozen(value[key])]);
577
+ return Object.freeze(Object.fromEntries(entries));
578
+ }
579
+ return value;
580
+ }
581
+ /**
582
+ * Merges `definition.properties[*].default` under the props a document supplied.
583
+ *
584
+ * A key present in `props` wins, even when its value is `undefined`; a key is only filled from the
585
+ * definition when the descriptor declares `default` itself, so `default: null` and "no default"
586
+ * stay distinguishable. Defaults are cloned and deeply frozen per instance, so a widget cannot
587
+ * mutate the definition or leak changes into another instance.
588
+ */
589
+ function mergeProperties(properties, props) {
590
+ const merged = /* @__PURE__ */ new Map();
591
+ for (const key of Object.keys(properties ?? {})) {
592
+ const descriptor = properties?.[key];
593
+ if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, "default")) continue;
594
+ merged.set(key, cloneFrozen(descriptor.default));
595
+ }
596
+ for (const key of Object.keys(props ?? {})) merged.set(key, props?.[key]);
597
+ return Object.freeze(Object.fromEntries(merged));
598
+ }
599
+ //#endregion
560
600
  //#region src/guest/widget/protocol.ts
561
601
  /**
562
602
  * Guest event names. The sandbox reserves the `mica:` namespace for its own traffic: guest events
@@ -574,6 +614,8 @@ var widgetMountMethod = "mount";
574
614
  var widgetUnmountMethod = "unmount";
575
615
  var widgetResizeMethod = "resize";
576
616
  var widgetSetPropertiesMethod = "set-properties";
617
+ /** Replaces the prefetched bytes of one mounted instance without remounting it. */
618
+ var widgetSetAssetsMethod = "set-assets";
577
619
  /**
578
620
  * Replaces the device endpoints one instance writes to and reads from (RFC 0018).
579
621
  *
@@ -584,10 +626,17 @@ var widgetSetBindingsMethod = "set-bindings";
584
626
  var widgetDeliverMethod = "deliver";
585
627
  var widgetPointerMethod = "pointer";
586
628
  /**
587
- * Releases every instance without terminating the guest. Widget modules stay evaluated, so the next
588
- * `load` reuses their factories and only fresh instances are created.
629
+ * Configures explicit stepping and connects the direct simulation-runtime port before mounting.
630
+ * Without explicit stepping the standalone guest retains automatic repaint scheduling.
631
+ */
632
+ var widgetConfigureMethod = "configure";
633
+ /**
634
+ * Advances the guest to a caller-supplied time.
635
+ *
636
+ * The editor owns the clock: it delivers the same step to widgets and devices, so the guest must
637
+ * not schedule time-bound work on its own.
589
638
  */
590
- var widgetResetRuntimeMethod = "reset-runtime";
639
+ var widgetStepMethod = "step";
591
640
  /**
592
641
  * Wire names shared by the worker script and the host adapter. Both sides must agree on the exact
593
642
  * strings, so they are defined once and registered with `register` / `getProxy`.
@@ -596,7 +645,8 @@ var widgetGuestService = defineRpcService("guest");
596
645
  var widgetGuestControlService = defineRpcService("guest-control");
597
646
  var widgetHostControlService = defineRpcService("host-control");
598
647
  var widgetHostCapabilitiesService = defineRpcService("host-capabilities");
599
- defineRpcService("guest");
648
+ /** Wire name of {@link IWidgetSimulationRuntimeChannel}. */
649
+ var widgetSimulationRuntimeService = defineRpcService("simulation-runtime");
600
650
  //#endregion
601
651
  //#region src/guest/audio/protocol.ts
602
652
  /**
@@ -617,7 +667,7 @@ defineRpcService("audio-worklet");
617
667
  var widgetAudioControlService = defineRpcService("audio-control");
618
668
  var widgetAudioGuestService = defineRpcService("audio-guest");
619
669
  //#endregion
620
- //#region \0mica-widget-audio-worklet-code:/home/runner/work/mica-js/mica-js/packages/widget/src/guest/audio/entry.ts
670
+ //#region \0mica-widget-audio-worklet-code:D:/mica-js.worktrees/add-editor-package/packages/widget/src/guest/audio/entry.ts
621
671
  var entry_default$1 = "(function(){function e(e){let t=!1;return{dispose(){t||(t=!0,e())}}}var t=class{#e=/* @__PURE__ */ new Set;#t=!1;event=(t,n,r)=>{if(this.#t)return e(()=>{});let i={listener:t,thisArgs:n};this.#e.add(i);let a=e(()=>{this.#e.delete(i)});return r?.push(a),a};get hasListeners(){return this.#e.size>0}fire(e){if(!this.#t)for(let t of[...this.#e])t.listener.call(t.thisArgs,e)}dispose(){this.#t||(this.#t=!0,this.#e.clear())}};function n(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.kind===`close`)return!0;if(!Number.isSafeInteger(t.id)||t.id<=0)return!1;switch(t.kind){case`call`:case`listen`:return typeof t.service==`string`&&t.service.length>0&&typeof t.member==`string`&&t.member.length>0&&Array.isArray(t.args)&&(t.kind!==`listen`||t.args.length===0);case`unlisten`:return!0;case`result`:return Object.hasOwn(t,`value`);case`error`:case`subscription-error`:return typeof t.name==`string`&&typeof t.message==`string`;case`event`:return Array.isArray(t.args);default:return!1}}function r(e,t){return Object.assign(Error(t),{name:e})}function i(e,t){if([`constructor`,`__proto__`,`prototype`,`then`].includes(t))throw r(`MethodNotFound`,`Method is not exposed: ${t}`);for(let n=e;n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(e){if(typeof e.value==`function`)return e.value;break}}throw r(`MethodNotFound`,`Method is not callable: ${t}`)}function a(a,l={}){let u=l,d=c(u.timeoutMs??0),f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=new t,_=new t,v=0,y=0,b=!1;function x(e){let t=o(e);try{u.onError?.(t)}catch{}g.fire(t)}function S(){if(b)throw r(`RpcDisconnectedError`,`RPC endpoint is closed`)}function C(){if(v===2**53-1)throw RangeError(`RPC request IDs exhausted`);return++v}function w(e,t){S(),a.postMessage(e,t?[...t]:void 0)}function T(e){let t=p.get(e);return p.delete(e),t?.timer!==void 0&&clearTimeout(t.timer),t}function E(e,t,n){return new Promise((i,a)=>{let s=t>0?setTimeout(()=>{T(e.id)?.reject(r(`RpcTimeoutError`,`RPC ${e.service}.${e.member} timed out`))},t):void 0;p.set(e.id,{resolve:i,reject:a,timer:s});try{w(e,n)}catch(t){T(e.id)?.reject(o(t))}})}function D(e){let t=h.get(e);h.delete(e);try{t?.stop?.()}catch(e){x(e)}}function O(e,t,n){if(b)return;let r=o(n);try{w({kind:e,id:t,name:r.name,message:r.message})}catch(e){x(e),A()}}function k(){if(!b){b=!0,a.removeEventListener(`message`,M),a.removeEventListener(`close`,k),a.removeEventListener(`messageerror`,A);for(let e of p.keys())T(e)?.reject(r(`RpcDisconnectedError`,`RPC endpoint is closed`));m.clear();for(let e of h.keys())D(e);f.clear(),_.fire(void 0),_.dispose(),g.dispose()}}function A(){if(!b){try{w({kind:`close`})}catch(e){x(e)}k()}}async function j(e){try{let t=f.get(e.service);if(!t)throw r(`ServiceNotFound`,`Unknown service: ${e.service}`);let n=t.implementation,a=i(n,e.member);if(e.kind===`listen`){if(!/^onDid[A-Z]/.test(e.member))throw r(`InvalidSubscription`,`Event members must start with onDid`);let i={registration:t,stop:void 0};h.set(e.id,i);let o=a.call(n,(...n)=>{if(!(b||h.get(e.id)!==i))try{w({kind:`event`,id:e.id,args:n},t.options.transfer?.(e.member,n))}catch(t){D(e.id),O(`subscription-error`,e.id,t)}});if(typeof o!=`function`)throw r(`InvalidSubscription`,`Event registration must return an unsubscribe function`);i.stop=o,h.get(e.id)!==i&&i.stop(),b||w({kind:`result`,id:e.id,value:void 0})}else{if(/^onDid[A-Z]/.test(e.member))throw r(`InvalidCall`,`Event members require a subscription`);let i=await a.apply(n,e.args);b||w({kind:`result`,id:e.id,value:i},t.options.transfer?.(e.member,i))}}catch(t){e.kind===`listen`&&D(e.id),O(`error`,e.id,t)}}function M(e){let t=e.data;if(!n(t))x(r(`RpcProtocolError`,`Malformed RPC message`));else switch(t.kind){case`call`:case`listen`:if(t.id<=y){x(r(`RpcProtocolError`,`Request IDs must increase`));return}y=t.id,j(t);break;case`unlisten`:D(t.id);break;case`result`:T(t.id)?.resolve(t.value);break;case`error`:T(t.id)?.reject(r(t.name,t.message));break;case`subscription-error`:{let e=r(t.name,t.message),n=m.delete(t.id),i=T(t.id);i?i.reject(e):n&&x(e);break}case`event`:try{m.get(t.id)?.(...t.args)}catch(e){x(e)}break;case`close`:k()}}return a.addEventListener(`message`,M),a.addEventListener(`close`,k),a.addEventListener(`messageerror`,A),a.start?.(),{register(t,n,i={}){S();let a=s(t);if(typeof n!=`object`||!n)throw TypeError(`RPC services must be objects`);if(f.has(a))throw Error(`Service already registered: ${a}`);let o={implementation:n,options:i};return f.set(a,o),e(()=>{if(f.get(a)===o){f.delete(a);for(let[e,t]of h)t.registration===o&&(D(e),O(`subscription-error`,e,r(`ServiceUnregistered`,`Service unregistered: ${a}`)))}})},getProxy(t,n={}){let r=s(t),i=c(n.timeoutMs??d),a=/* @__PURE__ */ new Map;return new Proxy(Object.create(null),{get(t,o){if(typeof o==`string`&&o!==`then`)return a.has(o)||a.set(o,/^onDid[A-Z]/.test(o)?t=>{if(S(),typeof t!=`function`)throw TypeError(`Expected an event listener`);let n=C();m.set(n,t),E({kind:`listen`,id:n,service:r,member:o,args:[]},i).catch(e=>{if(m.delete(n),!b)try{w({kind:`unlisten`,id:n})}catch(e){x(e)}x(e)});let a=e(()=>{if(m.delete(n)&&(T(n)?.resolve(void 0),!b))try{w({kind:`unlisten`,id:n})}catch(e){x(e)}});return()=>a.dispose()}:async(...e)=>(S(),E({kind:`call`,id:C(),service:r,member:o,args:e},i,n.transfer?.(o,e)))),a.get(o)}})},onDidError:(e,t,n)=>g.event(n=>{try{e.call(t,n)}catch{}},void 0,n),onDidClose:(t,n,r)=>b?(t.call(n,void 0),e(()=>{})):_.event(e=>{try{t.call(n,e)}catch(e){x(e)}},void 0,r),dispose:A}}function o(e){return e instanceof Error?e:Error(String(e))}function s(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}function c(e){if(!Number.isSafeInteger(e)||e<0||e>2147483647)throw RangeError(`RPC timeout must be an integer between 0 and 2147483647`);return e}function l(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}let u=l(`audio-worklet`),d=l(`audio-control`);l(`audio-guest`);function f(e){let t=1,n=1,r=e*e/4;for(let e=1;e<64&&(n*=r/(e*e),t+=n,!(n<=t*1e-15));e+=1);return t}function p(e){if(e===0)return 1;let t=Math.PI*e;return Math.sin(t)/t}function m(e){return e<=-1||e>=1?0:f(8*Math.sqrt(1-e*e))/f(8)}function h(e){let t=/* @__PURE__ */ new Float32Array(8192),n=.45*Math.min(1,1/e);for(let e=0;e<256;e+=1){let r=e/256,i=0;for(let a=0;a<32;a+=1){let o=a-15-r,s=2*n*p(2*n*o)*m(o/16);t[e*32+a]=s,i+=s}if(i!==0)for(let n=0;n<32;n+=1)t[e*32+n]=(t[e*32+n]??0)/i}return t}var g=class{sourceRate;targetRate;ratio;passthrough;delayFrames;#e;constructor(e,t){this.sourceRate=e,this.targetRate=t,this.ratio=e/t,this.passthrough=e===t,this.delayFrames=this.passthrough?0:16*Math.max(1,this.ratio),this.#e=this.passthrough?void 0:h(this.ratio)}get span(){return this.passthrough?{behind:0,ahead:0}:{behind:15,ahead:16}}sample(e,t){if(this.passthrough)return e(Math.round(t));let n=Math.floor(t),r=(t-n)*256,i=Math.min(255,Math.floor(r)),a=Math.min(1,r-i),o=this.#e;if(o===void 0)return e(n);let s=i*32,c=i+1>=256,l=c?0:(i+1)*32,u=c&&a>0?1:0,d=n-15,f=0;for(let t=0;t<32;t+=1){let n=d+t,r=o[s+t]??0,i=o[l+t]??0;f+=e(n)*r*(1-a)+e(n+u)*i*a}return f}};function _(e,t){let n=t===`s16`?e/32768:e;return Number.isFinite(n)?n>1?1:n<-1?-1:n:0}var v=class{capacity;channels;data;written=0;readFloor=0;constructor(e,t){this.capacity=e,this.channels=t,this.data=new Float32Array(e*t)}write(e,t,n){for(let r=0;r<t;r+=1){let t=(this.written+r)%this.capacity*this.channels;for(let i=0;i<this.channels;i+=1)this.data[t+i]=_(e[r*this.channels+i]??0,n)}this.written+=t}at(e,t){return e<this.readFloor||e>=this.written?0:this.data[e%this.capacity*this.channels+t]??0}},y=class{streamId;channels;format;capacityFrames;startFrames;buffer;resampler;volume;state=`buffering`;underruns=0;endRequested=!1;finished=!1;closed=!1;reportedState=`buffering`;position;consumed=0;#e=0;constructor(e,t){this.streamId=e.streamId,this.channels=e.channels,this.format=e.format,this.capacityFrames=e.capacityFrames,this.startFrames=e.startFrames,this.volume=e.volume,this.buffer=new v(e.capacityFrames,e.channels),this.resampler=new g(e.sampleRate,t),this.position=this.resampler.delayFrames}get bufferedFrames(){return Math.max(0,this.buffer.written-this.consumed)}write(e,t){return this.closed||t<=0||this.bufferedFrames+t>this.capacityFrames?!1:(this.buffer.write(e,t,this.format),!0)}clear(){this.consumed=this.buffer.written,this.buffer.readFloor=this.buffer.written,this.position=this.buffer.written+this.resampler.delayFrames,this.state=`buffering`,this.#e=0}render(e,t,n,r){if(this.closed||e.length===0)return;let{resampler:i,buffer:a}=this,o=i.span,s=i.delayFrames,c=this.endRequested?a.written-1:a.written-1-o.ahead,l=this.position-s,u=Math.ceil((c+1-l)/i.ratio),d=this.endRequested||u<t,f=Math.max(1,r-1);for(let o=0;o<t;o+=1){let t=this.position-s;if(this.state!==`playing`){if(a.written-Math.floor(t)<(this.endRequested?1:Math.max(this.startFrames,1)))break;a.readFloor=Math.max(a.readFloor,Math.floor(t)),this.state=`playing`,this.#e=r}if(Math.floor(t)>c){this.endRequested?(this.finished=!0,this.state=`ended`):(this.state=`buffering`,this.underruns+=1,this.#e=0);break}let l=n*this.volume;if(d){let e=Math.ceil((c+1-t)/i.ratio);e<=r&&(l*=Math.max(0,e-1)/f)}if(this.#e>0&&(l*=1-this.#e/r,--this.#e),this.channels===1){let n=i.sample(e=>a.at(e,0),t)*l;for(let t of e)t[o]=(t[o]??0)+n}else for(let n=0;n<this.channels;n+=1){let r=e[Math.min(n,e.length-1)];r&&(r[o]=(r[o]??0)+i.sample(e=>a.at(e,n),t)*l)}this.position+=i.ratio;let u=Math.min(a.written,Math.floor(this.position-s));u>this.consumed&&(this.consumed=u)}}};let b=Math.PI*2;var x=class{id;type;#e;#t=0;#n;#r=0;#i=0;#a;#o=0;#s=0;#c=0;#l=0;#u=!1;constructor(e,t,n){this.id=e,this.type=t.type,this.#e=n,this.#n=t.frequency,this.#a=t.volume}get frequency(){return this.#n}get volume(){return this.#a}get finished(){return this.#u}set(e){if(this.#u)return;let t=Math.max(.005,e.rampMs/1e3);e.frequency!==void 0&&this.#d(e.frequency,t),e.volume!==void 0&&this.#f(e.volume,t)}stop(e){if(this.#u)return;let t=Math.round(e/1e3*this.#e);t<=0?this.#u=!0:(this.#l=t,this.#c=t)}render(e,t,n){if(!(this.#u||e.length===0))for(let r=0;r<t;r+=1){this.#p();let t=this.#n/this.#e,i=this.#m(t)*this.#a*n;this.#c>0&&(i*=this.#c/this.#l,--this.#c);for(let t of e)t[r]=(t[r]??0)+i;if(this.#t+=t,this.#t>=1&&(this.#t-=Math.floor(this.#t)),this.#c===0&&this.#l>0){this.#u=!0;return}}}#d(e,t){let n=Math.max(1,Math.round(t*this.#e));this.#r=(e-this.#n)/n,this.#i=n,this.#r===0&&(this.#n=e)}#f(e,t){let n=Math.max(1,Math.round(t*this.#e));this.#o=(e-this.#a)/n,this.#s=n,this.#o===0&&(this.#a=e)}#p(){this.#i>0&&(this.#n+=this.#r,--this.#i),this.#s>0&&(this.#a+=this.#o,--this.#s)}#m(e){let t=this.#t;switch(this.type){case`sine`:return Math.sin(b*t);case`square`:return(t<.5?1:-1)+C(t,e)-C(S(t+.5),e);case`sawtooth`:return 2*t-1-C(t,e);case`triangle`:return 1-4*Math.abs(t-.5)}}};function S(e){return e>=1?e-1:e}function C(e,t){if(t<=0||t>=1)return 0;if(e<t){let n=e/t;return n+n-n*n-1}if(e>1-t){let n=(e-1)/t;return n*n+n+n+1}return 0}let w=[`sine`,`square`,`triangle`,`sawtooth`];var T=class{#e;#t;#n=/* @__PURE__ */ new Map;#r=/* @__PURE__ */ new Map;#i=/* @__PURE__ */ new Set;#a=/* @__PURE__ */ new Set;#o;#s=!1;#c=!1;#l=0;#u=!1;constructor(e){this.#e=e.sampleRate,this.#t=Math.max(1,Math.round(.02*this.#e))}attachHostPort(e){if(this.#u||this.#o!==void 0)return;let t=a(e);this.#o=t,t.register(d,this.#d())}attachGuestPort(e,t){if(this.#u)return;this.detachGuestPort(e);let n=a(t),r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,o=n.register(u,this.#f(e,{progress:r,ended:i}));this.#n.set(e,{id:e,port:t,endpoint:n,progress:r,ended:i,registration:o})}detachGuestPort(e){for(let[t,n]of[...this.#r])n.runtimeId===e&&this.#_(t,`disposed`);let t=this.#n.get(e);t&&(this.#n.delete(e),t.registration.dispose(),t.endpoint.dispose(),D(t.port))}process(e){let t=e[0];if(!t||t.length===0||this.#u)return!0;for(let e of t)e.fill(0);if(this.#c||this.#r.size===0)return!0;let n=t[0]?.length??0;if(n===0)return!0;let r=Math.max(1,Math.round(this.#e*.002));for(let e of[...this.#r.values()]){let i=this.#s?0:e.volume;for(let[r,a]of[...e.tones])a.render(t,n,i),a.finished&&(e.tones.delete(r),this.#b(e,{target:`tone`,id:r,reason:`stopped`}));for(let[a,o]of[...e.streams])o.render(t,n,i,r),o.finished?this.#v(e,a,`finished`):o.state!==o.reportedState&&(o.reportedState=o.state,this.#y(e,o))}if(this.#l+=n,this.#l>=this.#t){this.#l=0;for(let e of this.#r.values())for(let t of e.streams.values())this.#y(e,t)}return!0}dispose(){if(!this.#u){for(let e of[...this.#r.keys()])this.#_(e,`disposed`);for(let e of[...this.#n.keys()])this.detachGuestPort(e);this.#u=!0,this.#a.clear(),this.#o?.dispose(),this.#o=void 0}}#d(){return{openSession:e=>this.#p(e),closeSession:e=>this.#_(e,`stopped`),setSessionVolume:(e,t)=>{let n=this.#r.get(e);n&&typeof t==`number`&&Number.isFinite(t)&&(n.volume=Math.min(1,Math.max(0,t)))},setMuted:e=>{this.#s=e===!0},suspend:()=>{this.#c=!0},resume:()=>{this.#c=!1},attachGuestPort:(e,t)=>{typeof e==`string`&&e.length!==0&&E(t)&&this.attachGuestPort(e,t)},detachGuestPort:e=>{typeof e==`string`&&this.detachGuestPort(e)},onDidDiagnostic:e=>typeof e==`function`?(this.#a.add(e),()=>{this.#a.delete(e)}):()=>{}}}#f(e,t){return{createTone:(t,n)=>{this.#m(e,t,n)},setTone:(t,n,r)=>{let i=this.#g(e,t),a=i?.tones.get(n);i&&a&&(A(r)?a.set(r):this.#x(i.session,`worklet`,`A tone update was rejected`))},stopTone:(t,n,r)=>{let i=this.#g(e,t),a=i?.tones.get(n);if(!i||!a)return;let o=typeof r==`object`&&r&&Number.isFinite(r.fadeMs)?Math.min(1e4,Math.max(0,r.fadeMs)):0;a.stop(o),a.finished&&(i.tones.delete(n),this.#b(i,{target:`tone`,id:n,reason:`stopped`}))},createStream:(t,n)=>this.#h(e,t,n),writeStream:(t,n,r)=>{let i=this.#g(e,t),a=i?.streams.get(n);if(!i||!a)return!1;let o=M(r,a.channels,a.format);return o===void 0||o>a.capacityFrames?(this.#x(i.session,`worklet`,`A PCM block was rejected`),!1):a.write(r,o)?!0:(this.#x(i.session,`capacity`,`A PCM block beyond the stream capacity was dropped`),!1)},clearStream:(t,n)=>{let r=this.#g(e,t),i=r?.streams.get(n);r&&i&&(i.clear(),this.#y(r,i))},endStream:(t,n)=>{let r=this.#g(e,t),i=r?.streams.get(n);r&&i&&(i.endRequested=!0,i.consumed>=i.buffer.written&&this.#v(r,n,`finished`))},closeStream:(t,n)=>{let r=this.#g(e,t);r?.streams.has(n)&&this.#v(r,n,`stopped`)},onDidProgress:e=>typeof e==`function`?(t.progress.add(e),()=>{t.progress.delete(e)}):()=>{},onDidEnded:e=>typeof e==`function`?(t.ended.add(e),()=>{t.ended.delete(e)}):()=>{}}}#p(e){O(e)&&!this.#r.has(e.session)&&(this.#n.has(e.runtimeId)?this.#r.set(e.session,{session:e.session,runtimeId:e.runtimeId,instanceId:e.instanceId,maxVoices:Math.max(1,Math.floor(e.maxVoices)),maxStreams:Math.max(1,Math.floor(e.maxStreams)),volume:1,tones:/* @__PURE__ */ new Map,streams:/* @__PURE__ */ new Map}):this.#x(e.session,`worklet`,`A session arrived before its guest port`))}#m(e,t,n){let r=this.#g(e,t);if(r){if(!k(n))this.#x(r.session,`worklet`,`A tone command was rejected`);else if(!r.tones.has(n.voiceId))for(r.tones.set(n.voiceId,new x(n.voiceId,n,this.#e));r.tones.size>r.maxVoices;){let e=r.tones.keys().next().value;if(e===void 0||e===n.voiceId)break;r.tones.delete(e),this.#b(r,{target:`tone`,id:e,reason:`dropped`}),this.#x(r.session,`voices`,`A tone was dropped: the per-instance ceiling of ${r.maxVoices} is exhausted`)}}}#h(e,t,n){let r=this.#g(e,t);return r?j(n)?r.streams.has(n.streamId)?{accepted:!0}:r.streams.size>=r.maxStreams?(this.#x(r.session,`streams`,`A PCM stream was refused: the per-instance quota of ${r.maxStreams} is exhausted`),{accepted:!1}):(r.streams.set(n.streamId,new y(n,this.#e)),{accepted:!0}):(this.#x(r.session,`worklet`,`A stream-open command was rejected`),{accepted:!1}):{accepted:!1}}#g(e,t){if(typeof t!=`string`)return;let n=this.#r.get(t);if(!n)this.#x(t,`worklet`,`A guest call named an unknown session`);else if(n.runtimeId!==e)this.#x(t,`worklet`,`A guest call came from another runtime`);else return n}#_(e,t){let n=this.#r.get(e);if(n){for(let e of[...n.tones.keys()])n.tones.delete(e),this.#b(n,{target:`tone`,id:e,reason:t});for(let e of[...n.streams.keys()])this.#v(n,e,t);this.#r.delete(e);for(let t of[...this.#i])t.startsWith(`${e}\\u0000`)&&this.#i.delete(t)}}#v(e,t,n){let r=e.streams.get(t);r&&(r.closed=!0,r.state=n===`finished`?`ended`:`closed`,e.streams.delete(t),this.#y(e,r),this.#b(e,{target:`stream`,id:t,reason:n}))}#y(e,t){let n=this.#n.get(e.runtimeId);if(!n)return;let r={streamId:t.streamId,consumedFrames:t.consumed,underruns:t.underruns,state:t.state};for(let e of[...n.progress])try{e(r)}catch{}}#b(e,t){let n=this.#n.get(e.runtimeId);if(n)for(let e of[...n.ended])try{e(t)}catch{}}#x(e,t,n){let r=`${e}\\u0000${t}`;if(this.#i.has(r))return;this.#i.add(r);let i={session:e,code:t===`worklet`?`widget/audio-failed`:`widget/audio-limit`,category:t,message:n};for(let e of[...this.#a])try{e(i)}catch{}}};function E(e){return typeof e==`object`&&!!e&&typeof e.postMessage==`function`&&typeof e.addEventListener==`function`}function D(e){try{e.close?.()}catch{}}function O(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.session==`string`&&t.session.length>0&&typeof t.runtimeId==`string`&&t.runtimeId.length>0&&typeof t.instanceId==`string`&&typeof t.maxVoices==`number`&&Number.isFinite(t.maxVoices)&&typeof t.maxStreams==`number`&&Number.isFinite(t.maxStreams)}function k(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.frequency,r=t.volume;return typeof t.voiceId==`string`&&t.voiceId.length>0&&typeof t.type==`string`&&w.includes(t.type)&&typeof n==`number`&&Number.isFinite(n)&&n>0&&n<=24e3&&typeof r==`number`&&Number.isFinite(r)&&r>=0&&r<=1}function A(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.rampMs;if(typeof n!=`number`||!Number.isFinite(n)||n<0||n>1e4)return!1;let r=t.volume;if(r!==void 0&&(typeof r!=`number`||!Number.isFinite(r)||r<0||r>1))return!1;let i=t.frequency;return!(i!==void 0&&(typeof i!=`number`||!Number.isFinite(i)||i<=0||i>24e3))}function j(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.sampleRate,r=t.capacityFrames,i=t.startFrames,a=t.volume;return typeof t.streamId==`string`&&t.streamId.length>0&&typeof n==`number`&&Number.isInteger(n)&&n>=8e3&&n<=96e3&&(t.channels===1||t.channels===2)&&(t.format===`s16`||t.format===`f32`)&&typeof r==`number`&&Number.isInteger(r)&&r>=1&&r<=192e3&&typeof i==`number`&&Number.isInteger(i)&&i>=0&&i<=r&&typeof a==`number`&&Number.isFinite(a)}function M(e,t,n){if(e instanceof(n===`s16`?Int16Array:Float32Array)&&e.length!==0&&e.length%t===0)return e.length/t}var N=class extends AudioWorkletProcessor{#e;constructor(){super(),this.#e=new T({sampleRate}),this.#e.attachHostPort(this.port)}process(e,t){return this.#e.process(t)}};registerProcessor(`mica-widget-audio`,N)})();";
622
672
  //#endregion
623
673
  //#region src/host/audio/worklet.ts
@@ -636,8 +686,8 @@ function widgetAudioWorkletUrl() {
636
686
  /**
637
687
  * Loads the packaged processor into `context` and creates its node.
638
688
  *
639
- * Pass it as `getAudioWorklet` wherever a `WidgetHost` or `CanvasEditor` asks for one; hosts that
640
- * provide no loader of their own use the same processor internally.
689
+ * Pass it as `WidgetAudioOptions.getAudioWorklet`; runtimes that provide no loader of their
690
+ * own use the same processor internally.
641
691
  */
642
692
  async function createWidgetAudioWorklet(context) {
643
693
  if (typeof context.audioWorklet?.addModule !== "function") throw new Error("The AudioContext does not support AudioWorklet.addModule().");
@@ -761,8 +811,8 @@ var WidgetAudioEngine = class {
761
811
  this.#call((control) => control.setMuted(this.#muted));
762
812
  }
763
813
  setInstanceVolume(instanceId, volume) {
764
- if (typeof volume !== "number") throw new TypeError("WidgetHost.audio.setInstanceVolume expects a number");
765
- if (!Number.isFinite(volume) || volume < 0 || volume > 1) throw new RangeError("WidgetHost.audio.setInstanceVolume expects a value in [0, 1]");
814
+ if (typeof volume !== "number") throw new TypeError("WidgetAudioControls.setInstanceVolume expects a number");
815
+ if (!Number.isFinite(volume) || volume < 0 || volume > 1) throw new RangeError("WidgetAudioControls.setInstanceVolume expects a value in [0, 1]");
766
816
  const instance = this.#instances.get(instanceId);
767
817
  if (!instance) return;
768
818
  this.#call((control) => control.setSessionVolume(instance.session, volume));
@@ -821,7 +871,7 @@ var WidgetAudioEngine = class {
821
871
  const worklet = this.#worklet;
822
872
  this.#worklet = void 0;
823
873
  if (worklet !== void 0) {
824
- closePort(worklet.port);
874
+ closePort$1(worklet.port);
825
875
  try {
826
876
  worklet.disconnect?.();
827
877
  } catch {}
@@ -844,7 +894,7 @@ var WidgetAudioEngine = class {
844
894
  this.#listenForContextState();
845
895
  const worklet = await (this.#loadWorklet?.() ?? this.#loadDefaultWorklet());
846
896
  if (this.#disposed) {
847
- closePort(worklet.port);
897
+ closePort$1(worklet.port);
848
898
  try {
849
899
  worklet.disconnect?.();
850
900
  } catch {}
@@ -909,8 +959,8 @@ var WidgetAudioEngine = class {
909
959
  try {
910
960
  await control.attachGuestPort(this.#runtimeId, channel.port1);
911
961
  } catch (error) {
912
- closePort(channel.port1);
913
- closePort(channel.port2);
962
+ closePort$1(channel.port1);
963
+ closePort$1(channel.port2);
914
964
  this.#report("widget/audio-failed", "", `The audio worklet rejected the guest port: ${describe(error)}`);
915
965
  return;
916
966
  }
@@ -931,7 +981,7 @@ var WidgetAudioEngine = class {
931
981
  this.#notify.emitState(next);
932
982
  }
933
983
  };
934
- function closePort(port) {
984
+ function closePort$1(port) {
935
985
  try {
936
986
  port.close();
937
987
  } catch {}
@@ -956,1510 +1006,560 @@ var NO_AUDIO_CONTROLS = {
956
1006
  resume() {}
957
1007
  };
958
1008
  //#endregion
959
- //#region src/guest/widget/props.ts
960
- function isPlainObject(value) {
961
- if (typeof value !== "object" || value === null) return false;
962
- const prototype = Object.getPrototypeOf(value);
963
- return prototype === Object.prototype || prototype === null;
964
- }
1009
+ //#region src/runtime/errors.ts
965
1010
  /**
966
- * Deep-copies plain data and freezes every container on the way back up. Typed arrays and other
967
- * objects are returned untouched: they are not part of the JSON-shaped property format, and
968
- * freezing a typed array with elements throws.
1011
+ * Typed rejection of one runtime call.
1012
+ *
1013
+ * Widget boundary failures (render, input, publish) become diagnostics instead; errors with this
1014
+ * type mean the caller asked for something the runtime cannot do.
969
1015
  */
970
- function cloneFrozen(value) {
971
- if (Array.isArray(value)) return Object.freeze(value.map((item) => cloneFrozen(item)));
972
- if (isPlainObject(value)) {
973
- const entries = [];
974
- for (const key of Object.keys(value)) entries.push([key, cloneFrozen(value[key])]);
975
- return Object.freeze(Object.fromEntries(entries));
1016
+ var WidgetRuntimeError = class extends Error {
1017
+ code;
1018
+ constructor(code, message, options) {
1019
+ super(message, options);
1020
+ this.name = "WidgetRuntimeError";
1021
+ this.code = code;
976
1022
  }
977
- return value;
978
- }
979
- function isAssetMode(value) {
980
- return value === "file" || value === "inline" || value === "store";
981
- }
1023
+ };
1024
+ //#endregion
1025
+ //#region src/runtime/runtime.ts
982
1026
  /**
983
- * Merges `definition.properties[*].default` under the props a document supplied.
1027
+ * Creates the widget runtime over an existing sandbox.
984
1028
  *
985
- * A key present in `props` wins, even when its value is `undefined`; a key is only filled from the
986
- * definition when the descriptor declares `default` itself, so `default: null` and "no default"
987
- * stay distinguishable. Defaults are cloned and deeply frozen per instance, so a widget cannot
988
- * mutate the definition or leak changes into another instance.
1029
+ * The runtime owns the sandbox: `dispose()` terminates it, so the caller must not keep using it
1030
+ * afterwards. The runtime never reads documents or files, resolves widget modules, drives a clock
1031
+ * or talks to a device runtime; those stay with the editor that calls it.
989
1032
  */
990
- function mergeProperties(properties, props) {
991
- const merged = /* @__PURE__ */ new Map();
992
- for (const key of Object.keys(properties ?? {})) {
993
- const descriptor = properties?.[key];
994
- if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, "default")) continue;
995
- merged.set(key, cloneFrozen(descriptor.default));
996
- }
997
- for (const key of Object.keys(props ?? {})) merged.set(key, props?.[key]);
998
- return Object.freeze(Object.fromEntries(merged));
1033
+ function createWidgetRuntime(sandbox, options = {}) {
1034
+ return new WidgetRuntimeImpl(sandbox, options);
999
1035
  }
1000
- /**
1001
- * Collects image / binary property values (`{ src, mode }`) from nested objects and arrays.
1002
- * Results are keyed by `src`, so one resource referenced twice is only read once.
1003
- */
1004
- function collectAssetRefs(value, found = /* @__PURE__ */ new Map(), seen = /* @__PURE__ */ new Set()) {
1005
- if (typeof value !== "object" || value === null) return found;
1006
- if (seen.has(value)) return found;
1007
- seen.add(value);
1008
- if (Array.isArray(value)) {
1009
- for (const item of value) collectAssetRefs(item, found, seen);
1010
- return found;
1011
- }
1012
- if (!isPlainObject(value)) return found;
1013
- const candidate = value;
1014
- if (typeof candidate.src === "string" && isAssetMode(candidate.mode)) {
1015
- if (!found.has(candidate.src)) found.set(candidate.src, {
1016
- src: candidate.src,
1017
- mode: candidate.mode
1036
+ var WidgetRuntimeImpl = class {
1037
+ #sandbox;
1038
+ #engine;
1039
+ #instances = /* @__PURE__ */ new Map();
1040
+ #pending = [];
1041
+ #published = new Emitter();
1042
+ #rendered = new Emitter();
1043
+ #diagnostics = new Emitter();
1044
+ #unsubscribers = [];
1045
+ onDidPublish = this.#published.event;
1046
+ onDidRender = this.#rendered.event;
1047
+ onDidDiagnostic = this.#diagnostics.event;
1048
+ audio;
1049
+ /** Serializes mount, update, unmount, setBindings and step; a failure never poisons the chain. */
1050
+ #tail = Promise.resolve();
1051
+ #configured;
1052
+ #simTime = timePs(0);
1053
+ #generation = 0;
1054
+ #disposed = false;
1055
+ #disposal;
1056
+ constructor(sandbox, options) {
1057
+ this.#sandbox = sandbox;
1058
+ const audioOptions = options.audio;
1059
+ if (audioOptions === void 0) this.audio = NO_AUDIO_CONTROLS;
1060
+ else {
1061
+ const context = audioOptions.context;
1062
+ const getAudioWorklet = audioOptions.getAudioWorklet;
1063
+ const engine = new WidgetAudioEngine({
1064
+ context,
1065
+ ...audioOptions.destination === void 0 ? {} : { destination: audioOptions.destination },
1066
+ ...getAudioWorklet === void 0 ? {} : { loadWorklet: () => getAudioWorklet(context) },
1067
+ ...audioOptions.limits === void 0 ? {} : { limits: audioOptions.limits },
1068
+ report: (code, instanceId, message) => this.#report(code, "audio", message, instanceId === "" ? {} : { instanceId }),
1069
+ notify: {
1070
+ emitPort: (port) => {
1071
+ const lane = sandbox.audio;
1072
+ if (lane === void 0) {
1073
+ closePort(port);
1074
+ return;
1075
+ }
1076
+ try {
1077
+ lane.attachPort(port);
1078
+ } catch {
1079
+ closePort(port);
1080
+ }
1081
+ },
1082
+ emitState: (state) => {
1083
+ try {
1084
+ sandbox.audio?.setState(state);
1085
+ } catch {}
1086
+ }
1087
+ }
1088
+ });
1089
+ this.#engine = engine;
1090
+ this.audio = engine;
1091
+ }
1092
+ this.#unsubscribers.push(sandbox.on(widgetFrameEvent, (payload) => this.#onFrame(payload)), sandbox.on(widgetPublishEvent, (payload) => this.#onPublish(payload)), sandbox.on(widgetErrorEvent, (payload) => this.#onError(payload)), sandbox.on(widgetAssetFailedEvent, (payload) => this.#onAssetFailed(payload)));
1093
+ }
1094
+ mount(instance) {
1095
+ return this.#run(async () => {
1096
+ const prepared = normalizePrepared(instance);
1097
+ this.#assertActive();
1098
+ if (this.#instances.has(prepared.instanceId)) throw new WidgetRuntimeError("widget/instance-exists", `Widget instance "${prepared.instanceId}" is already mounted.`);
1099
+ const ref = splitRef(prepared.widget);
1100
+ if (ref === void 0) throw new WidgetRuntimeError("widget/invalid-instance", `Widget reference "${prepared.widget}" must use the "<package>:<widget>" form.`);
1101
+ await this.#configure();
1102
+ this.#assertActive();
1103
+ const record = {
1104
+ instanceId: prepared.instanceId,
1105
+ widget: prepared.widget,
1106
+ module: prepared.module,
1107
+ generation: ++this.#generation,
1108
+ width: prepared.width,
1109
+ height: prepared.height,
1110
+ dpr: prepared.dpr,
1111
+ bitmap: void 0,
1112
+ sequence: 0,
1113
+ mounted: false,
1114
+ audioSession: void 0
1115
+ };
1116
+ this.#instances.set(record.instanceId, record);
1117
+ try {
1118
+ await this.#sandbox.call(widgetLoadMethod, { packages: [{
1119
+ id: ref.packageId,
1120
+ modules: { [ref.widgetId]: {
1121
+ definition: prepared.module.definition,
1122
+ code: prepared.module.code
1123
+ } }
1124
+ }] });
1125
+ this.#assertOwnership(record);
1126
+ const audio = await this.#openAudio(record);
1127
+ this.#assertOwnership(record);
1128
+ const properties = mergeProperties(prepared.module.definition.properties, prepared.properties);
1129
+ await this.#sandbox.call(widgetMountMethod, {
1130
+ instanceId: record.instanceId,
1131
+ widget: record.widget,
1132
+ width: record.width,
1133
+ height: record.height,
1134
+ dpr: record.dpr,
1135
+ props: properties,
1136
+ ...prepared.assets === void 0 ? {} : { assets: prepared.assets },
1137
+ generation: record.generation,
1138
+ audio
1139
+ });
1140
+ this.#assertOwnership(record);
1141
+ record.mounted = true;
1142
+ } catch (error) {
1143
+ this.#forget(record);
1144
+ await this.#releaseGuest(record.instanceId);
1145
+ if (record.audioSession !== void 0) this.#engine?.closeSession(record.instanceId, record.audioSession);
1146
+ if (this.#disposed) throw new WidgetRuntimeError("widget/disposed", `Mount of widget instance "${prepared.instanceId}" was cancelled before it finished.`);
1147
+ if (this.#sandbox.state === "terminated") {
1148
+ this.#report("widget/runtime-failed", "runtime", "The widget sandbox terminated during mount.");
1149
+ throw new WidgetRuntimeError("widget/sandbox-failed", "The widget sandbox terminated during mount.", { cause: error });
1150
+ }
1151
+ this.#report("widget/mount-failed", "mount", `Widget "${prepared.widget}" failed to mount: ${describeError(error)}`, {
1152
+ instanceId: prepared.instanceId,
1153
+ widget: prepared.widget
1154
+ });
1155
+ throw error instanceof WidgetRuntimeError ? error : new WidgetRuntimeError("widget/sandbox-failed", `Widget "${prepared.widget}" failed to mount: ${describeError(error)}`, { cause: error });
1156
+ }
1018
1157
  });
1019
1158
  }
1020
- for (const key of Object.keys(value)) collectAssetRefs(value[key], found, seen);
1021
- return found;
1022
- }
1023
- //#endregion
1024
- //#region src/host/catalog.ts
1025
- /** `symbol` + `port` pair as one map key; neither part can contain a NUL. */
1026
- function portKey(symbol, port) {
1027
- return `${symbol}\u0000${port}`;
1028
- }
1029
- /**
1030
- * Catalog the host assembles itself (RFC 0018).
1031
- *
1032
- * Widget ports and properties come from the definitions `widgetProvider.resolve` returned, the
1033
- * device side from `deviceHost.getTopics()` and the schematic the runtime loaded. A host with an
1034
- * explicit `WidgetHostOptions.catalog` skips this one entirely.
1035
- */
1036
- var HostBindingCatalog = class {
1037
- #definitions = /* @__PURE__ */ new Map();
1038
- #schematics = /* @__PURE__ */ new Set();
1039
- #symbols = /* @__PURE__ */ new Set();
1040
- #ports = /* @__PURE__ */ new Map();
1041
- /** Whether the provider answered for `ref`; until it does, that widget stays unchecked. */
1042
- knows(ref) {
1043
- return this.#definitions.has(ref);
1044
- }
1045
- /** Records one definition, so the synchronous validation no longer needs the provider. */
1046
- recordDefinition(ref, definition) {
1047
- this.#definitions.set(ref, {
1048
- ports: definition.ports,
1049
- propertyKeys: Object.keys(definition.properties)
1159
+ update(instanceId, update) {
1160
+ return this.#run(async () => {
1161
+ requireId(instanceId);
1162
+ this.#assertActive();
1163
+ const record = this.#requireMounted(instanceId);
1164
+ if (update.width !== void 0 || update.height !== void 0 || update.dpr !== void 0) {
1165
+ const width = update.width === void 0 ? record.width : requireSize(update.width, "width");
1166
+ const height = update.height === void 0 ? record.height : requireSize(update.height, "height");
1167
+ const dpr = update.dpr === void 0 ? record.dpr : requireDpr(update.dpr);
1168
+ await this.#call(widgetResizeMethod, [
1169
+ instanceId,
1170
+ width,
1171
+ height,
1172
+ dpr
1173
+ ], record, "widget/update-failed", "update");
1174
+ record.width = width;
1175
+ record.height = height;
1176
+ record.dpr = dpr;
1177
+ }
1178
+ if (update.properties !== void 0) {
1179
+ const properties = mergeProperties(record.module.definition.properties, update.properties);
1180
+ await this.#call(widgetSetPropertiesMethod, [instanceId, properties], record, "widget/update-failed", "update");
1181
+ }
1182
+ if (update.assets !== void 0) await this.#call(widgetSetAssetsMethod, [instanceId, update.assets], record, "widget/update-failed", "update");
1050
1183
  });
1051
1184
  }
1052
- /**
1053
- * Replaces the device side after a schematic load.
1054
- *
1055
- * `schematics` holds every path that identifies the loaded schematic (the reference the document
1056
- * wrote and the absolute URI it resolved to); `topics` are the endpoints the running devices
1057
- * report. A symbol the runtime does not report an endpoint for still counts as present when the
1058
- * schematic lists it.
1059
- */
1060
- setDeviceFacts(options) {
1061
- this.#schematics = new Set(options.schematics.filter((path) => path !== void 0 && path !== ""));
1062
- this.#symbols = new Set(options.schematic?.sheet.symbols.map((symbol) => symbol.id) ?? []);
1063
- this.#ports = /* @__PURE__ */ new Map();
1064
- for (const topic of options.topics) {
1065
- this.#symbols.add(topic.symbol);
1066
- const type = parsePayloadType(topic.type);
1067
- if (type === void 0) continue;
1068
- this.#ports.set(portKey(topic.symbol, topic.port), {
1069
- direction: topic.direction,
1070
- type
1185
+ unmount(instanceId) {
1186
+ return this.#run(async () => {
1187
+ requireId(instanceId);
1188
+ if (this.#disposed) return;
1189
+ const record = this.#instances.get(instanceId);
1190
+ if (record === void 0) return;
1191
+ this.#instances.delete(instanceId);
1192
+ this.#closeRecord(record);
1193
+ for (let index = this.#pending.length - 1; index >= 0; index -= 1) if (this.#pending[index]?.instanceId === instanceId) this.#pending.splice(index, 1);
1194
+ if (record.audioSession !== void 0) this.#engine?.closeSession(instanceId, record.audioSession);
1195
+ try {
1196
+ await this.#sandbox.call(widgetUnmountMethod, instanceId);
1197
+ } catch (error) {
1198
+ this.#report("widget/unmount-failed", "unmount", `Widget instance "${instanceId}" could not be released: ${describeError(error)}`, {
1199
+ instanceId,
1200
+ widget: record.widget
1201
+ });
1202
+ }
1203
+ });
1204
+ }
1205
+ deliver(message) {
1206
+ try {
1207
+ if (this.#disposed) throw new WidgetRuntimeError("widget/disposed", "The widget runtime is disposed.");
1208
+ const port = this.#requireMounted(message.instanceId).module.definition.ports[message.port];
1209
+ if (port === void 0) throw new WidgetRuntimeError("widget/unknown-port", `Widget instance "${message.instanceId}" has no port ${JSON.stringify(message.port)}.`);
1210
+ if (port.direction !== "input") throw new WidgetRuntimeError("widget/invalid-direction", `Port "${message.port}" of "${message.instanceId}" is an output.`);
1211
+ if (!payloadMatches(port.type, message.payload)) throw new WidgetRuntimeError("widget/invalid-payload", `Payload for "${message.instanceId}.${message.port}" does not match ${port.type}.`);
1212
+ const simTime = requireTime(message.simTime, "simTime");
1213
+ this.#pending.push({
1214
+ instanceId: message.instanceId,
1215
+ method: widgetDeliverMethod,
1216
+ args: [
1217
+ message.instanceId,
1218
+ message.port,
1219
+ message.payload,
1220
+ simTime
1221
+ ]
1222
+ });
1223
+ return Promise.resolve();
1224
+ } catch (error) {
1225
+ return Promise.reject(error);
1226
+ }
1227
+ }
1228
+ dispatch(instanceId, event) {
1229
+ try {
1230
+ if (this.#disposed) throw new WidgetRuntimeError("widget/disposed", "The widget runtime is disposed.");
1231
+ this.#requireMounted(instanceId);
1232
+ if (typeof event !== "object" || event === null || typeof event.type !== "string" || event.type === "") throw new WidgetRuntimeError("widget/invalid-payload", "A widget input event needs a nonempty type.");
1233
+ this.#pending.push({
1234
+ instanceId,
1235
+ method: widgetPointerMethod,
1236
+ args: [instanceId, event]
1071
1237
  });
1238
+ return Promise.resolve();
1239
+ } catch (error) {
1240
+ return Promise.reject(error);
1072
1241
  }
1073
1242
  }
1074
- widgetDefinition(ref) {
1075
- return this.#definitions.get(ref);
1243
+ step(context) {
1244
+ return this.#run(async () => {
1245
+ this.#assertActive();
1246
+ const simTime = requireTime(context.simTime, "simTime");
1247
+ const dt = requireTime(context.dt, "dt");
1248
+ if (context.mode !== "edit" && context.mode !== "simulation") throw new WidgetRuntimeError("widget/invalid-step", `Unknown widget step mode: ${String(context.mode)}.`);
1249
+ await this.#configure();
1250
+ this.#assertActive();
1251
+ for (const call of this.#pending.splice(0)) {
1252
+ const record = this.#instances.get(call.instanceId);
1253
+ if (record === void 0 || !record.mounted) {
1254
+ this.#report("widget/deliver-failed", "deliver", `Queued ${call.method} for "${call.instanceId}" was dropped: the instance is not mounted.`, { instanceId: call.instanceId });
1255
+ continue;
1256
+ }
1257
+ try {
1258
+ await this.#sandbox.call(call.method, ...call.args);
1259
+ } catch (error) {
1260
+ if (this.#disposed) throw new WidgetRuntimeError("widget/disposed", "Widget step was cancelled by runtime disposal.");
1261
+ this.#report("widget/deliver-failed", "deliver", `Widget call "${call.method}" failed for "${call.instanceId}": ${describeError(error)}`, {
1262
+ instanceId: call.instanceId,
1263
+ widget: record.widget
1264
+ });
1265
+ }
1266
+ }
1267
+ this.#simTime = simTime;
1268
+ try {
1269
+ await this.#sandbox.call(widgetStepMethod, {
1270
+ simTime,
1271
+ dt,
1272
+ mode: context.mode
1273
+ });
1274
+ } catch (error) {
1275
+ if (this.#disposed) throw new WidgetRuntimeError("widget/disposed", "Widget step was cancelled by runtime disposal.");
1276
+ this.#report("widget/step-failed", "step", `Widget step failed: ${describeError(error)}`);
1277
+ throw new WidgetRuntimeError("widget/sandbox-failed", `Widget step failed: ${describeError(error)}`, { cause: error });
1278
+ }
1279
+ });
1280
+ }
1281
+ setBindings(instanceId, bindings) {
1282
+ return this.#run(async () => {
1283
+ const normalized = normalizeBindings(bindings);
1284
+ requireId(instanceId);
1285
+ this.#assertActive();
1286
+ const record = this.#requireMounted(instanceId);
1287
+ await this.#call(widgetSetBindingsMethod, [instanceId, normalized], record, "widget/update-failed", "update");
1288
+ });
1076
1289
  }
1077
- hasSchematic(path) {
1078
- return this.#schematics.has(path);
1290
+ dispose() {
1291
+ if (this.#disposal !== void 0) return this.#disposal;
1292
+ this.#disposed = true;
1293
+ this.#pending.length = 0;
1294
+ const terminating = terminateSandbox(this.#sandbox);
1295
+ this.#disposal = this.#run(async () => {
1296
+ const records = [...this.#instances.values()];
1297
+ this.#instances.clear();
1298
+ for (const record of records) this.#closeRecord(record);
1299
+ for (const unsubscribe of this.#unsubscribers.splice(0)) try {
1300
+ unsubscribe();
1301
+ } catch {}
1302
+ this.#engine?.dispose();
1303
+ await terminating;
1304
+ this.#published.dispose();
1305
+ this.#rendered.dispose();
1306
+ this.#diagnostics.dispose();
1307
+ });
1308
+ return this.#disposal;
1079
1309
  }
1080
- hasSymbol(symbolId) {
1081
- return this.#symbols.has(symbolId);
1310
+ /** Runs one operation after the previous one, whether it resolved or rejected. */
1311
+ #run(operation) {
1312
+ const result = this.#tail.then(operation, operation);
1313
+ this.#tail = result.then(() => void 0, () => void 0);
1314
+ return result;
1082
1315
  }
1083
- symbolPort(symbolId, port) {
1084
- return this.#ports.get(portKey(symbolId, port));
1316
+ #assertActive() {
1317
+ if (this.#disposed) throw new WidgetRuntimeError("widget/disposed", "The widget runtime is disposed.");
1318
+ if (this.#sandbox.state === "terminated") throw new WidgetRuntimeError("widget/sandbox-failed", "The widget sandbox is terminated.");
1085
1319
  }
1086
- };
1087
- //#endregion
1088
- //#region src/host/widgets.ts
1089
- /**
1090
- * Instance table owned by the host.
1091
- *
1092
- * The table is the single source of the two projections RFC 0018 defines: `listInstances()` reads a
1093
- * bulk view without bitmaps, and the four `onDid*` events report one change each with the complete
1094
- * state. The legacy `WidgetLayers` view stays for the canvas editor: records mutate in place, so a
1095
- * caller holding a layer from `get()` sees later frames without re-reading the table.
1096
- */
1097
- var WidgetStore = class {
1098
- #records = /* @__PURE__ */ new Map();
1099
- #changes = /* @__PURE__ */ new Set();
1100
- #added = new Emitter();
1101
- #updated = new Emitter();
1102
- #removed = new Emitter();
1103
- #reordered = new Emitter();
1104
- /**
1105
- * The four RFC 0018 events. A listener that throws is logged instead of breaking the document
1106
- * flow, and the subscription itself is an ordinary {@link Disposable}.
1107
- */
1108
- onDidAddWidget = (listener, thisArgs, disposables) => this.#added.event((widget) => invoke(listener, widget, "widget add listener", thisArgs), void 0, disposables);
1109
- onDidChangeWidget = (listener, thisArgs, disposables) => this.#updated.event((widget) => invoke(listener, widget, "widget change listener", thisArgs), void 0, disposables);
1110
- onDidRemoveWidget = (listener, thisArgs, disposables) => this.#removed.event((instanceId) => invoke(listener, instanceId, "widget remove listener", thisArgs), void 0, disposables);
1111
- onDidReorderWidgets = (listener, thisArgs, disposables) => this.#reordered.event((order) => invoke(listener, order, "widget reorder listener", thisArgs), void 0, disposables);
1112
- list() {
1113
- return [...this.#records.values()];
1114
- }
1115
- get(instanceId) {
1116
- return this.#records.get(instanceId);
1117
- }
1118
- listInstances() {
1119
- return [...this.#records.values()].map(toInstance);
1120
- }
1121
- subscribe(listener) {
1122
- this.#changes.add(listener);
1123
- return () => {
1124
- this.#changes.delete(listener);
1125
- };
1320
+ #assertOwnership(record) {
1321
+ if (this.#disposed) throw new WidgetRuntimeError("widget/disposed", `Mount of widget instance "${record.instanceId}" was cancelled before it finished.`);
1322
+ if (this.#instances.get(record.instanceId) !== record) throw new WidgetRuntimeError("widget/unknown-instance", `Widget instance "${record.instanceId}" was replaced during mount.`);
1126
1323
  }
1127
- add(init) {
1128
- this.remove(init.instanceId);
1129
- const record = {
1130
- instanceId: init.instanceId,
1131
- widget: init.widget,
1132
- x: init.x,
1133
- y: init.y,
1134
- width: init.width,
1135
- height: init.height,
1136
- rotation: init.rotation,
1137
- dpr: init.dpr,
1138
- properties: init.properties,
1139
- bindings: init.bindings,
1140
- bitmap: void 0,
1141
- sequence: 0
1142
- };
1143
- this.#records.set(init.instanceId, record);
1144
- this.#emitChange({
1145
- type: "added",
1146
- instanceId: init.instanceId
1147
- });
1148
- this.#emitAdd(record);
1324
+ #requireMounted(instanceId) {
1325
+ const record = this.#instances.get(instanceId);
1326
+ if (record === void 0 || !record.mounted) throw new WidgetRuntimeError("widget/unknown-instance", `Widget instance "${instanceId}" is not mounted.`);
1149
1327
  return record;
1150
1328
  }
1151
- /**
1152
- * Applies the document-derived fields of one instance and reports the ones that changed.
1153
- *
1154
- * @returns whether anything changed.
1155
- */
1156
- update(instanceId, patch) {
1157
- const record = this.#records.get(instanceId);
1158
- if (!record) return false;
1159
- let changed = false;
1160
- if (patch.x !== void 0 && patch.x !== record.x) {
1161
- record.x = patch.x;
1162
- changed = true;
1163
- }
1164
- if (patch.y !== void 0 && patch.y !== record.y) {
1165
- record.y = patch.y;
1166
- changed = true;
1167
- }
1168
- if (patch.width !== void 0 && patch.width !== record.width) {
1169
- record.width = patch.width;
1170
- changed = true;
1171
- }
1172
- if (patch.height !== void 0 && patch.height !== record.height) {
1173
- record.height = patch.height;
1174
- changed = true;
1175
- }
1176
- if (patch.rotation !== void 0 && patch.rotation !== record.rotation) {
1177
- record.rotation = patch.rotation;
1178
- changed = true;
1179
- }
1180
- if (patch.dpr !== void 0 && patch.dpr !== record.dpr) {
1181
- record.dpr = patch.dpr;
1182
- changed = true;
1183
- }
1184
- if (patch.properties !== void 0 && !sameRecord(record.properties, patch.properties)) {
1185
- record.properties = patch.properties;
1186
- changed = true;
1187
- }
1188
- if (patch.bindings !== void 0 && !sameRecord(record.bindings, patch.bindings)) {
1189
- record.bindings = patch.bindings;
1190
- changed = true;
1329
+ #configure() {
1330
+ const existing = this.#configured;
1331
+ if (existing !== void 0) return existing;
1332
+ const pending = this.#sandbox.call(widgetConfigureMethod, {
1333
+ explicitStepping: true,
1334
+ directTopicService: "simulation-runtime"
1335
+ }).then((result) => result === true).catch((error) => {
1336
+ this.#configured = void 0;
1337
+ const message = `Widget guest configuration failed: ${describeError(error)}`;
1338
+ this.#report("widget/runtime-failed", "runtime", message);
1339
+ throw new WidgetRuntimeError("widget/sandbox-failed", message, { cause: error });
1340
+ });
1341
+ this.#configured = pending;
1342
+ return pending;
1343
+ }
1344
+ async #openAudio(record) {
1345
+ const engine = this.#engine;
1346
+ if (engine === void 0) return { state: "unavailable" };
1347
+ const info = await engine.open(record.instanceId);
1348
+ if (info.session !== void 0) record.audioSession = info.session;
1349
+ return info;
1350
+ }
1351
+ async #call(method, args, record, code, phase) {
1352
+ try {
1353
+ await this.#sandbox.call(method, ...args);
1354
+ } catch (error) {
1355
+ if (this.#disposed) throw new WidgetRuntimeError("widget/disposed", `Widget call "${method}" was cancelled by runtime disposal.`);
1356
+ this.#report(code, phase, `Widget call "${method}" failed for "${record.instanceId}": ${describeError(error)}`, {
1357
+ instanceId: record.instanceId,
1358
+ widget: record.widget
1359
+ });
1360
+ throw new WidgetRuntimeError("widget/sandbox-failed", `Widget call "${method}" failed for "${record.instanceId}": ${describeError(error)}`, { cause: error });
1191
1361
  }
1192
- if (changed) this.#emitUpdate(record);
1193
- return changed;
1194
1362
  }
1195
- /** Installs a frame, closing the one it replaces, and bumps the sequence. */
1196
- setBitmap(instanceId, bitmap) {
1197
- const record = this.#records.get(instanceId);
1198
- if (!record) {
1363
+ #forget(record) {
1364
+ if (this.#instances.get(record.instanceId) === record) this.#instances.delete(record.instanceId);
1365
+ this.#closeRecord(record);
1366
+ }
1367
+ #closeRecord(record) {
1368
+ const bitmap = record.bitmap;
1369
+ record.bitmap = void 0;
1370
+ closeBitmap(bitmap);
1371
+ }
1372
+ async #releaseGuest(instanceId) {
1373
+ try {
1374
+ await this.#sandbox.call(widgetUnmountMethod, instanceId);
1375
+ } catch {}
1376
+ }
1377
+ #onFrame(payload) {
1378
+ const message = payload;
1379
+ if (message === null || typeof message !== "object") return;
1380
+ const { instanceId, bitmap } = message;
1381
+ if (typeof instanceId !== "string" || !isBitmap(bitmap)) return;
1382
+ if (this.#disposed) {
1383
+ closeBitmap(bitmap);
1384
+ return;
1385
+ }
1386
+ const record = this.#instances.get(instanceId);
1387
+ if (record === void 0 || message.generation !== void 0 && message.generation !== record.generation) {
1199
1388
  closeBitmap(bitmap);
1200
1389
  return;
1201
1390
  }
1391
+ const width = frameNumber(message.width, record.width);
1392
+ const height = frameNumber(message.height, record.height);
1393
+ const dpr = frameNumber(message.dpr, record.dpr);
1202
1394
  const previous = record.bitmap;
1203
1395
  record.bitmap = bitmap;
1396
+ record.width = width;
1397
+ record.height = height;
1398
+ record.dpr = dpr;
1204
1399
  record.sequence += 1;
1205
1400
  closeBitmap(previous);
1206
- this.#emitUpdate(record);
1207
- }
1208
- remove(instanceId) {
1209
- const record = this.#records.get(instanceId);
1210
- if (!record) return;
1211
- this.#records.delete(instanceId);
1212
- closeBitmap(record.bitmap);
1213
- record.bitmap = void 0;
1214
- this.#emitChange({
1215
- type: "removed",
1216
- instanceId
1401
+ this.#fire(this.#rendered, "render", {
1402
+ instanceId,
1403
+ width,
1404
+ height,
1405
+ dpr,
1406
+ bitmap,
1407
+ sequence: record.sequence
1217
1408
  });
1218
- this.#emitRemove(instanceId);
1219
1409
  }
1220
- /**
1221
- * Rewrites drawing order to `instanceIds` without touching a frame.
1222
- *
1223
- * Ids the table does not hold are skipped, and records the caller did not list keep their
1224
- * relative order at the end: a mount in flight owns an instance before the document entry that
1225
- * created it is reconciled.
1226
- */
1227
- reorder(instanceIds) {
1228
- const ordered = /* @__PURE__ */ new Map();
1229
- for (const instanceId of instanceIds) {
1230
- const record = this.#records.get(instanceId);
1231
- if (record !== void 0) ordered.set(instanceId, record);
1410
+ #onPublish(payload) {
1411
+ const message = payload;
1412
+ if (message === null || typeof message !== "object") return;
1413
+ const { instanceId, port } = message;
1414
+ if (typeof instanceId !== "string" || typeof port !== "string") return;
1415
+ if (this.#disposed) return;
1416
+ const record = this.#instances.get(instanceId);
1417
+ if (record === void 0) {
1418
+ this.#report("widget/publish-rejected", "publish", `Publish from unknown widget instance "${instanceId}" was dropped.`, {
1419
+ instanceId,
1420
+ port
1421
+ });
1422
+ return;
1232
1423
  }
1233
- for (const [instanceId, record] of this.#records) if (!ordered.has(instanceId)) ordered.set(instanceId, record);
1234
- if (sameOrder([...this.#records.keys()], [...ordered.keys()])) return;
1235
- this.#records.clear();
1236
- for (const [instanceId, record] of ordered) this.#records.set(instanceId, record);
1237
- this.#emitChange({ type: "reordered" });
1238
- this.#reordered.fire([...this.#records.keys()]);
1239
- }
1240
- clear() {
1241
- for (const instanceId of [...this.#records.keys()]) this.remove(instanceId);
1242
- }
1243
- /**
1244
- * Reports every instance as removed and then added again, in drawing order, without touching a
1245
- * record: a subscriber rebuilds its composite from the same bitmaps.
1246
- */
1247
- invalidate() {
1248
- const records = [...this.#records.values()];
1249
- for (const record of records) {
1250
- this.#emitChange({
1251
- type: "removed",
1252
- instanceId: record.instanceId
1424
+ const definitionPort = record.module.definition.ports[port];
1425
+ if (definitionPort === void 0) {
1426
+ this.#report("widget/publish-rejected", "publish", `Widget "${instanceId}" published on unknown port "${port}".`, {
1427
+ instanceId,
1428
+ widget: record.widget,
1429
+ port
1430
+ });
1431
+ return;
1432
+ }
1433
+ if (definitionPort.direction !== "output") {
1434
+ this.#report("widget/publish-rejected", "publish", `Widget "${instanceId}" published on input port "${port}".`, {
1435
+ instanceId,
1436
+ widget: record.widget,
1437
+ port
1253
1438
  });
1254
- this.#emitRemove(record.instanceId);
1439
+ return;
1255
1440
  }
1256
- for (const record of records) {
1257
- this.#emitChange({
1258
- type: "added",
1259
- instanceId: record.instanceId
1441
+ if (!payloadMatches(definitionPort.type, message.payload)) {
1442
+ this.#report("widget/publish-rejected", "publish", `Publish on "${instanceId}.${port}" does not match ${definitionPort.type}.`, {
1443
+ instanceId,
1444
+ widget: record.widget,
1445
+ port
1260
1446
  });
1261
- this.#emitAdd(record);
1447
+ return;
1262
1448
  }
1449
+ this.#fire(this.#published, "publish", {
1450
+ instanceId,
1451
+ port,
1452
+ payload: message.payload,
1453
+ simTime: publishTime(message.simTime, this.#simTime),
1454
+ ...message.direct === true ? { direct: true } : {}
1455
+ });
1263
1456
  }
1264
- #emitUpdate(record) {
1265
- this.#emitChange({
1266
- type: "updated",
1267
- instanceId: record.instanceId
1457
+ #onError(payload) {
1458
+ const message = payload;
1459
+ if (message === null || typeof message !== "object") return;
1460
+ if (typeof message.instanceId !== "string") return;
1461
+ if (message.phase !== "render" && message.phase !== "deliver") return;
1462
+ const record = this.#instances.get(message.instanceId);
1463
+ const code = message.phase === "render" ? "widget/render-failed" : "widget/deliver-failed";
1464
+ const name = message.error?.name ?? "Error";
1465
+ const text = message.error?.message ?? "Unknown widget failure";
1466
+ this.#report(code, message.phase, `Widget "${message.instanceId}" failed during ${message.phase}: ${name}: ${text}`, {
1467
+ instanceId: message.instanceId,
1468
+ ...record === void 0 ? {} : { widget: record.widget }
1268
1469
  });
1269
- this.#updated.fire(toWidget(record));
1270
1470
  }
1271
- #emitAdd(record) {
1272
- this.#added.fire(toWidget(record));
1471
+ #onAssetFailed(payload) {
1472
+ const message = payload;
1473
+ if (message === null || typeof message !== "object") return;
1474
+ if (typeof message.instanceId !== "string") return;
1475
+ const src = typeof message.src === "string" ? message.src : "unknown";
1476
+ const name = message.error?.name ?? "Error";
1477
+ const text = message.error?.message ?? "Unknown asset failure";
1478
+ const record = this.#instances.get(message.instanceId);
1479
+ this.#report("widget/asset-failed", "asset", `Widget "${message.instanceId}" could not read asset "${src}": ${name}: ${text}`, {
1480
+ instanceId: message.instanceId,
1481
+ ...record === void 0 ? {} : { widget: record.widget }
1482
+ });
1273
1483
  }
1274
- #emitRemove(instanceId) {
1275
- this.#removed.fire(instanceId);
1484
+ #report(code, phase, message, ids = {}) {
1485
+ if (this.#disposed) return;
1486
+ const diagnostic = {
1487
+ code,
1488
+ message,
1489
+ phase,
1490
+ ...ids.instanceId === void 0 ? {} : { instanceId: ids.instanceId },
1491
+ ...ids.widget === void 0 ? {} : { widget: ids.widget },
1492
+ ...ids.port === void 0 ? {} : { port: ids.port }
1493
+ };
1494
+ this.#fire(this.#diagnostics, "diagnostic", diagnostic);
1276
1495
  }
1277
- #emitChange(change) {
1278
- for (const listener of [...this.#changes]) invoke(listener, change, "layer listener");
1496
+ /** Observer exceptions never break the instance flow a diagnostic or frame reports. */
1497
+ #fire(emitter, label, value) {
1498
+ try {
1499
+ emitter.fire(value);
1500
+ } catch (error) {
1501
+ console.error(`[@mica-js/widget] ${label} listener threw`, error);
1502
+ }
1279
1503
  }
1280
1504
  };
1281
- function toWidget(record) {
1505
+ function normalizePrepared(instance) {
1506
+ if (typeof instance !== "object" || instance === null) throw new WidgetRuntimeError("widget/invalid-instance", "A prepared widget is required.");
1507
+ requireId(instance.instanceId);
1508
+ if (typeof instance.widget !== "string" || !instance.widget.includes(":")) throw new WidgetRuntimeError("widget/invalid-instance", "A prepared widget needs a \"<package>:<widget>\" reference.");
1509
+ const module = instance.module;
1510
+ if (typeof module !== "object" || module === null || typeof module.code !== "string" || typeof module.definition !== "object" || module.definition === null || typeof module.definition.ports !== "object" || module.definition.ports === null) throw new WidgetRuntimeError("widget/invalid-instance", `Widget "${instance.widget}" has no complete module.`);
1282
1511
  return {
1283
- instanceId: record.instanceId,
1284
- widget: record.widget,
1285
- x: record.x,
1286
- y: record.y,
1287
- width: record.width,
1288
- height: record.height,
1289
- rotation: record.rotation,
1290
- dpr: record.dpr,
1291
- properties: record.properties,
1292
- bindings: record.bindings,
1293
- bitmap: record.bitmap,
1294
- sequence: record.sequence
1512
+ instanceId: instance.instanceId,
1513
+ widget: instance.widget,
1514
+ module,
1515
+ width: requireSize(instance.width, "width"),
1516
+ height: requireSize(instance.height, "height"),
1517
+ dpr: requireDpr(instance.dpr),
1518
+ ...instance.properties === void 0 ? {} : { properties: instance.properties },
1519
+ ...instance.assets === void 0 ? {} : { assets: instance.assets }
1295
1520
  };
1296
1521
  }
1297
- function toInstance(record) {
1298
- return {
1299
- instanceId: record.instanceId,
1300
- widget: record.widget,
1301
- x: record.x,
1302
- y: record.y,
1303
- width: record.width,
1304
- height: record.height,
1305
- rotation: record.rotation,
1306
- dpr: record.dpr,
1307
- properties: record.properties,
1308
- bindings: record.bindings,
1309
- sequence: record.sequence
1310
- };
1522
+ function requireId(value) {
1523
+ if (typeof value !== "string" || value === "") throw new WidgetRuntimeError("widget/invalid-instance", "A widget instance id must be a nonempty string.");
1524
+ return value;
1525
+ }
1526
+ function requireSize(value, name) {
1527
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new WidgetRuntimeError("widget/invalid-instance", `${name}=${String(value)} must be a finite nonnegative number.`);
1528
+ return value;
1311
1529
  }
1312
- function invoke(listener, payload, name, thisArgs) {
1530
+ function requireDpr(value) {
1531
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) throw new WidgetRuntimeError("widget/invalid-instance", `dpr=${String(value)} must be a finite positive number.`);
1532
+ return value;
1533
+ }
1534
+ function requireTime(value, name) {
1313
1535
  try {
1314
- listener.call(thisArgs, payload);
1536
+ return timePs(value);
1315
1537
  } catch (error) {
1316
- console.error(`[@mica-js/widget] ${name} threw`, error);
1538
+ throw new WidgetRuntimeError("widget/invalid-time", `${name} must be a valid time in picoseconds: ${describeError(error)}`, { cause: error });
1317
1539
  }
1318
1540
  }
1319
- /** Closes a bitmap without letting a double close escape. */
1320
- function closeBitmap(bitmap) {
1321
- if (!bitmap) return;
1541
+ function publishTime(value, fallback) {
1542
+ if (typeof value !== "number") return fallback;
1322
1543
  try {
1323
- bitmap.close();
1324
- } catch {}
1325
- }
1326
- /**
1327
- * Shallow comparison of two record maps.
1328
- *
1329
- * The document owns property/binding values, so a nested object only counts as changed when the
1330
- * caller replaced the object itself; deep equality would swallow those edits. The key sets matter
1331
- * as much as the values, because a missing property key falls back to the definition default.
1332
- */
1333
- function sameRecord(left, right) {
1334
- if (left === right) return true;
1335
- const keys = Object.keys(left);
1336
- return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && Object.is(left[key], right[key]));
1337
- }
1338
- function sameOrder(left, right) {
1339
- return left.length === right.length && left.every((id, index) => id === right[index]);
1340
- }
1341
- //#endregion
1342
- //#region src/host/widget-host.ts
1343
- /** Host state before any document was loaded. */
1344
- var EMPTY_DOCUMENT = {
1345
- version: CANVAS_VERSION,
1346
- widgets: []
1347
- };
1348
- /** One fixed step, in milliseconds; the host converts it to picoseconds for the simulator. */
1349
- var DEFAULT_STEP_MS = 25;
1350
- var PS_PER_MS = 1e9;
1351
- function defaultRequestFrame(callback, delayMs) {
1352
- const timer = setTimeout(callback, delayMs);
1353
- return () => {
1354
- clearTimeout(timer);
1355
- };
1356
- }
1357
- /** Startup or shutdown failure; already reported, so call sites must not report it twice. */
1358
- var WidgetRuntimeError = class extends Error {
1359
- constructor(message, options) {
1360
- super(message, options);
1361
- this.name = "WidgetRuntimeError";
1362
- }
1363
- };
1364
- /**
1365
- * The instance was removed (or the host disposed) while its mount was in flight. Rejecting keeps
1366
- * `mount()` honest instead of resolving for an instance that no longer has a layer.
1367
- */
1368
- var WidgetMountCancelledError = class extends Error {
1369
- constructor(instanceId) {
1370
- super(`Mount of widget instance "${instanceId}" was cancelled before it finished`);
1371
- this.name = "WidgetMountCancelledError";
1372
- }
1373
- };
1374
- /**
1375
- * Creates the widget host.
1376
- *
1377
- * The document is the single source of truth: instances are mounted, resized, repropped and
1378
- * reordered to match it. The sandbox starts lazily on the first instance and every concurrent mount
1379
- * shares that one startup, so a host with no instances never pays for an iframe and a worker. After
1380
- * a crash the next reconciliation starts a fresh sandbox instead of rebuilding instances
1381
- * automatically.
1382
- */
1383
- function createWidgetHost(options, createSandbox) {
1384
- return new WidgetHostImpl(options, createSandbox);
1385
- }
1386
- var WidgetHostImpl = class {
1387
- #provider;
1388
- #fs;
1389
- #container;
1390
- #onDiagnostic;
1391
- #onPublish;
1392
- #assets;
1393
- #catalog;
1394
- /** Catalog assembled from the widget provider and the running simulation (RFC 0018). */
1395
- #autoCatalog = new HostBindingCatalog();
1396
- #deviceHost;
1397
- #mode;
1398
- #frameOptions;
1399
- #createSandbox;
1400
- #audio;
1401
- #store = new WidgetStore();
1402
- #instances = /* @__PURE__ */ new Map();
1403
- #detachers = [];
1404
- #documentListeners = /* @__PURE__ */ new Set();
1405
- /** Input events waiting for the next step start; only used while a frame clock runs. */
1406
- #pendingInputs = [];
1407
- /** `WidgetHost.audio`; a no-op control surface when no audio was configured. */
1408
- audio;
1409
- /** Port the worklet handed over before a sandbox existed; flushed on the next attach. */
1410
- #pendingAudioPort;
1411
- /** Latest availability, replayed to a sandbox that was created after the change. */
1412
- #lastAudioState;
1413
- #document = EMPTY_DOCUMENT;
1414
- /** Instances whose binding diagnostics prevent guest mounting for the current snapshot. */
1415
- #bindingSkipped = /* @__PURE__ */ new Set();
1416
- /** URI the current snapshot was read from; `undefined` for the parsed-document entry. */
1417
- #documentUri;
1418
- /** Absolute URI of the schematic the runtime was told to load. */
1419
- #schematicUri;
1420
- #unsubscribeDevicePublish;
1421
- #cancelFrame;
1422
- #paused = false;
1423
- #advancing = false;
1424
- /** Whether a document was loaded; only then does the clock have something to advance. */
1425
- #loaded = false;
1426
- /** Last simulation time reported by the device host, used as a publish timestamp fallback. */
1427
- #simTime = 0;
1428
- /**
1429
- * Last payload the simulation published per endpoint.
1430
- *
1431
- * A level topic only publishes when it changes, so an instance that mounts afterwards is seeded
1432
- * from here instead of waiting for a change that may never come.
1433
- */
1434
- #lastPublished = /* @__PURE__ */ new Map();
1435
- #reconcilePending = false;
1436
- /** The next coordination pass has to reset the guest before it syncs instances. */
1437
- #resetPending = false;
1438
- /** The next coordination pass has to reset the device before it resets the guest. */
1439
- #deviceResetPending = false;
1440
- /** The next coordination pass has to re-read the document and reload the schematic. */
1441
- #reloadPending = false;
1442
- #reloadSchematicPending = false;
1443
- #reconcilePass;
1444
- /** Identifies the drain that owns {@link #reconcilePass}; only that drain may release it. */
1445
- #reconcileOwner = 0;
1446
- /**
1447
- * One end of the direct device channel, consumed by the first sandbox this host starts.
1448
- *
1449
- * It is transferred to the guest at startup, so it cannot be reused: a restart runs in fallback.
1450
- */
1451
- #devicePort;
1452
- /** True while the running guest owns the direct device channel and routes topic traffic itself. */
1453
- #directDevice = false;
1454
- #sandbox;
1455
- #starting;
1456
- #disposing;
1457
- #disposed = false;
1458
- #dpr;
1459
- constructor(options, createSandbox) {
1460
- const provider = options.widgetProvider ?? options.provider;
1461
- if (provider === void 0) throw new TypeError("createWidgetHost requires a widgetProvider");
1462
- this.#provider = provider;
1463
- this.#fs = options.fs;
1464
- this.#container = options.container;
1465
- this.#onDiagnostic = options.onDidReportDiagnostic ?? options.onDiagnostic;
1466
- this.#onPublish = options.onDidPublish ?? options.onPublish;
1467
- this.#assets = options.assets;
1468
- this.#catalog = options.catalog;
1469
- this.#deviceHost = options.deviceHost;
1470
- this.#devicePort = options.devicePort;
1471
- this.#mode = options.mode ?? "simulation";
1472
- const frame = options.frame;
1473
- const stepMs = frame?.stepMs !== void 0 && Number.isFinite(frame.stepMs) && frame.stepMs > 0 ? frame.stepMs : DEFAULT_STEP_MS;
1474
- this.#frameOptions = {
1475
- stepMs,
1476
- requestFrame: frame?.requestFrame ?? ((callback) => defaultRequestFrame(callback, stepMs))
1477
- };
1478
- this.#createSandbox = createSandbox;
1479
- this.#dpr = options.dpr ?? currentDevicePixelRatio();
1480
- let audio;
1481
- if (options.audio !== void 0) {
1482
- const getAudioWorklet = options.audio.getAudioWorklet;
1483
- const context = options.audio.context;
1484
- const audioOptions = {
1485
- context,
1486
- report: (code, instanceId, message) => this.#report(code, message, this.#instanceIds(instanceId)),
1487
- notify: {
1488
- emitPort: (port) => this.#emitAudioPort(port),
1489
- emitState: (state) => this.#emitAudioState(state)
1490
- }
1491
- };
1492
- if (options.audio.destination !== void 0) Object.assign(audioOptions, { destination: options.audio.destination });
1493
- if (getAudioWorklet !== void 0) Object.assign(audioOptions, { loadWorklet: () => getAudioWorklet(context) });
1494
- if (options.audio.limits !== void 0) Object.assign(audioOptions, { limits: options.audio.limits });
1495
- audio = new WidgetAudioEngine(audioOptions);
1496
- }
1497
- this.#audio = audio;
1498
- this.audio = this.#audio ?? NO_AUDIO_CONTROLS;
1499
- this.#unsubscribeDevicePublish = this.#deviceHost.onDidPublish((publish) => {
1500
- if (this.#mode === "simulation") this.#onSimulationPublish(publish);
1501
- });
1502
- }
1503
- getDocument() {
1504
- return this.#document;
1505
- }
1506
- getMode() {
1507
- return this.#mode;
1508
- }
1509
- async setMode(mode) {
1510
- if (this.#disposed) throw new WidgetRuntimeError("Widget host is disposed");
1511
- if (mode === this.#mode) return;
1512
- const previous = this.#mode;
1513
- this.#stopClock();
1514
- this.#pendingInputs.length = 0;
1515
- try {
1516
- this.#clearWidgetInstances();
1517
- this.#resetPending = true;
1518
- this.#deviceResetPending = true;
1519
- this.#reloadPending = false;
1520
- this.#reloadSchematicPending = false;
1521
- this.#mode = mode;
1522
- await this.#scheduleReconcile();
1523
- if (this.#mode === "simulation" && this.#loaded && !this.#paused) this.#startClock();
1524
- } catch (error) {
1525
- this.#mode = previous;
1526
- if (previous === "simulation" && this.#loaded && !this.#paused) this.#startClock();
1527
- throw error;
1528
- }
1529
- }
1530
- getLayers() {
1531
- return this.#store;
1532
- }
1533
- listInstances() {
1534
- return this.#store.listInstances();
1535
- }
1536
- onDidAddWidget = this.#store.onDidAddWidget;
1537
- onDidChangeWidget = this.#store.onDidChangeWidget;
1538
- onDidRemoveWidget = this.#store.onDidRemoveWidget;
1539
- onDidReorderWidgets = this.#store.onDidReorderWidgets;
1540
- invalidate() {
1541
- if (this.#disposed) return;
1542
- this.#store.invalidate();
1543
- }
1544
- pause() {
1545
- this.#paused = true;
1546
- this.#stopClock();
1547
- }
1548
- resume() {
1549
- if (this.#disposed) return;
1550
- this.#paused = false;
1551
- if (this.#loaded) this.#startClock();
1552
- }
1553
- async loadDocument(source) {
1554
- const documentUri = typeof source === "string" ? source : void 0;
1555
- const input = documentUri === void 0 ? source : await this.#readDocumentText(documentUri);
1556
- const parsed = parseCanvas(input);
1557
- const schematicUri = this.#resolveSchematicUri(parsed, documentUri);
1558
- await this.#loadSchematic(schematicUri);
1559
- await this.#refreshCatalog(parsed, parsed.schematic, schematicUri);
1560
- const bindingSkipped = this.#bindingSkipIds(parsed);
1561
- this.#documentUri = documentUri;
1562
- this.#schematicUri = schematicUri;
1563
- this.#commit(parsed, bindingSkipped);
1564
- const pass = this.#scheduleReconcile();
1565
- this.#emitDocument(parsed);
1566
- await pass;
1567
- this.#loaded = true;
1568
- if (this.#mode === "simulation") this.#startClock();
1569
- }
1570
- /**
1571
- * Reads a document URI: `data:` decodes locally, every other scheme goes through `fs`.
1572
- *
1573
- * Relative references never reach the reader; the caller supplies an absolute URI, which is also
1574
- * what `HostFs.read` expects.
1575
- */
1576
- async #readDocumentText(uri) {
1577
- if (!isAbsoluteHostUri(uri)) throw new TypeError(`WidgetHost.loadDocument requires an absolute URI: ${uri}`);
1578
- if (uri.slice(0, 5).toLowerCase() === "data:") return decodeDataUriText(uri);
1579
- const fs = this.#fs;
1580
- if (fs === void 0) throw new HostFsError("NoFileSystem", uri, "WidgetHost has no HostFs configured to read this document URI");
1581
- return new TextDecoder().decode(await fs.read(uri));
1582
- }
1583
- /**
1584
- * Resolves the document's `schematic` reference against the canvas URI.
1585
- *
1586
- * `undefined` clears the runtime. An absolute reference passes through; a relative one needs the
1587
- * canvas URI as its base, so the parsed-document form can only carry absolute references.
1588
- */
1589
- #resolveSchematicUri(document, documentUri) {
1590
- const schematic = document.schematic;
1591
- if (schematic === void 0 || schematic === "") return void 0;
1592
- if (documentUri === void 0) return schematic;
1593
- return resolveHostUri(documentUri, schematic);
1594
- }
1595
- /** Loads (or clears) the schematic on the device host. */
1596
- async #loadSchematic(uri) {
1597
- await this.#deviceHost.loadSchematic(uri);
1598
- }
1599
- applyCommand(command) {
1600
- const document = applyCanvasCommand(this.#document, command);
1601
- const bindingSkipped = this.#bindingSkipIds(document);
1602
- this.#commit(document, bindingSkipped);
1603
- this.#scheduleReconcile();
1604
- this.#emitDocument(document);
1605
- }
1606
- onDocumentChange(listener) {
1607
- this.#documentListeners.add(listener);
1608
- return () => {
1609
- this.#documentListeners.delete(listener);
1610
- };
1611
- }
1612
- reset() {
1613
- if (this.#disposed) return Promise.reject(new WidgetRuntimeError("Widget host is disposed"));
1614
- return this.#resetRuntime({
1615
- reloadDocument: this.#documentUri !== void 0,
1616
- reloadSchematic: this.#schematicUri !== void 0,
1617
- resetDevice: true
1618
- });
1619
- }
1620
- #clearWidgetInstances() {
1621
- for (const instanceId of this.#instances.keys()) this.#audio?.close(instanceId);
1622
- this.#instances.clear();
1623
- this.#store.clear();
1624
- }
1625
- async #resetRuntime(options) {
1626
- this.#stopClock();
1627
- this.#pendingInputs.length = 0;
1628
- this.#clearWidgetInstances();
1629
- this.#resetPending = true;
1630
- this.#deviceResetPending = options.resetDevice;
1631
- this.#reloadPending = options.reloadDocument;
1632
- this.#reloadSchematicPending = options.reloadSchematic;
1633
- await this.#scheduleReconcile();
1634
- if (this.#mode === "simulation" && this.#loaded && !this.#paused) this.#startClock();
1635
- }
1636
- deliver(instanceId, port, payload, simTime) {
1637
- if (!this.#requireInstance(instanceId)) return;
1638
- this.#fire("widget/deliver-failed", widgetDeliverMethod, [
1639
- instanceId,
1640
- port,
1641
- payload,
1642
- simTime
1643
- ], instanceId);
1644
- }
1645
- dispatch(instanceId, event) {
1646
- if (!this.#requireInstance(instanceId)) return;
1647
- if (this.#loaded) {
1648
- this.#pendingInputs.push({
1649
- instanceId,
1650
- event
1651
- });
1652
- return;
1653
- }
1654
- this.#fire("widget/deliver-failed", widgetPointerMethod, [instanceId, event], instanceId);
1655
- }
1656
- resize(dpr) {
1657
- if (!Number.isFinite(dpr) || dpr <= 0 || dpr === this.#dpr) return;
1658
- this.#dpr = dpr;
1659
- for (const layer of this.#store.list()) {
1660
- this.#store.update(layer.instanceId, { dpr });
1661
- this.#fire("widget/render-failed", widgetResizeMethod, [
1662
- layer.instanceId,
1663
- layer.width,
1664
- layer.height,
1665
- dpr
1666
- ], layer.instanceId);
1667
- }
1668
- }
1669
- dispose() {
1670
- const pending = this.#disposing ?? this.#shutdown();
1671
- this.#disposing = pending;
1672
- return pending;
1673
- }
1674
- /**
1675
- * Runs the binding checks both document entry points share.
1676
- *
1677
- * An explicit `catalog` option wins. Otherwise the host checks against the catalog it assembled
1678
- * from the widget provider and the running simulation (RFC 0018).
1679
- */
1680
- #bindingSkipIds(document) {
1681
- const explicit = this.#catalog;
1682
- const catalog = explicit ?? this.#autoCatalog;
1683
- const resolved = explicit !== void 0 || document.widgets.every((widget) => this.#autoCatalog.knows(widget.widget));
1684
- const diagnostics = validateCanvasBindings(document, resolved ? { catalog } : {
1685
- catalog,
1686
- skipWidgets: true
1687
- });
1688
- const bindingCodes = /* @__PURE__ */ new Set([
1689
- "canvas/unknown-symbol",
1690
- "canvas/unknown-target-port",
1691
- "canvas/unknown-port",
1692
- "topic/type-mismatch"
1693
- ]);
1694
- if (diagnostics.some((diagnostic) => {
1695
- const pointer = diagnostic.pointer ?? "";
1696
- return !bindingCodes.has(diagnostic.code) || !/^\/widgets\/\d+\/bindings(?:\/|$)/.test(pointer);
1697
- })) assertCanvasBindings(document, resolved ? { catalog } : {
1698
- catalog,
1699
- skipWidgets: true
1700
- });
1701
- const skipped = /* @__PURE__ */ new Set();
1702
- for (const diagnostic of diagnostics) {
1703
- if (!bindingCodes.has(diagnostic.code)) continue;
1704
- const match = /^\/widgets\/(\d+)\/bindings(?:\/|$)/.exec(diagnostic.pointer ?? "");
1705
- if (match === null) continue;
1706
- const widget = document.widgets[Number(match[1])];
1707
- if (widget !== void 0) {
1708
- skipped.add(widget.id);
1709
- this.#reportBindingDiagnostic(widget, diagnostic.code, diagnostic.message, diagnostic.pointer);
1710
- }
1711
- }
1712
- return skipped;
1713
- }
1714
- /**
1715
- * Re-assembles the automatic catalog after the device host loaded a schematic (RFC 0018).
1716
- *
1717
- * The device side is read once the load resolved, so `getTopics()` and `getSchematic()` describe
1718
- * the runtime the instances will talk to; the widget side resolves every reference the document
1719
- * names before validation runs.
1720
- */
1721
- async #refreshCatalog(document, schematic, schematicUri) {
1722
- if (this.#catalog !== void 0) return;
1723
- const deviceHost = this.#deviceHost;
1724
- const [topics, loaded] = await Promise.all([deviceHost.getTopics(), deviceHost.getSchematic()]);
1725
- this.#autoCatalog.setDeviceFacts({
1726
- schematics: [schematic, schematicUri],
1727
- schematic: loaded,
1728
- topics
1729
- });
1730
- await this.#resolveDefinitions(document);
1731
- }
1732
- /**
1733
- * Resolves the widget definitions the document references, so validation itself stays synchronous.
1734
- *
1735
- * A rejection or an unknown reference is only recorded as "not resolved": the mount of every
1736
- * instance using it reports the failure on its own.
1737
- */
1738
- async #resolveDefinitions(document) {
1739
- const refs = new Set(document.widgets.map((widget) => widget.widget));
1740
- await Promise.all([...refs].map(async (ref) => {
1741
- if (this.#autoCatalog.knows(ref)) return;
1742
- try {
1743
- const module = await this.#provider.resolve(ref);
1744
- if (module !== void 0) this.#autoCatalog.recordDefinition(ref, module.definition);
1745
- } catch {}
1746
- }));
1747
- }
1748
- /**
1749
- * Makes `document` the new snapshot and drops the instances it no longer lists.
1750
- *
1751
- * Removal is synchronous on purpose: a mount still in flight for a removed id has to be cancelled
1752
- * right away, while the coordination pass that would have removed it may be blocked on it.
1753
- */
1754
- #commit(document, bindingSkipped = /* @__PURE__ */ new Set()) {
1755
- this.#document = document;
1756
- this.#bindingSkipped = new Set(bindingSkipped);
1757
- const live = new Set(document.widgets.map((widget) => widget.id));
1758
- for (const instanceId of [...this.#instances.keys()]) if (!live.has(instanceId)) this.#unmount(instanceId);
1759
- }
1760
- /**
1761
- * Queues a coordination pass and returns the running queue.
1762
- *
1763
- * A pass reads {@link document} per instance, so everything committed while it waits is coalesced
1764
- * into the next iteration; the promise settles only once the queue has caught up.
1765
- *
1766
- * The drain starts on a microtask instead of from here: {@link #syncInstances} notifies the layer
1767
- * store synchronously from inside a guest await, and a subscriber that applies a command from that
1768
- * notification would otherwise re-enter while the slot below is still empty and start a second,
1769
- * concurrent drain.
1770
- */
1771
- #scheduleReconcile() {
1772
- this.#reconcilePending = true;
1773
- this.#reconcilePass ??= Promise.resolve().then(() => this.#drainReconcile());
1774
- return this.#reconcilePass;
1775
- }
1776
- async #drainReconcile() {
1777
- const owner = ++this.#reconcileOwner;
1778
- try {
1779
- while (this.#reconcilePending && !this.#disposed) {
1780
- this.#reconcilePending = false;
1781
- if (this.#reloadPending) {
1782
- this.#reloadPending = false;
1783
- await this.#reloadDocument();
1784
- }
1785
- if (this.#deviceResetPending) {
1786
- this.#deviceResetPending = false;
1787
- await this.#deviceHost.reset();
1788
- this.#simTime = await this.#deviceHost.getSimTime();
1789
- this.#lastPublished.clear();
1790
- }
1791
- if (this.#resetPending) {
1792
- this.#resetPending = false;
1793
- await this.#resetGuestRuntime();
1794
- if (this.#reloadSchematicPending) {
1795
- this.#reloadSchematicPending = false;
1796
- await this.#reloadSchematic();
1797
- }
1798
- }
1799
- await this.#syncInstances();
1800
- }
1801
- } finally {
1802
- if (this.#reconcileOwner === owner) {
1803
- this.#reconcilePending = false;
1804
- this.#reconcilePass = void 0;
1805
- }
1806
- }
1807
- }
1808
- /**
1809
- * Re-reads the document behind the current URI, for `reset()`.
1810
- *
1811
- * A document that no longer parses is reported instead of rejecting: the reset still has to put
1812
- * the instances back with the snapshot the host already holds.
1813
- */
1814
- async #reloadDocument() {
1815
- const uri = this.#documentUri;
1816
- if (uri === void 0) return;
1817
- try {
1818
- const parsed = parseCanvas(await this.#readDocumentText(uri));
1819
- const bindingSkipped = this.#bindingSkipIds(parsed);
1820
- this.#schematicUri = this.#resolveSchematicUri(parsed, uri);
1821
- this.#commit(parsed, bindingSkipped);
1822
- this.#emitDocument(parsed);
1823
- } catch (error) {
1824
- this.#report("widget/runtime-failed", `The canvas document "${uri}" could not be reloaded: ${describeError(error)}`);
1825
- }
1826
- }
1827
- /** Re-executes the runtime half of `loadDocument`: the schematic goes back to time 0. */
1828
- async #reloadSchematic() {
1829
- try {
1830
- await this.#loadSchematic(this.#schematicUri);
1831
- await this.#refreshCatalog(this.#document, this.#document.schematic, this.#schematicUri);
1832
- } catch (error) {
1833
- this.#report("widget/runtime-failed", `The schematic could not be reloaded: ${describeError(error)}`);
1834
- }
1835
- }
1836
- /** Mounts, resizes, sets properties and reorders instances to match the document. */
1837
- async #syncInstances() {
1838
- for (const { id: instanceId } of this.#document.widgets) {
1839
- if (this.#disposed) return;
1840
- const widget = this.#document.widgets.find((entry) => entry.id === instanceId);
1841
- if (widget === void 0) continue;
1842
- if (this.#bindingSkipped.has(instanceId)) {
1843
- if (this.#instances.has(instanceId)) this.#unmount(instanceId);
1844
- continue;
1845
- }
1846
- await this.#syncInstance(widget);
1847
- }
1848
- this.#store.reorder(this.#document.widgets.map((widget) => widget.id));
1849
- }
1850
- async #syncInstance(widget) {
1851
- const existing = this.#instances.get(widget.id);
1852
- if (existing === void 0) {
1853
- await this.#mount(widget);
1854
- return;
1855
- }
1856
- if (existing.widget !== widget.widget) {
1857
- this.#unmount(widget.id);
1858
- await this.#mount(widget);
1859
- return;
1860
- }
1861
- const placement = placementOf(widget);
1862
- const props = widget.properties ?? {};
1863
- this.#store.update(widget.id, {
1864
- ...placement,
1865
- properties: props,
1866
- bindings: widget.bindings ?? {}
1867
- });
1868
- if (placement.width !== existing.placement.width || placement.height !== existing.placement.height) this.#resizeGuest(widget.id, placement.width, placement.height);
1869
- existing.placement = placement;
1870
- const bindings = widget.bindings ?? {};
1871
- if (!sameBindings(existing.bindings, bindings)) this.#setBindings(widget.id, bindings);
1872
- if (!sameRecord(existing.props, props)) {
1873
- if (this.#referencesUnprefetchedAsset(existing, props)) {
1874
- this.#unmount(widget.id);
1875
- await this.#mount(widget);
1876
- return;
1877
- }
1878
- this.#setProperties(widget.id, props);
1879
- }
1880
- }
1881
- #referencesUnprefetchedAsset(existing, props) {
1882
- if (this.#assets === void 0) return false;
1883
- for (const src of collectAssetRefs(props).keys()) if (!existing.assets.has(src)) return true;
1884
- return false;
1885
- }
1886
- /**
1887
- * Mounts one document instance. Failures stay inside that instance: the mount attempt already
1888
- * reported its own diagnostic, and the document is never rolled back for it.
1889
- */
1890
- async #mount(widget) {
1891
- try {
1892
- await this.#startInstance(widget);
1893
- } catch {}
1894
- }
1895
- async #startInstance(widget) {
1896
- const { id: instanceId, widget: ref } = widget;
1897
- if (this.#disposed) {
1898
- this.#report("widget/runtime-failed", "The widget host is disposed.", {
1899
- instanceId,
1900
- widget: ref
1901
- });
1902
- throw new WidgetRuntimeError("Widget host is disposed");
1903
- }
1904
- if (this.#instances.has(instanceId)) {
1905
- this.#report("widget/instance-exists", `Widget instance "${instanceId}" is already mounted.`, {
1906
- instanceId,
1907
- widget: ref
1908
- });
1909
- return;
1910
- }
1911
- const record = {
1912
- widget: ref,
1913
- token: Symbol(instanceId),
1914
- placement: placementOf(widget),
1915
- props: widget.properties ?? {},
1916
- bindings: widget.bindings ?? {},
1917
- assets: /* @__PURE__ */ new Set()
1918
- };
1919
- this.#instances.set(instanceId, record);
1920
- this.#store.add({
1921
- instanceId,
1922
- widget: ref,
1923
- ...record.placement,
1924
- dpr: this.#dpr,
1925
- properties: record.props,
1926
- bindings: widget.bindings ?? {}
1927
- });
1928
- this.#store.reorder(this.#document.widgets.map((entry) => entry.id));
1929
- let mounted = false;
1930
- try {
1931
- mounted = await this.#mountInstance(instanceId, ref, record);
1932
- } finally {
1933
- if (!mounted) this.#forget(instanceId, record);
1934
- }
1935
- if (mounted) {
1936
- this.#setBindings(instanceId, record.bindings);
1937
- this.#replayPublished(widget);
1938
- }
1939
- }
1940
- /**
1941
- * Runs one mount attempt; every await re-checks that this attempt still owns the id.
1942
- *
1943
- * @returns always `true`; a cancelled attempt throws instead of reporting success.
1944
- */
1945
- async #mountInstance(instanceId, ref, record) {
1946
- let module;
1947
- try {
1948
- module = await this.#provider.resolve(ref);
1949
- } catch (error) {
1950
- this.#report("widget/mount-failed", `Widget "${ref}" could not be resolved: ${describeError(error)}`, {
1951
- instanceId,
1952
- widget: ref
1953
- });
1954
- throw error;
1955
- }
1956
- const resolved = module === void 0 ? void 0 : splitRef(ref);
1957
- if (module === void 0 || resolved === void 0) {
1958
- this.#report("widget/unknown-widget", module === void 0 ? `No widget is registered as "${ref}".` : `Widget reference "${ref}" must use the "<package>:<widget>" form.`, {
1959
- instanceId,
1960
- widget: ref
1961
- });
1962
- return false;
1963
- }
1964
- this.#autoCatalog.recordDefinition(ref, module.definition);
1965
- this.#requireOwnership(instanceId, record);
1966
- const sandbox = await this.#ensureSandbox();
1967
- this.#requireOwnership(instanceId, record);
1968
- try {
1969
- await sandbox.call(widgetLoadMethod, { packages: [{
1970
- id: resolved.packageId,
1971
- modules: { [resolved.widgetId]: {
1972
- definition: module.definition,
1973
- code: module.code
1974
- } }
1975
- }] });
1976
- this.#requireOwnership(instanceId, record);
1977
- const props = mergeProperties(module.definition?.properties, record.props);
1978
- const assets = await this.#prefetchAssets(instanceId, ref, props);
1979
- record.assets = new Set(collectAssetRefs(props).keys());
1980
- this.#requireOwnership(instanceId, record);
1981
- const layer = this.#store.get(instanceId);
1982
- if (!layer) throw new WidgetMountCancelledError(instanceId);
1983
- const audio = this.#audio === void 0 ? { state: "unavailable" } : await this.#audio.open(instanceId);
1984
- if (audio.session !== void 0) record.audioSession = audio.session;
1985
- this.#requireOwnership(instanceId, record);
1986
- await sandbox.call(widgetMountMethod, {
1987
- instanceId,
1988
- widget: ref,
1989
- width: layer.width,
1990
- height: layer.height,
1991
- dpr: layer.dpr,
1992
- props,
1993
- ...assets === void 0 ? {} : { assets },
1994
- audio
1995
- });
1996
- } catch (error) {
1997
- if (error instanceof WidgetRuntimeError) throw error;
1998
- if (error instanceof WidgetMountCancelledError) throw error;
1999
- if (this.#disposed) throw new WidgetMountCancelledError(instanceId);
2000
- if (this.#isTerminated()) {
2001
- this.#failRuntime("The widget sandbox terminated during mount.");
2002
- throw error;
2003
- }
2004
- this.#report("widget/mount-failed", `Widget "${ref}" failed to mount: ${describeError(error)}`, {
2005
- instanceId,
2006
- widget: ref
2007
- });
2008
- throw error;
2009
- }
2010
- if (!this.#owns(instanceId, record)) {
2011
- if (!this.#instances.has(instanceId)) await releaseGuestInstance(sandbox, instanceId);
2012
- throw new WidgetMountCancelledError(instanceId);
2013
- }
2014
- return true;
2015
- }
2016
- #unmount(instanceId) {
2017
- const instance = this.#instances.get(instanceId);
2018
- if (!instance) {
2019
- this.#report("widget/instance-not-found", `Widget instance "${instanceId}" is not mounted.`, { instanceId });
2020
- return;
2021
- }
2022
- this.#forget(instanceId, instance);
2023
- this.#fire(void 0, widgetUnmountMethod, [instanceId], instanceId);
2024
- }
2025
- /** Repaints one instance at a new size; the store already carries the new geometry. */
2026
- #resizeGuest(instanceId, width, height) {
2027
- if (!this.#requireInstance(instanceId)) return;
2028
- const layer = this.#store.get(instanceId);
2029
- if (!layer) return;
2030
- this.#fire("widget/render-failed", widgetResizeMethod, [
2031
- instanceId,
2032
- width,
2033
- height,
2034
- layer.dpr
2035
- ], instanceId);
2036
- }
2037
- #setProperties(instanceId, props) {
2038
- const instance = this.#requireInstance(instanceId);
2039
- if (!instance) return;
2040
- instance.props = props;
2041
- this.#fire("widget/render-failed", widgetSetPropertiesMethod, [instanceId, props], instanceId);
2042
- }
2043
- /**
2044
- * Hands one instance's binding map to the guest.
2045
- *
2046
- * Only a guest with the direct device channel needs it: that guest then routes publishes to the
2047
- * device and device publishes back to the instance. A guest without one keeps the host as its only
2048
- * router, so the call is skipped rather than sent into a runtime that ignores it.
2049
- */
2050
- #setBindings(instanceId, bindings) {
2051
- const instance = this.#instances.get(instanceId);
2052
- if (instance === void 0) return;
2053
- instance.bindings = bindings;
2054
- if (!this.#directDevice) return;
2055
- this.#fire("widget/deliver-failed", widgetSetBindingsMethod, [instanceId, bindings], instanceId);
2056
- }
2057
- #requireInstance(instanceId) {
2058
- const instance = this.#instances.get(instanceId);
2059
- if (!instance) this.#report("widget/instance-not-found", `Widget instance "${instanceId}" is not mounted.`, { instanceId });
2060
- return instance;
2061
- }
2062
- /** True while `record` is still the live record for this id in an undisposed host. */
2063
- #owns(instanceId, record) {
2064
- return !this.#disposed && this.#instances.get(instanceId) === record;
2065
- }
2066
- /** Aborts a mount attempt whose instance was removed or replaced while it awaited. */
2067
- #requireOwnership(instanceId, record) {
2068
- if (!this.#owns(instanceId, record)) throw new WidgetMountCancelledError(instanceId);
2069
- }
2070
- /** Drops this attempt's reservation and layer; a newer record for the same id is left alone. */
2071
- #forget(instanceId, record) {
2072
- if (this.#instances.get(instanceId) !== record) {
2073
- if (record.audioSession !== void 0) this.#audio?.closeSession(instanceId, record.audioSession);
2074
- return;
2075
- }
2076
- this.#instances.delete(instanceId);
2077
- this.#store.remove(instanceId);
2078
- this.#audio?.close(instanceId);
2079
- }
2080
- /**
2081
- * Asks the guest to release its sessions.
2082
- *
2083
- * The guest keeps its evaluated modules: a reset rebuilds instances, so module-level state is out
2084
- * of scope by contract and the factories stay warm. A host without a sandbox has nothing to
2085
- * reset: no instance ever mounted, so the following sync pass simply mounts into a fresh runtime.
2086
- * Failures are reported, never thrown: the remount below resumes from whatever state the guest is
2087
- * in.
2088
- */
2089
- async #resetGuestRuntime() {
2090
- if (!this.#sandbox && !this.#starting) return;
2091
- try {
2092
- const sandbox = await this.#ensureSandbox();
2093
- if (this.#disposed) return;
2094
- await sandbox.call(widgetResetRuntimeMethod);
2095
- } catch (error) {
2096
- if (this.#disposed || error instanceof WidgetRuntimeError) return;
2097
- if (this.#isTerminated()) {
2098
- this.#failRuntime("The widget sandbox terminated during reset.");
2099
- return;
2100
- }
2101
- this.#report("widget/runtime-failed", `The widget runtime could not be reset: ${describeError(error)}`);
2102
- }
2103
- }
2104
- #ensureSandbox() {
2105
- if (this.#disposed) return Promise.reject(new WidgetRuntimeError("Widget host is disposed"));
2106
- const existing = this.#sandbox;
2107
- if (existing) {
2108
- if (existing.state === "terminated") return Promise.reject(this.#failRuntime("The widget sandbox terminated unexpectedly."));
2109
- return Promise.resolve(existing);
2110
- }
2111
- if (!this.#starting) {
2112
- const devicePort = this.#devicePort;
2113
- this.#devicePort = void 0;
2114
- const pending = this.#createSandbox({
2115
- ...this.#container === void 0 ? {} : { container: this.#container },
2116
- ...this.#fs === void 0 ? {} : { fs: this.#fs },
2117
- ...devicePort === void 0 ? {} : { devicePort }
2118
- }).catch((error) => {
2119
- throw this.#failRuntime(`The widget sandbox failed to start: ${describeError(error)}`, error);
2120
- }).then(async (sandbox) => {
2121
- if (this.#disposed) {
2122
- await terminate(sandbox);
2123
- throw new WidgetRuntimeError("Widget host is disposed");
2124
- }
2125
- this.#sandbox = sandbox;
2126
- this.#directDevice = sandbox.directDevice === true;
2127
- this.#attach(sandbox);
2128
- return sandbox;
2129
- });
2130
- this.#starting = pending;
2131
- const settle = () => {
2132
- if (this.#starting === pending) this.#starting = void 0;
2133
- };
2134
- pending.then(settle, settle);
2135
- }
2136
- return this.#starting;
2137
- }
2138
- /**
2139
- * Reads every asset reference found in the merged props.
2140
- *
2141
- * RFC 0018 step 4: widget property resources resolve against the canvas document URI, so a host
2142
- * without a `WidgetAssetProvider` reads them through `fs` (a `data:` reference is decoded
2143
- * locally). Failures are reported and skipped: a missing image must not stop the mount.
2144
- */
2145
- async #prefetchAssets(instanceId, ref, props) {
2146
- const source = this.#assets;
2147
- const fs = this.#fs;
2148
- const baseUri = this.#documentUri;
2149
- let read;
2150
- if (source !== void 0) read = (assetRef) => source.resolve(assetRef);
2151
- else if (fs !== void 0 && baseUri !== void 0) read = (assetRef) => readHostAsset(fs, baseUri, assetRef);
2152
- else return;
2153
- const refs = collectAssetRefs(props);
2154
- const entries = await Promise.all([...refs.values()].map(async (assetRef) => {
2155
- try {
2156
- const bytes = await read(assetRef);
2157
- if (!(bytes instanceof Uint8Array)) throw new TypeError("WidgetAssetProvider.resolve() must resolve to a Uint8Array");
2158
- return [assetRef.src, bytes];
2159
- } catch (error) {
2160
- this.#report("widget/asset-failed", `Widget asset "${assetRef.src}" for "${ref}" could not be read: ${describeError(error)}`, {
2161
- instanceId,
2162
- widget: ref
2163
- });
2164
- return;
2165
- }
2166
- }));
2167
- return Object.fromEntries(entries.filter((entry) => entry !== void 0));
2168
- }
2169
- #attach(sandbox) {
2170
- this.#detachers.push(sandbox.on(widgetFrameEvent, (payload) => this.#onFrame(payload)), sandbox.on(widgetPublishEvent, (payload) => this.#onPublishMessage(payload)), sandbox.on(widgetErrorEvent, (payload) => this.#onErrorMessage(payload)), sandbox.on(widgetAssetFailedEvent, (payload) => this.#onAssetFailedMessage(payload)));
2171
- this.#flushAudioPort();
2172
- this.#flushAudioState();
2173
- }
2174
- #emitAudioPort(port) {
2175
- this.#pendingAudioPort = port;
2176
- this.#flushAudioPort();
2177
- }
2178
- /** Drops a port nobody received; the host owns it until it is transferred. */
2179
- #releaseAudioPort() {
2180
- const port = this.#pendingAudioPort;
2181
- this.#pendingAudioPort = void 0;
2182
- try {
2183
- port?.close();
2184
- } catch {}
2185
- }
2186
- /** Transfers the direct worker ↔ worklet port; skipped until a sandbox can receive it. */
2187
- #flushAudioPort() {
2188
- const port = this.#pendingAudioPort;
2189
- const sandbox = this.#sandbox;
2190
- if (port === void 0 || sandbox === void 0) return;
2191
- this.#pendingAudioPort = void 0;
2192
- if (sandbox.audio === void 0) {
2193
- try {
2194
- port.close();
2195
- } catch {}
2196
- return;
2197
- }
2198
- try {
2199
- sandbox.audio.attachPort(port);
2200
- } catch {}
2201
- }
2202
- #emitAudioState(state) {
2203
- if (this.#lastAudioState === state) return;
2204
- this.#lastAudioState = state;
2205
- this.#flushAudioState();
2206
- }
2207
- /** Pushes the latest availability; a mounted instance already received it in its mount request. */
2208
- #flushAudioState() {
2209
- const state = this.#lastAudioState;
2210
- const sandbox = this.#sandbox;
2211
- if (state === void 0 || sandbox === void 0) return;
2212
- try {
2213
- sandbox.audio?.setState(state);
2214
- } catch {}
2215
- }
2216
- #detach() {
2217
- for (const detach of this.#detachers.splice(0)) try {
2218
- detach();
2219
- } catch {}
2220
- }
2221
- #onFrame(payload) {
2222
- const frame = payload;
2223
- if (!frame || typeof frame !== "object" || typeof frame.instanceId !== "string") return;
2224
- if (!isBitmap(frame.bitmap)) return;
2225
- this.#store.setBitmap(frame.instanceId, frame.bitmap);
2226
- }
2227
- #onPublishMessage(payload) {
2228
- const message = payload;
2229
- if (!message || typeof message !== "object") return;
2230
- if (typeof message.instanceId !== "string" || typeof message.port !== "string") return;
2231
- const publish = {
2232
- instanceId: message.instanceId,
2233
- port: message.port,
2234
- payload: message.payload,
2235
- simTime: typeof message.simTime === "number" && Number.isFinite(message.simTime) ? message.simTime : this.#simTime
2236
- };
2237
- if (message.direct !== true) this.#forwardToDeviceHost(publish);
2238
- this.#onPublish?.(publish);
2239
- }
2240
- /** Sends a widget publish to the endpoint its port is bound to; unbound ports stay host-local. */
2241
- #forwardToDeviceHost(publish) {
2242
- const widget = this.#document.widgets.find((candidate) => candidate.id === publish.instanceId);
2243
- const target = widget?.bindings?.[publish.port];
2244
- if (target === void 0) return;
2245
- this.#deviceHost.deliver(target, publish.payload, publish.simTime).catch((error) => {
2246
- this.#report("widget/deliver-failed", `Publish from "${publish.instanceId}" could not reach ${target.symbol}.${target.port}: ${describeError(error)}`, {
2247
- instanceId: publish.instanceId,
2248
- widget: widget?.widget
2249
- });
2250
- });
2251
- }
2252
- /** Fans a device publish out to every widget port bound to its endpoint. */
2253
- #onSimulationPublish(publish) {
2254
- if (this.#disposed) return;
2255
- const { target } = publish;
2256
- this.#lastPublished.set(targetKey(target), publish);
2257
- if (this.#directDevice) return;
2258
- for (const widget of this.#document.widgets) {
2259
- const bindings = widget.bindings;
2260
- if (bindings === void 0) continue;
2261
- for (const port of Object.keys(bindings)) {
2262
- const bound = bindings[port];
2263
- if (bound === void 0 || bound.symbol !== target.symbol || bound.port !== target.port) continue;
2264
- this.deliver(widget.id, port, publish.payload, publish.simTime);
2265
- }
2266
- }
2267
- }
2268
- /**
2269
- * Seeds one freshly mounted instance with the values its endpoints already carry.
2270
- *
2271
- * `deliver` only forwards what the simulation publishes, and a level topic publishes on change
2272
- * only, so without this a widget mounted mid-run would wait for the next change to show anything.
2273
- */
2274
- #replayPublished(widget) {
2275
- for (const [port, target] of Object.entries(widget.bindings ?? {})) {
2276
- const publish = this.#lastPublished.get(targetKey(target));
2277
- if (publish === void 0) continue;
2278
- this.deliver(widget.id, port, publish.payload, publish.simTime);
2279
- }
2280
- }
2281
- #onAssetFailedMessage(payload) {
2282
- const message = payload;
2283
- if (!message || typeof message !== "object") return;
2284
- if (typeof message.instanceId !== "string") return;
2285
- const src = typeof message.src === "string" ? message.src : "unknown";
2286
- const name = message.error?.name ?? "Error";
2287
- const text = message.error?.message ?? "Unknown asset failure";
2288
- this.#report("widget/asset-failed", `Widget "${message.instanceId}" could not read asset "${src}": ${name}: ${text}`, {
2289
- instanceId: message.instanceId,
2290
- widget: this.#instances.get(message.instanceId)?.widget
2291
- });
2292
- }
2293
- #onErrorMessage(payload) {
2294
- const message = payload;
2295
- if (!message || typeof message !== "object") return;
2296
- if (typeof message.instanceId !== "string") return;
2297
- if (message.phase !== "render" && message.phase !== "deliver") return;
2298
- const code = message.phase === "render" ? "widget/render-failed" : "widget/deliver-failed";
2299
- const name = message.error?.name ?? "Error";
2300
- const text = message.error?.message ?? "Unknown widget failure";
2301
- this.#report(code, `Widget "${message.instanceId}" failed during ${message.phase}: ${name}: ${text}`, {
2302
- instanceId: message.instanceId,
2303
- widget: this.#instances.get(message.instanceId)?.widget
2304
- });
2305
- }
2306
- #fire(code, method, args, instanceId) {
2307
- if (this.#disposed) return;
2308
- if (!this.#sandbox && !this.#starting) return;
2309
- this.#ensureSandbox().then((sandbox) => sandbox.call(method, ...args)).catch((error) => {
2310
- if (this.#disposed || error instanceof WidgetRuntimeError) return;
2311
- if (this.#isTerminated()) {
2312
- this.#failRuntime("The widget sandbox terminated unexpectedly.");
2313
- return;
2314
- }
2315
- if (code === void 0) return;
2316
- this.#report(code, `Widget call "${method}" failed for "${instanceId}": ${describeError(error)}`, {
2317
- instanceId,
2318
- widget: this.#instances.get(instanceId)?.widget
2319
- });
2320
- });
2321
- }
2322
- #isTerminated() {
2323
- return this.#sandbox?.state === "terminated";
2324
- }
2325
- /**
2326
- * Starts the frame clock. RFC 0018 gives the host the clock, so a loaded document advances on its
2327
- * own; a pause or a disposed host keeps it stopped.
2328
- */
2329
- #startClock() {
2330
- if (this.#disposed || this.#paused || this.#mode !== "simulation") return;
2331
- this.#scheduleFrame();
2332
- }
2333
- #stopClock() {
2334
- const cancel = this.#cancelFrame;
2335
- this.#cancelFrame = void 0;
2336
- cancel?.();
2337
- }
2338
- #scheduleFrame() {
2339
- if (this.#cancelFrame !== void 0 || this.#disposed) return;
2340
- this.#cancelFrame = this.#frameOptions.requestFrame(() => {
2341
- this.#cancelFrame = void 0;
2342
- this.#advanceFrame();
2343
- });
2344
- }
2345
- /** Advances one fixed simulation step, then schedules the next 25 ms clock tick. */
2346
- async #advanceFrame() {
2347
- if (this.#advancing || this.#disposed || this.#paused) return;
2348
- this.#advancing = true;
2349
- try {
2350
- if (this.#disposed || this.#paused) return;
2351
- this.#flushInputs();
2352
- if (this.#mode === "simulation") {
2353
- const report = await this.#deviceHost.tick(this.#frameOptions.stepMs * PS_PER_MS);
2354
- this.#simTime = report.simTime;
2355
- }
2356
- } catch (error) {
2357
- this.#report("widget/runtime-failed", `A simulation step failed: ${describeError(error)}`);
2358
- } finally {
2359
- this.#advancing = false;
2360
- if (!this.#disposed && !this.#paused && this.#mode === "simulation") this.#scheduleFrame();
2361
- }
2362
- }
2363
- /** Dispatches the queued input events at the start of a step. */
2364
- #flushInputs() {
2365
- for (const input of this.#pendingInputs.splice(0)) {
2366
- if (!this.#instances.has(input.instanceId)) continue;
2367
- this.#fire("widget/deliver-failed", widgetPointerMethod, [input.instanceId, input.event], input.instanceId);
2368
- }
2369
- }
2370
- /** Abandons the runtime: layers are cleared and the failure is reported once. */
2371
- #failRuntime(message, cause) {
2372
- this.#sandbox = void 0;
2373
- this.#starting = void 0;
2374
- this.#directDevice = false;
2375
- this.#detach();
2376
- this.#store.clear();
2377
- this.#instances.clear();
2378
- this.#pendingInputs.length = 0;
2379
- this.#releaseAudioPort();
2380
- this.#audio?.reset();
2381
- if (!this.#disposed) this.#report("widget/runtime-failed", message);
2382
- return new WidgetRuntimeError(message, cause === void 0 ? void 0 : { cause });
2383
- }
2384
- async #shutdown() {
2385
- this.#disposed = true;
2386
- this.#stopClock();
2387
- this.#detach();
2388
- this.#unsubscribeDevicePublish?.dispose();
2389
- this.#unsubscribeDevicePublish = void 0;
2390
- this.#pendingInputs.length = 0;
2391
- this.#store.clear();
2392
- this.#instances.clear();
2393
- this.#lastPublished.clear();
2394
- this.#directDevice = false;
2395
- const devicePort = this.#devicePort;
2396
- this.#devicePort = void 0;
2397
- try {
2398
- devicePort?.close();
2399
- } catch {}
2400
- this.#releaseAudioPort();
2401
- this.#audio?.dispose();
2402
- const pending = this.#starting;
2403
- const sandbox = this.#sandbox;
2404
- this.#starting = void 0;
2405
- this.#sandbox = void 0;
2406
- if (sandbox) {
2407
- await terminate(sandbox);
2408
- return;
2409
- }
2410
- if (pending) {
2411
- const late = await pending.catch(() => void 0);
2412
- if (late) await terminate(late);
2413
- }
2414
- }
2415
- /** Diagnostic ids for one instance; audio failures without an instance report no ids. */
2416
- #instanceIds(instanceId) {
2417
- if (instanceId === "") return {};
2418
- const widget = this.#instances.get(instanceId)?.widget;
2419
- return widget === void 0 ? { instanceId } : {
2420
- instanceId,
2421
- widget
2422
- };
2423
- }
2424
- #reportBindingDiagnostic(widget, code, message, pointer) {
2425
- this.#report("widget/binding-failed", message, {
2426
- instanceId: widget.id,
2427
- widget: widget.widget,
2428
- bindingCode: code,
2429
- pointer
2430
- });
2431
- }
2432
- #report(code, message, ids = {}) {
2433
- const diagnostic = {
2434
- code,
2435
- message,
2436
- ...ids.instanceId === void 0 ? {} : { instanceId: ids.instanceId },
2437
- ...ids.widget === void 0 ? {} : { widget: ids.widget },
2438
- ...ids.bindingCode === void 0 ? {} : { bindingCode: ids.bindingCode },
2439
- ...ids.pointer === void 0 ? {} : { pointer: ids.pointer }
2440
- };
2441
- try {
2442
- this.#onDiagnostic?.(diagnostic);
2443
- } catch (error) {
2444
- console.error("[@mica-js/widget] diagnostic handler threw", error);
2445
- }
2446
- }
2447
- #emitDocument(document) {
2448
- for (const listener of [...this.#documentListeners]) try {
2449
- listener(document);
2450
- } catch (error) {
2451
- console.error("[@mica-js/widget] document listener threw", error);
2452
- }
2453
- }
2454
- };
2455
- function placementOf(widget) {
2456
- return {
2457
- x: widget.x,
2458
- y: widget.y,
2459
- width: widget.width,
2460
- height: widget.height,
2461
- rotation: widget.rotation
2462
- };
1544
+ return timePs(value);
1545
+ } catch {
1546
+ return fallback;
1547
+ }
1548
+ }
1549
+ function frameNumber(value, fallback) {
1550
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
1551
+ }
1552
+ function normalizeBindings(value) {
1553
+ if (typeof value !== "object" || value === null) throw new WidgetRuntimeError("widget/invalid-update", "Bindings must be an object.");
1554
+ const bindings = {};
1555
+ for (const [port, target] of Object.entries(value)) {
1556
+ if (typeof target !== "object" || target === null || typeof target.symbol !== "string" || target.symbol === "" || typeof target.port !== "string" || target.port === "") throw new WidgetRuntimeError("widget/invalid-update", `Binding "${port}" needs a nonempty symbol and port.`);
1557
+ bindings[port] = {
1558
+ symbol: target.symbol,
1559
+ port: target.port
1560
+ };
1561
+ }
1562
+ return Object.freeze(bindings);
2463
1563
  }
2464
1564
  function splitRef(ref) {
2465
1565
  const separator = ref.indexOf(":");
@@ -2469,67 +1569,50 @@ function splitRef(ref) {
2469
1569
  widgetId: ref.slice(separator + 1)
2470
1570
  };
2471
1571
  }
2472
- /** Map key of one binding endpoint; the separator cannot occur in a symbol id or a port name. */
2473
- function targetKey(target) {
2474
- return `${target.symbol}\u0000${target.port}`;
2475
- }
2476
- /** Compares two binding maps by endpoint; the document reparses objects it never changed. */
2477
- function sameBindings(left, right) {
2478
- if (left === right) return true;
2479
- const ports = Object.keys(left);
2480
- if (ports.length !== Object.keys(right).length) return false;
2481
- return ports.every((port) => {
2482
- const bound = right[port];
2483
- return bound !== void 0 && targetKey(left[port]) === targetKey(bound);
2484
- });
2485
- }
2486
- function currentDevicePixelRatio() {
2487
- const ratio = globalThis.devicePixelRatio;
2488
- return typeof ratio === "number" && Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
2489
- }
2490
1572
  function isBitmap(value) {
2491
1573
  return typeof value === "object" && value !== null && typeof value.close === "function";
2492
1574
  }
2493
- function describeError(error) {
2494
- if (error instanceof Error && error.message) return error.message;
2495
- return typeof error === "string" ? error : String(error);
2496
- }
2497
- /**
2498
- * Reads one widget property resource (RFC 0018 step 4).
2499
- *
2500
- * `inline` references carry base64 and a `data:` reference carries its own bytes, so neither
2501
- * reaches `fs`; every other reference resolves against the canvas document URI first.
2502
- */
2503
- function readHostAsset(fs, baseUri, ref) {
2504
- if (ref.src.slice(0, 5).toLowerCase() === "data:") return Promise.resolve(decodeDataUri(ref.src));
2505
- if (ref.mode === "inline") return Promise.resolve(decodeBase64Asset(ref.src));
2506
- return fs.read(resolveHostUri(baseUri, ref.src));
1575
+ function isVec2d(value) {
1576
+ if (typeof value !== "object" || value === null) return false;
1577
+ const point = value;
1578
+ return typeof point.x === "number" && typeof point.y === "number";
1579
+ }
1580
+ /** Mirrors the shared value model: a payload must match the declared port type exactly. */
1581
+ function payloadMatches(type, payload) {
1582
+ switch (type) {
1583
+ case "boolean": return typeof payload === "boolean";
1584
+ case "number": return typeof payload === "number";
1585
+ case "string": return typeof payload === "string";
1586
+ case "bytes":
1587
+ case "bytes<rgb565>":
1588
+ case "bytes<segments>": return payload instanceof Uint8Array;
1589
+ case "vec2d": return isVec2d(payload);
1590
+ case "vec3d": return isVec2d(payload) && typeof payload.z === "number";
1591
+ }
2507
1592
  }
2508
- function decodeBase64Asset(text) {
2509
- let binary;
1593
+ function closeBitmap(bitmap) {
1594
+ if (bitmap === void 0) return;
2510
1595
  try {
2511
- binary = atob(text);
2512
- } catch (cause) {
2513
- throw new TypeError("Inline asset src is not valid base64", { cause });
2514
- }
2515
- const bytes = new Uint8Array(binary.length);
2516
- for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
2517
- return bytes;
1596
+ bitmap.close();
1597
+ } catch {}
2518
1598
  }
2519
- async function terminate(sandbox) {
1599
+ function closePort(port) {
2520
1600
  try {
2521
- await sandbox.terminate("widget host disposed");
1601
+ port.close();
2522
1602
  } catch {}
2523
1603
  }
2524
- /** Asks the guest to drop an instance the host has already given up on. */
2525
- async function releaseGuestInstance(sandbox, instanceId) {
1604
+ function describeError(error) {
1605
+ if (error instanceof Error && error.message) return error.message;
1606
+ return typeof error === "string" ? error : String(error);
1607
+ }
1608
+ async function terminateSandbox(sandbox) {
2526
1609
  try {
2527
- await sandbox.call(widgetUnmountMethod, instanceId);
1610
+ await sandbox.terminate("widget runtime disposed");
2528
1611
  } catch {}
2529
1612
  }
2530
1613
  //#endregion
2531
1614
  //#region src/host/sandbox.ts
2532
- /** Adapts a provider-created widget worker to WidgetHost's RPC-facing surface. */
1615
+ /** Adapts a provider-created widget worker to the runtime's RPC-facing surface. */
2533
1616
  async function createWidgetSandboxFromWorker(worker, options) {
2534
1617
  const devicePort = options.devicePort;
2535
1618
  let port;
@@ -2612,13 +1695,11 @@ async function createWidgetSandboxFromWorker(worker, options) {
2612
1695
  * It is a classic script: every dependency is inlined, so the sandbox can run it without a module
2613
1696
  * loader and the package publishes no separate `*.sandbox.js` file.
2614
1697
  */
2615
- var widgetGuestScript = "(function(){function e(e){let t=!1;return{dispose(){t||(t=!0,e())}}}var t=class{#e=/* @__PURE__ */ new Set;#t=!1;event=(t,n,r)=>{if(this.#t)return e(()=>{});let i={listener:t,thisArgs:n};this.#e.add(i);let a=e(()=>{this.#e.delete(i)});return r?.push(a),a};get hasListeners(){return this.#e.size>0}fire(e){if(!this.#t)for(let t of[...this.#e])t.listener.call(t.thisArgs,e)}dispose(){this.#t||(this.#t=!0,this.#e.clear())}};function n(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.kind===`close`)return!0;if(!Number.isSafeInteger(t.id)||t.id<=0)return!1;switch(t.kind){case`call`:case`listen`:return typeof t.service==`string`&&t.service.length>0&&typeof t.member==`string`&&t.member.length>0&&Array.isArray(t.args)&&(t.kind!==`listen`||t.args.length===0);case`unlisten`:return!0;case`result`:return Object.hasOwn(t,`value`);case`error`:case`subscription-error`:return typeof t.name==`string`&&typeof t.message==`string`;case`event`:return Array.isArray(t.args);default:return!1}}function r(e,t){return Object.assign(Error(t),{name:e})}function i(e,t){if([`constructor`,`__proto__`,`prototype`,`then`].includes(t))throw r(`MethodNotFound`,`Method is not exposed: ${t}`);for(let n=e;n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(e){if(typeof e.value==`function`)return e.value;break}}throw r(`MethodNotFound`,`Method is not callable: ${t}`)}function a(a,l={}){let u=l,d=c(u.timeoutMs??0),f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=new t,_=new t,v=0,y=0,b=!1;function x(e){let t=o(e);try{u.onError?.(t)}catch{}g.fire(t)}function S(){if(b)throw r(`RpcDisconnectedError`,`RPC endpoint is closed`)}function C(){if(v===2**53-1)throw RangeError(`RPC request IDs exhausted`);return++v}function w(e,t){S(),a.postMessage(e,t?[...t]:void 0)}function T(e){let t=p.get(e);return p.delete(e),t?.timer!==void 0&&clearTimeout(t.timer),t}function E(e,t,n){return new Promise((i,a)=>{let s=t>0?setTimeout(()=>{T(e.id)?.reject(r(`RpcTimeoutError`,`RPC ${e.service}.${e.member} timed out`))},t):void 0;p.set(e.id,{resolve:i,reject:a,timer:s});try{w(e,n)}catch(t){T(e.id)?.reject(o(t))}})}function D(e){let t=h.get(e);h.delete(e);try{t?.stop?.()}catch(e){x(e)}}function O(e,t,n){if(b)return;let r=o(n);try{w({kind:e,id:t,name:r.name,message:r.message})}catch(e){x(e),A()}}function k(){if(!b){b=!0,a.removeEventListener(`message`,M),a.removeEventListener(`close`,k),a.removeEventListener(`messageerror`,A);for(let e of p.keys())T(e)?.reject(r(`RpcDisconnectedError`,`RPC endpoint is closed`));m.clear();for(let e of h.keys())D(e);f.clear(),_.fire(void 0),_.dispose(),g.dispose()}}function A(){if(!b){try{w({kind:`close`})}catch(e){x(e)}k()}}async function j(e){try{let t=f.get(e.service);if(!t)throw r(`ServiceNotFound`,`Unknown service: ${e.service}`);let n=t.implementation,a=i(n,e.member);if(e.kind===`listen`){if(!/^onDid[A-Z]/.test(e.member))throw r(`InvalidSubscription`,`Event members must start with onDid`);let i={registration:t,stop:void 0};h.set(e.id,i);let o=a.call(n,(...n)=>{if(!(b||h.get(e.id)!==i))try{w({kind:`event`,id:e.id,args:n},t.options.transfer?.(e.member,n))}catch(t){D(e.id),O(`subscription-error`,e.id,t)}});if(typeof o!=`function`)throw r(`InvalidSubscription`,`Event registration must return an unsubscribe function`);i.stop=o,h.get(e.id)!==i&&i.stop(),b||w({kind:`result`,id:e.id,value:void 0})}else{if(/^onDid[A-Z]/.test(e.member))throw r(`InvalidCall`,`Event members require a subscription`);let i=await a.apply(n,e.args);b||w({kind:`result`,id:e.id,value:i},t.options.transfer?.(e.member,i))}}catch(t){e.kind===`listen`&&D(e.id),O(`error`,e.id,t)}}function M(e){let t=e.data;if(!n(t))x(r(`RpcProtocolError`,`Malformed RPC message`));else switch(t.kind){case`call`:case`listen`:if(t.id<=y){x(r(`RpcProtocolError`,`Request IDs must increase`));return}y=t.id,j(t);break;case`unlisten`:D(t.id);break;case`result`:T(t.id)?.resolve(t.value);break;case`error`:T(t.id)?.reject(r(t.name,t.message));break;case`subscription-error`:{let e=r(t.name,t.message),n=m.delete(t.id),i=T(t.id);i?i.reject(e):n&&x(e);break}case`event`:try{m.get(t.id)?.(...t.args)}catch(e){x(e)}break;case`close`:k()}}return a.addEventListener(`message`,M),a.addEventListener(`close`,k),a.addEventListener(`messageerror`,A),a.start?.(),{register(t,n,i={}){S();let a=s(t);if(typeof n!=`object`||!n)throw TypeError(`RPC services must be objects`);if(f.has(a))throw Error(`Service already registered: ${a}`);let o={implementation:n,options:i};return f.set(a,o),e(()=>{if(f.get(a)===o){f.delete(a);for(let[e,t]of h)t.registration===o&&(D(e),O(`subscription-error`,e,r(`ServiceUnregistered`,`Service unregistered: ${a}`)))}})},getProxy(t,n={}){let r=s(t),i=c(n.timeoutMs??d),a=/* @__PURE__ */ new Map;return new Proxy(Object.create(null),{get(t,o){if(typeof o==`string`&&o!==`then`)return a.has(o)||a.set(o,/^onDid[A-Z]/.test(o)?t=>{if(S(),typeof t!=`function`)throw TypeError(`Expected an event listener`);let n=C();m.set(n,t),E({kind:`listen`,id:n,service:r,member:o,args:[]},i).catch(e=>{if(m.delete(n),!b)try{w({kind:`unlisten`,id:n})}catch(e){x(e)}x(e)});let a=e(()=>{if(m.delete(n)&&(T(n)?.resolve(void 0),!b))try{w({kind:`unlisten`,id:n})}catch(e){x(e)}});return()=>a.dispose()}:async(...e)=>(S(),E({kind:`call`,id:C(),service:r,member:o,args:e},i,n.transfer?.(o,e)))),a.get(o)}})},onDidError:(e,t,n)=>g.event(n=>{try{e.call(t,n)}catch{}},void 0,n),onDidClose:(t,n,r)=>b?(t.call(n,void 0),e(()=>{})):_.event(e=>{try{t.call(n,e)}catch(e){x(e)}},void 0,r),dispose:A}}function o(e){return e instanceof Error?e:Error(String(e))}function s(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}function c(e){if(!Number.isSafeInteger(e)||e<0||e>2147483647)throw RangeError(`RPC timeout must be an integer between 0 and 2147483647`);return e}function l(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}let u=l(`logger`),d=l(`audio-worklet`);l(`audio-control`);let f=l(`audio-guest`),p=Object.freeze({}),m=[`sine`,`square`,`triangle`,`sawtooth`],h=[`s16`,`f32`],g={min:8e3,max:96e3},_={min:50,max:2e3},v={min:0,max:1},y={min:0,max:24e3},b={min:0,max:1e4};function x(e,t,n){if(e===void 0)return p;if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${n} must be a plain object`);let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)throw TypeError(`${n} must be a plain object`);let i=e,a=new Set(t);for(let e of Object.keys(i)){if(!a.has(e))throw TypeError(`${n} does not accept the option \"${e}\"`);if(i[e]===void 0)throw TypeError(`${n}.${e} must not be undefined`)}return i}function S(e,t,n){if(e===void 0){if(n===void 0)throw TypeError(`${t} is required`);return n}if(typeof e!=`number`)throw TypeError(`${t} must be a number`);if(!Number.isFinite(e))throw RangeError(`${t} must be a finite number`);return e}function C(e,t,n){if(t.integer===!0&&!Number.isInteger(e))throw RangeError(`${n} must be an integer`);if((t.exclusiveMin===!0?e<=t.min:e<t.min)||e>t.max){let e=t.exclusiveMin===!0?`(${t.min}, ${t.max}]`:`[${t.min}, ${t.max}]`;throw RangeError(`${n} must be in ${e}`)}return e}function w(e,t,n,r,i){return C(i===void 0?S(e[t],`${n}.${t}`):S(e[t],`${n}.${t}`,i),r,`${n}.${t}`)}function T(e,t,n,r){if(e[t]!==void 0)return w(e,t,n,r)}function E(e,t,n,r,i){let a=e[t];if(a===void 0)return i;if(!n.includes(a))throw RangeError(`${r}.${t} must be one of ${n.join(`, `)}`);return a}function D(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function`)}let O=[`unavailable`,`suspended`,`running`],k=[`buffering`,`playing`,`ended`,`closed`],A=[`finished`,`stopped`,`dropped`,`error`,`unavailable`,`disposed`];function j(){let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}}function M(e){let t=e.maxVoices??8,n=e.maxStreams??4,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s,c,l=()=>{},u=new Promise(e=>{l=e}),f=`unavailable`,p=!1,S=0,C=0;function M(t,n){try{e.onListenerError?.(t,n)}catch{}}function P(){return u.then(()=>p?void 0:c)}function F(e){let t={instanceId:e,session:void 0,state:f,stateListeners:/* @__PURE__ */ new Set,voices:/* @__PURE__ */ new Map,streams:/* @__PURE__ */ new Map,api:void 0};return t.api=q(t),t}function I(e){let t=r.get(e);return t||(t=F(e),r.set(e,t)),t}function L(e,t){e.settled||(e.settled=!0,i.delete(e.id),r.get(e.instanceId)?.voices.delete(e.id),e.resolve({reason:t}))}function R(e,t){e.settled||(e.closed=!0,e.state=t===`finished`?`ended`:`closed`,o.delete(e.id),r.get(e.instanceId)?.streams.delete(e.id),V(e),e.settled=!0,e.resolve({reason:t}))}function z(e){return Math.max(0,e.writtenFrames+e.pendingFrames-e.consumedFrames)}function B(e){return{state:e.state,underruns:e.underruns,dropped:e.dropped,bufferedFrames:z(e),capacityFrames:e.capacityFrames}}function V(e){if(e.statusListeners.size===0)return;let t=B(e);for(let n of[...e.statusListeners])try{n(t)}catch(t){M(e.instanceId,t)}}function H(e){for(let t of[...e.drainListeners])try{t()}catch(t){M(e.instanceId,t)}}function U(e){if(e.closed)return;let t=e.capacityFrames/2;e.drainNotified?z(e)>t&&(e.drainNotified=!1):z(e)>t||(e.drainNotified=!0,H(e))}function W(e){if(f!==e){f=e;for(let t of r.values())if(t.state!==e){t.state=e;for(let n of[...t.stateListeners])try{n(e)}catch(e){M(t.instanceId,e)}}}}function G(e,n){S+=1;let{promise:r,resolve:a}=j(),o={id:`t${S}`,instanceId:e.instanceId,dead:n,settled:!1,ended:r,resolve:a};if(e.voices.size>=t){let t=e.voices.values().next().value;t!==void 0&&L(t,`dropped`)}return e.voices.set(o.id,o),i.set(o.id,o),o}function K(e){return{id:e.id,ended:e.ended,stop(){if(!e.settled){if(!e.dead){let t=r.get(e.instanceId)?.session;t!==void 0&&P().then(n=>n?.stopTone(t,e.id,{fadeMs:0})).catch(()=>void 0)}L(e,`stopped`)}}}}function q(e){return{get state(){return e.state},onStateChange(t){return D(t,`api.audio.onStateChange(listener)`),e.stateListeners.add(t),()=>{e.stateListeners.delete(t)}},tone(t){let n=x(t,[`type`,`frequency`,`volume`],`options`),r=E(n,`type`,m,`options`,`sine`),i=w(n,`frequency`,`options`,{...y,exclusiveMin:!0}),a=w(n,`volume`,`options`,v,1),o=e.session,s=G(e,e.state===`unavailable`||o===void 0);return!s.dead&&o!==void 0&&P().then(e=>e?.createTone(o,{voiceId:s.id,type:r,frequency:i,volume:a})).catch(()=>void 0),Object.assign(K(s),{set(e,t){let n=x(e,[`volume`,`frequency`],`options`),r=w(x(t,[`rampMs`],`options`),`rampMs`,`options`,b,0),i=T(n,`volume`,`options`,v),a=T(n,`frequency`,`options`,{...y,exclusiveMin:!0});s.settled||s.dead||o===void 0||P().then(e=>e?.setTone(o,s.id,{rampMs:r,...i===void 0?{}:{volume:i},...a===void 0?{}:{frequency:a}})).catch(()=>void 0)}})},createStream(t){let r=x(t,[`sampleRate`,`channels`,`format`,`bufferMs`,`startMs`,`volume`],`options`),i=w(r,`sampleRate`,`options`,{...g,integer:!0}),a=E(r,`channels`,[1,2],`options`,1),s=E(r,`format`,h,`options`,`f32`),c=w(r,`bufferMs`,`options`,_,500),l=w(r,`startMs`,`options`,{min:0,max:c},50),u=w(r,`volume`,`options`,v,1),d=Math.max(1,Math.ceil(c*i/1e3)),f=Math.min(d,Math.max(0,Math.ceil(l*i/1e3)));C+=1;let p=e.streams.size>=n,m=e.state===`unavailable`||e.session===void 0,{promise:y,resolve:b}=j(),S={id:`s${C}`,instanceId:e.instanceId,session:e.session,sampleRate:i,channels:a,format:s,capacityFrames:d,startFrames:f,volume:u,unavailable:m,writtenFrames:0,pendingFrames:0,consumedFrames:0,underruns:0,dropped:0,state:p?`closed`:`buffering`,drainNotified:!1,endRequested:!1,closed:p,settled:p,ended:y,resolve:b,statusListeners:/* @__PURE__ */ new Set,drainListeners:/* @__PURE__ */ new Set};if(p)b({reason:`stopped`});else if(e.streams.set(S.id,S),o.set(S.id,S),!m&&e.session!==void 0){let t=e.session;P().then(e=>e?.createStream(t,{streamId:S.id,sampleRate:i,channels:a,format:s,capacityFrames:d,startFrames:f,volume:u})).then(e=>{e?.accepted===!1&&R(S,`stopped`)}).catch(()=>void 0)}return J(S)}}}function J(e){return{id:e.id,sampleRate:e.sampleRate,channels:e.channels,format:e.format,capacityFrames:e.capacityFrames,startFrames:e.startFrames,volume:e.volume,get bufferedFrames(){return z(e)},get underruns(){return e.underruns},get dropped(){return e.dropped},get state(){return e.state},ended:e.ended,write(t){if(e.closed)return Promise.resolve(!1);let n=e.format===`s16`?Int16Array:Float32Array;if(!(t instanceof n))throw TypeError(`api.audio stream.write expects a ${n.name} for format \"${e.format}\"`);let r=t.length;if(r===0)throw RangeError(`api.audio stream.write expects at least one sample`);if(r%e.channels!==0)throw RangeError(`api.audio stream.write expects a whole number of ${e.channels}-channel frames`);let i=r/e.channels;if(i>e.capacityFrames)throw RangeError(`api.audio stream.write accepts at most ${e.capacityFrames} frames per call`);if(e.unavailable)return Promise.resolve(!1);if(z(e)+i>e.capacityFrames)return e.dropped+=1,V(e),Promise.resolve(!1);let a=e.format===`s16`?new Int16Array(t):new Float32Array(t),o=e.session??``;return e.pendingFrames+=i,P().then(async t=>{if(t===void 0||e.closed)return e.pendingFrames-=i,!1;try{let n=await t.writeStream(o,e.id,a);return e.pendingFrames-=i,n?e.writtenFrames+=i:e.dropped+=1,V(e),U(e),n}catch{return e.pendingFrames-=i,!1}})},clear(){if(!e.closed){if(e.consumedFrames=e.writtenFrames,!e.unavailable&&e.session!==void 0){let t=e.session;P().then(n=>n?.clearStream(t,e.id)).catch(()=>void 0)}V(e),U(e)}},end(){if(e.closed||e.endRequested)return;if(e.endRequested=!0,e.unavailable||e.session===void 0){R(e,`finished`);return}let t=e.session;P().then(n=>n?.endStream(t,e.id)).catch(()=>void 0)},close(){if(!e.settled){if(!e.closed&&!e.unavailable&&e.session!==void 0){let t=e.session;P().then(n=>n?.closeStream(t,e.id)).catch(()=>void 0)}R(e,`stopped`)}},onDrain(t){return D(t,`api.audio stream.onDrain(listener)`),e.drainListeners.add(t),()=>{e.drainListeners.delete(t)}},onStatus(t){return D(t,`api.audio stream.onStatus(listener)`),e.statusListeners.add(t),()=>{e.statusListeners.delete(t)}}}}function Y(e){if(typeof e!=`object`||!e||typeof e.streamId!=`string`)return;let t=o.get(e.streamId);t&&(typeof e.consumedFrames==`number`&&Number.isFinite(e.consumedFrames)&&(t.consumedFrames=Math.max(t.consumedFrames,Math.floor(e.consumedFrames))),typeof e.underruns==`number`&&Number.isFinite(e.underruns)&&(t.underruns=Math.max(0,Math.floor(e.underruns))),!t.closed&&k.includes(e.state)&&(t.state=e.state),V(t),U(t))}function X(e){if(typeof e!=`object`||!e||typeof e.id!=`string`)return;let t=A.includes(e.reason)?e.reason:`stopped`;if(e.target===`tone`){let n=i.get(e.id);n&&L(n,t);return}let n=o.get(e.id);n&&R(n,t)}function Z(e){let t=r.get(e);if(t){r.delete(e);for(let e of t.voices.values())L(e,`disposed`);t.voices.clear();for(let e of[...t.streams.values()])R(e,`disposed`);t.streams.clear(),t.stateListeners.clear()}}return{get state(){return f},api(e){return I(e).api},open(e,t){let n=I(e);n.session=t?.session,t!==void 0&&(n.state=t.state,f=t.state)},setState(e){O.includes(e)&&W(e)},attachPort(e){if(p||s!==void 0)return;let t=a(e);s=t,c=t.getProxy(d,{transfer:(e,t)=>e===`writeStream`&&N(t[2])?[t[2].buffer]:[]}),c.onDidProgress(e=>Y(e)),c.onDidEnded(e=>X(e)),l()},release:Z,dispose(){if(!p){for(let e of[...r.keys()])Z(e);p=!0,l(),s?.dispose(),s=void 0,c=void 0,i.clear(),o.clear()}}}}function N(e){return e instanceof Int16Array||e instanceof Float32Array}let P=l(`guest`),F=l(`guest-control`),I=l(`host-control`);l(`host-capabilities`);let L=l(`guest`);function R(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function z(e){if(Array.isArray(e))return Object.freeze(e.map(e=>z(e)));if(R(e)){let t=[];for(let n of Object.keys(e))t.push([n,z(e[n])]);return Object.freeze(Object.fromEntries(t))}return e}function B(e,t){let n=/* @__PURE__ */ new Map;for(let t of Object.keys(e??{})){let r=e?.[t];r&&Object.prototype.hasOwnProperty.call(r,`default`)&&n.set(t,z(r.default))}for(let e of Object.keys(t??{}))n.set(e,t?.[e]);return Object.freeze(Object.fromEntries(n))}function V(e,t={}){let n=t.createEndpoint?.(e)??a(e);n.getProxy(u).write({level:`debug`,scope:`widget-runtime`,message:`guest-started`,data:[]}).catch(()=>void 0);let r=/* @__PURE__ */ new Map,i=t.ports?.[0],o=i===void 0?void 0:a(i),s=o?.getProxy(L),c=(e,t)=>{for(let n of[...r.get(e)??[]])try{n(t)}catch{}},l=n.getProxy(I,{transfer:(e,t)=>e===`event`&&Array.isArray(t[2])?[...t[2]]:[]}),d=!1,p=H({emit(e,t,n){if(d)throw Error(`The widget sandbox is gone`);l.event(e,t,n).catch(()=>void 0)},on(e,t){let n=r.get(e);return n||r.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)}},{...t,...s===void 0?{}:{device:s}}),m=()=>{if(!d){d=!0,r.clear(),p.dispose(),n.dispose(),o?.dispose();try{e.close()}catch{}try{i?.close()}catch{}}};return n.register(P,{load:e=>p.load(e),mount:e=>p.mount(e),unmount:e=>p.unmount(e),resize:(e,t,n,r)=>p.resize(e,t,n,r),\"set-properties\":(e,t)=>p.setProperties(e,t),\"set-bindings\":(e,t)=>p.setBindings(e,t),deliver:(e,t,n,r)=>p.deliver(e,t,n,r),pointer:(e,t)=>p.pointer(e,t),\"reset-runtime\":()=>p.resetRuntime()}),n.register(F,{dispatchEvent:c,terminate:m}),n.register(f,{attachPort:e=>p.attachAudioPort(e),setState:e=>p.setAudioState(e)}),{runtime:p,dispose:m}}function H(e,t={}){let n=t.importModule??te,r=t.device,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Set,l=!1,u=!1,d=M({onListenerError:(e,t)=>f(`deliver`,e,t)});function f(t,n,r){let i={instanceId:n,phase:t,error:{name:Q(r),message:ee(r)}};try{e.emit(`widget:error`,i)}catch{}}function p(e,t,n,r){let i=b(e).subscriptions.get(t);if(!i||i.size===0)return;let a={simTime:r};for(let t of[...i])try{t(n,a)}catch(t){f(`deliver`,e,t)}}function m(e){if(!u)for(let t of[...s.values()])for(let[n,r]of Object.entries(t.bindings))r.symbol===e.target.symbol&&r.port===e.target.port&&p(t.instanceId,n,e.payload,e.simTime)}let h=r?.onDidPublish(m)??(()=>{});function g(e){e.failed||e.disposed||u||(c.add(e),!l&&(l=!0,queueMicrotask(_)))}function _(){l=!1;let e=[...c];c.clear();for(let t of e)v(t)}function v(e){if(e.failed||e.disposed||u)return;let{context:t,canvas:n}=e;typeof t.setTransform==`function`&&(t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,n.width,n.height),t.setTransform(e.dpr,0,0,e.dpr,0,0));let r=e.instance?.render;if(typeof r==`function`)try{r.call(e.instance,t)}catch(t){e.failed=!0,c.delete(e),f(`render`,e.instanceId,t);return}y(e)}function y(t){let n;try{n=t.canvas.transferToImageBitmap()}catch(e){t.failed=!0,f(`render`,t.instanceId,e);return}let r={instanceId:t.instanceId,bitmap:n,width:t.width,height:t.height,dpr:t.dpr};try{e.emit(`widget:frame`,r,[n])}catch{Z(n)}}function b(e){let t=s.get(e);if(!t)throw Error(`Widget instance ${JSON.stringify(e)} is not mounted`);return t}function x(e,t){let n=U(e.width,e.height,e.dpr),r=t?.properties??{};return d.open(e.instanceId,e.audio),{instanceId:e.instanceId,width:K(e.width),height:K(e.height),dpr:q(e.dpr),props:B(r,e.props),properties:r,assets:Y(e.assets),reportedAssets:/* @__PURE__ */ new Set,canvas:n,context:W(n),subscriptions:/* @__PURE__ */ new Map,bindings:{},instance:void 0,failed:!1,disposed:!1}}function S(t,n,r){if(t.disposed||u||t.reportedAssets.has(n))return;t.reportedAssets.add(n);let i={instanceId:t.instanceId,src:n,error:{name:`Error`,message:r}};try{e.emit(`widget:asset-failed`,i)}catch{}}function C(e,t){if(typeof t!=`string`)return Promise.reject(/* @__PURE__ */ TypeError(`Widget asset src must be a string`));let n=e.assets.get(t);if(n!==void 0&&!e.disposed&&!u)return Promise.resolve(new Uint8Array(n));let r=`Widget asset ${JSON.stringify(t)} was not prefetched`;return e.disposed||u||S(e,t,r),Promise.reject(Error(r))}function w(t){return{instanceId:t.instanceId,get width(){return t.width},get height(){return t.height},get props(){return t.props},assets:{readBinary:e=>C(t,e)},audio:d.api(t.instanceId),subscribe(e,n){if(t.disposed||typeof n!=`function`)return()=>{};let r=t.subscriptions.get(e);return r||(r=/* @__PURE__ */ new Set,t.subscriptions.set(e,r)),r.add(n),()=>{t.subscriptions.get(e)?.delete(n)}},publish(n,i,a){if(t.disposed||u)return;let o={instanceId:t.instanceId,port:n,payload:i,simTime:X(a)},s=t.bindings[n],c=s!==void 0&&r!==void 0;s!==void 0&&r!==void 0&&r.deliver(s,i,o.simTime).catch(e=>{f(`deliver`,t.instanceId,e)});try{e.emit(`widget:publish`,c?{...o,direct:c}:o)}catch(e){f(`deliver`,t.instanceId,e)}},invalidate(){g(t)}}}function T(e){e.disposed=!0,c.delete(e),e.subscriptions.clear(),d.release(e.instanceId);let t=e.instance;if(e.instance=void 0,t&&typeof t.dispose==`function`)try{t.dispose()}catch(t){f(`render`,e.instanceId,t)}e.assets.clear(),e.canvas.width=1,e.canvas.height=1}async function E(e,t){let r=await n(t),i=r&&typeof r==`object`?r.default:void 0;if(typeof i!=`function`)throw Error(`Widget ${JSON.stringify(e)} must default-export a factory function`);return i}return{async load(e){let t=Array.isArray(e.packages)?e.packages:[],n,r=!1;for(let e of t){let t=e.modules;if(t&&typeof t==`object`)for(let s of Object.keys(t)){let c=t[s];if(!c)continue;let l=`${e.id}:${s}`;if(!i.has(l))try{let e=o.get(l);e||(e=E(l,c.code),o.set(l,e)),i.set(l,await e),a.set(l,c.definition)}catch(e){r||=(n=e,!0)}finally{o.delete(l)}}}if(r)throw n},mount(e){if(u)throw Error(`The widget runtime is disposed`);let{instanceId:t,widget:n}=e;if(s.has(t))throw Error(`Widget instance ${JSON.stringify(t)} is already mounted`);let r=i.get(n);if(!r)throw Error(`Widget ${JSON.stringify(n)} is not loaded`);let o=x(e,a.get(n));s.set(t,o);try{o.instance=G(r(w(o)))}catch(e){throw s.delete(t),T(o),f(`mount`,t,e),e instanceof Error?e:Error(String(e))}c.delete(o),v(o)},unmount(e){let t=s.get(e);t&&(s.delete(e),T(t))},resize(e,t,n,r){let i=b(e);i.width=K(t),i.height=K(n),i.dpr=q(r),i.canvas.width=J(t,i.dpr),i.canvas.height=J(n,i.dpr),c.delete(i),v(i)},setProperties(e,t){let n=b(e);n.props=B(n.properties,t),g(n)},setBindings(e,t){let n=s.get(e);n!==void 0&&(n.bindings=t??{})},deliver(e,t,n,r){p(e,t,n,r)},pointer(e,t){let n=b(e);if(n.failed||n.disposed)return;let r=n.instance?.input;if(typeof r==`function`)try{r.call(n.instance,t)}catch(t){f(`deliver`,e,t)}},resetRuntime(){if(!u){c.clear();for(let e of[...s.values()])s.delete(e.instanceId),T(e);s.clear()}},dispose(){if(!u){u=!0,h(),c.clear();for(let e of[...s.values()])T(e);s.clear(),d.dispose(),i.clear(),a.clear(),o.clear()}},attachAudioPort(e){d.attachPort(e)},setAudioState(e){d.setState(e)}}}function U(e,t,n){return new OffscreenCanvas(J(e,n),J(t,n))}function W(e){let t=e.getContext(`2d`);if(!t)throw Error(`The widget runtime needs a 2D context`);return t}function G(e){return e&&typeof e==`object`?e:{}}function K(e){return Number.isFinite(e)&&e>0?e:0}function q(e){return Number.isFinite(e)&&e>0?e:1}function J(e,t){return Math.max(1,Math.round(K(e)*q(t)))}function Y(e){let t=/* @__PURE__ */ new Map;if(typeof e!=`object`||!e)return t;for(let n of Object.keys(e)){let r=e[n];r instanceof Uint8Array&&t.set(n,new Uint8Array(r))}return t}function X(e){return typeof e==`number`&&Number.isFinite(e)?e:0}function Z(e){try{e.close()}catch{}}function Q(e){return e instanceof Error&&e.name?e.name:`Error`}function ee(e){return e instanceof Error&&e.message?e.message:typeof e==`string`?e:String(e)}function te(e){let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(\n/* @vite-ignore */\nt).finally(()=>URL.revokeObjectURL(t))}let $=!1;self.addEventListener(`message`,e=>{if($)return;let t=e.ports[0];t!==void 0&&($=!0,V(t,{ports:e.ports.slice(1)}))})})();";
1698
+ var widgetGuestScript = "(function(){function e(e,t){if(typeof e!=`number`||!Number.isFinite(e)||!Number.isInteger(e))throw TypeError(`${t}=${String(e)} must be a finite integer number of picoseconds`);if(e<0||e>72e14)throw RangeError(`${t}=${e} must be in [0, 7200000000000000] ps`);return e===0?0:e}function t(t){return e(t,`time`)}function n(e){let t=!1;return{dispose(){t||(t=!0,e())}}}var r=class{#e=/* @__PURE__ */ new Set;#t=!1;event=(e,t,r)=>{if(this.#t)return n(()=>{});let i={listener:e,thisArgs:t};this.#e.add(i);let a=n(()=>{this.#e.delete(i)});return r?.push(a),a};get hasListeners(){return this.#e.size>0}fire(e){if(!this.#t)for(let t of[...this.#e])t.listener.call(t.thisArgs,e)}dispose(){this.#t||(this.#t=!0,this.#e.clear())}};function i(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(t.kind===`close`)return!0;if(!Number.isSafeInteger(t.id)||t.id<=0)return!1;switch(t.kind){case`call`:case`listen`:return typeof t.service==`string`&&t.service.length>0&&typeof t.member==`string`&&t.member.length>0&&Array.isArray(t.args)&&(t.kind!==`listen`||t.args.length===0);case`unlisten`:return!0;case`result`:return Object.hasOwn(t,`value`);case`error`:case`subscription-error`:return typeof t.name==`string`&&typeof t.message==`string`;case`event`:return Array.isArray(t.args);default:return!1}}function a(e,t){return Object.assign(Error(t),{name:e})}function o(e,t){if([`constructor`,`__proto__`,`prototype`,`then`].includes(t))throw a(`MethodNotFound`,`Method is not exposed: ${t}`);for(let n=e;n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){let e=Object.getOwnPropertyDescriptor(n,t);if(e){if(typeof e.value==`function`)return e.value;break}}throw a(`MethodNotFound`,`Method is not callable: ${t}`)}function s(e,t={}){let s=t,d=u(s.timeoutMs??0),f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=new r,_=new r,v=0,y=0,b=!1;function x(e){let t=c(e);try{s.onError?.(t)}catch{}g.fire(t)}function S(){if(b)throw a(`RpcDisconnectedError`,`RPC endpoint is closed`)}function C(){if(v===2**53-1)throw RangeError(`RPC request IDs exhausted`);return++v}function w(t,n){S(),e.postMessage(t,n?[...n]:void 0)}function T(e){let t=p.get(e);return p.delete(e),t?.timer!==void 0&&clearTimeout(t.timer),t}function E(e,t,n){return new Promise((r,i)=>{let o=t>0?setTimeout(()=>{T(e.id)?.reject(a(`RpcTimeoutError`,`RPC ${e.service}.${e.member} timed out`))},t):void 0;p.set(e.id,{resolve:r,reject:i,timer:o});try{w(e,n)}catch(t){T(e.id)?.reject(c(t))}})}function D(e){let t=h.get(e);h.delete(e);try{t?.stop?.()}catch(e){x(e)}}function O(e,t,n){if(b)return;let r=c(n);try{w({kind:e,id:t,name:r.name,message:r.message})}catch(e){x(e),A()}}function k(){if(!b){b=!0,e.removeEventListener(`message`,M),e.removeEventListener(`close`,k),e.removeEventListener(`messageerror`,A);for(let e of p.keys())T(e)?.reject(a(`RpcDisconnectedError`,`RPC endpoint is closed`));m.clear();for(let e of h.keys())D(e);f.clear(),_.fire(void 0),_.dispose(),g.dispose()}}function A(){if(!b){try{w({kind:`close`})}catch(e){x(e)}k()}}async function j(e){try{let t=f.get(e.service);if(!t)throw a(`ServiceNotFound`,`Unknown service: ${e.service}`);let n=t.implementation,r=o(n,e.member);if(e.kind===`listen`){if(!/^onDid[A-Z]/.test(e.member))throw a(`InvalidSubscription`,`Event members must start with onDid`);let i={registration:t,stop:void 0};h.set(e.id,i);let o=r.call(n,(...n)=>{if(!(b||h.get(e.id)!==i))try{w({kind:`event`,id:e.id,args:n},t.options.transfer?.(e.member,n))}catch(t){D(e.id),O(`subscription-error`,e.id,t)}});if(typeof o!=`function`)throw a(`InvalidSubscription`,`Event registration must return an unsubscribe function`);i.stop=o,h.get(e.id)!==i&&i.stop(),b||w({kind:`result`,id:e.id,value:void 0})}else{if(/^onDid[A-Z]/.test(e.member))throw a(`InvalidCall`,`Event members require a subscription`);let i=await r.apply(n,e.args);b||w({kind:`result`,id:e.id,value:i},t.options.transfer?.(e.member,i))}}catch(t){e.kind===`listen`&&D(e.id),O(`error`,e.id,t)}}function M(e){let t=e.data;if(!i(t))x(a(`RpcProtocolError`,`Malformed RPC message`));else switch(t.kind){case`call`:case`listen`:if(t.id<=y){x(a(`RpcProtocolError`,`Request IDs must increase`));return}y=t.id,j(t);break;case`unlisten`:D(t.id);break;case`result`:T(t.id)?.resolve(t.value);break;case`error`:T(t.id)?.reject(a(t.name,t.message));break;case`subscription-error`:{let e=a(t.name,t.message),n=m.delete(t.id),r=T(t.id);r?r.reject(e):n&&x(e);break}case`event`:try{m.get(t.id)?.(...t.args)}catch(e){x(e)}break;case`close`:k()}}return e.addEventListener(`message`,M),e.addEventListener(`close`,k),e.addEventListener(`messageerror`,A),e.start?.(),{register(e,t,r={}){S();let i=l(e);if(typeof t!=`object`||!t)throw TypeError(`RPC services must be objects`);if(f.has(i))throw Error(`Service already registered: ${i}`);let o={implementation:t,options:r};return f.set(i,o),n(()=>{if(f.get(i)===o){f.delete(i);for(let[e,t]of h)t.registration===o&&(D(e),O(`subscription-error`,e,a(`ServiceUnregistered`,`Service unregistered: ${i}`)))}})},getProxy(e,t={}){let r=l(e),i=u(t.timeoutMs??d),a=/* @__PURE__ */ new Map;return new Proxy(Object.create(null),{get(e,o){if(typeof o==`string`&&o!==`then`)return a.has(o)||a.set(o,/^onDid[A-Z]/.test(o)?e=>{if(S(),typeof e!=`function`)throw TypeError(`Expected an event listener`);let t=C();m.set(t,e),E({kind:`listen`,id:t,service:r,member:o,args:[]},i).catch(e=>{if(m.delete(t),!b)try{w({kind:`unlisten`,id:t})}catch(e){x(e)}x(e)});let a=n(()=>{if(m.delete(t)&&(T(t)?.resolve(void 0),!b))try{w({kind:`unlisten`,id:t})}catch(e){x(e)}});return()=>a.dispose()}:async(...e)=>(S(),E({kind:`call`,id:C(),service:r,member:o,args:e},i,t.transfer?.(o,e)))),a.get(o)}})},onDidError:(e,t,n)=>g.event(n=>{try{e.call(t,n)}catch{}},void 0,n),onDidClose:(e,t,r)=>b?(e.call(t,void 0),n(()=>{})):_.event(n=>{try{e.call(t,n)}catch(e){x(e)}},void 0,r),dispose:A}}function c(e){return e instanceof Error?e:Error(String(e))}function l(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}function u(e){if(!Number.isSafeInteger(e)||e<0||e>2147483647)throw RangeError(`RPC timeout must be an integer between 0 and 2147483647`);return e}function d(e){if(typeof e!=`string`||e.length===0)throw TypeError(`RPC service name must be nonempty`);return e}let f=d(`logger`),p=d(`audio-worklet`);d(`audio-control`);let m=d(`audio-guest`),h=Object.freeze({}),g=[`sine`,`square`,`triangle`,`sawtooth`],_=[`s16`,`f32`],v={min:8e3,max:96e3},y={min:50,max:2e3},b={min:0,max:1},x={min:0,max:24e3},S={min:0,max:1e4};function C(e,t,n){if(e===void 0)return h;if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`${n} must be a plain object`);let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)throw TypeError(`${n} must be a plain object`);let i=e,a=new Set(t);for(let e of Object.keys(i)){if(!a.has(e))throw TypeError(`${n} does not accept the option \"${e}\"`);if(i[e]===void 0)throw TypeError(`${n}.${e} must not be undefined`)}return i}function w(e,t,n){if(e===void 0){if(n===void 0)throw TypeError(`${t} is required`);return n}if(typeof e!=`number`)throw TypeError(`${t} must be a number`);if(!Number.isFinite(e))throw RangeError(`${t} must be a finite number`);return e}function T(e,t,n){if(t.integer===!0&&!Number.isInteger(e))throw RangeError(`${n} must be an integer`);if((t.exclusiveMin===!0?e<=t.min:e<t.min)||e>t.max){let e=t.exclusiveMin===!0?`(${t.min}, ${t.max}]`:`[${t.min}, ${t.max}]`;throw RangeError(`${n} must be in ${e}`)}return e}function E(e,t,n,r,i){return T(i===void 0?w(e[t],`${n}.${t}`):w(e[t],`${n}.${t}`,i),r,`${n}.${t}`)}function D(e,t,n,r){if(e[t]!==void 0)return E(e,t,n,r)}function O(e,t,n,r,i){let a=e[t];if(a===void 0)return i;if(!n.includes(a))throw RangeError(`${r}.${t} must be one of ${n.join(`, `)}`);return a}function k(e,t){if(typeof e!=`function`)throw TypeError(`${t} must be a function`)}let A=[`unavailable`,`suspended`,`running`],j=[`buffering`,`playing`,`ended`,`closed`],M=[`finished`,`stopped`,`dropped`,`error`,`unavailable`,`disposed`];function N(){let e=()=>{};return{promise:new Promise(t=>{e=t}),resolve:e}}function P(e){let t=e.maxVoices??8,n=e.maxStreams??4,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o,c,l=()=>{},u=new Promise(e=>{l=e}),d=`unavailable`,f=!1,m=0,h=0;function w(t,n){try{e.onListenerError?.(t,n)}catch{}}function T(){return u.then(()=>f?void 0:c)}function P(e){let t={instanceId:e,session:void 0,state:d,stateListeners:/* @__PURE__ */ new Set,voices:/* @__PURE__ */ new Map,streams:/* @__PURE__ */ new Map,api:void 0};return t.api=q(t),t}function I(e){let t=r.get(e);return t||(t=P(e),r.set(e,t)),t}function L(e,t){e.settled||(e.settled=!0,i.delete(e.id),r.get(e.instanceId)?.voices.delete(e.id),e.resolve({reason:t}))}function R(e,t){e.settled||(e.closed=!0,e.state=t===`finished`?`ended`:`closed`,a.delete(e.id),r.get(e.instanceId)?.streams.delete(e.id),V(e),e.settled=!0,e.resolve({reason:t}))}function z(e){return Math.max(0,e.writtenFrames+e.pendingFrames-e.consumedFrames)}function B(e){return{state:e.state,underruns:e.underruns,dropped:e.dropped,bufferedFrames:z(e),capacityFrames:e.capacityFrames}}function V(e){if(e.statusListeners.size===0)return;let t=B(e);for(let n of[...e.statusListeners])try{n(t)}catch(t){w(e.instanceId,t)}}function H(e){for(let t of[...e.drainListeners])try{t()}catch(t){w(e.instanceId,t)}}function U(e){if(e.closed)return;let t=e.capacityFrames/2;e.drainNotified?z(e)>t&&(e.drainNotified=!1):z(e)>t||(e.drainNotified=!0,H(e))}function W(e){if(d!==e){d=e;for(let t of r.values())if(t.state!==e){t.state=e;for(let n of[...t.stateListeners])try{n(e)}catch(e){w(t.instanceId,e)}}}}function G(e,n){m+=1;let{promise:r,resolve:a}=N(),o={id:`t${m}`,instanceId:e.instanceId,dead:n,settled:!1,ended:r,resolve:a};if(e.voices.size>=t){let t=e.voices.values().next().value;t!==void 0&&L(t,`dropped`)}return e.voices.set(o.id,o),i.set(o.id,o),o}function K(e){return{id:e.id,ended:e.ended,stop(){if(!e.settled){if(!e.dead){let t=r.get(e.instanceId)?.session;t!==void 0&&T().then(n=>n?.stopTone(t,e.id,{fadeMs:0})).catch(()=>void 0)}L(e,`stopped`)}}}}function q(e){return{get state(){return e.state},onStateChange(t){return k(t,`api.audio.onStateChange(listener)`),e.stateListeners.add(t),()=>{e.stateListeners.delete(t)}},tone(t){let n=C(t,[`type`,`frequency`,`volume`],`options`),r=O(n,`type`,g,`options`,`sine`),i=E(n,`frequency`,`options`,{...x,exclusiveMin:!0}),a=E(n,`volume`,`options`,b,1),o=e.session,s=G(e,e.state===`unavailable`||o===void 0);return!s.dead&&o!==void 0&&T().then(e=>e?.createTone(o,{voiceId:s.id,type:r,frequency:i,volume:a})).catch(()=>void 0),Object.assign(K(s),{set(e,t){let n=C(e,[`volume`,`frequency`],`options`),r=E(C(t,[`rampMs`],`options`),`rampMs`,`options`,S,0),i=D(n,`volume`,`options`,b),a=D(n,`frequency`,`options`,{...x,exclusiveMin:!0});s.settled||s.dead||o===void 0||T().then(e=>e?.setTone(o,s.id,{rampMs:r,...i===void 0?{}:{volume:i},...a===void 0?{}:{frequency:a}})).catch(()=>void 0)}})},createStream(t){let r=C(t,[`sampleRate`,`channels`,`format`,`bufferMs`,`startMs`,`volume`],`options`),i=E(r,`sampleRate`,`options`,{...v,integer:!0}),o=O(r,`channels`,[1,2],`options`,1),s=O(r,`format`,_,`options`,`f32`),c=E(r,`bufferMs`,`options`,y,500),l=E(r,`startMs`,`options`,{min:0,max:c},50),u=E(r,`volume`,`options`,b,1),d=Math.max(1,Math.ceil(c*i/1e3)),f=Math.min(d,Math.max(0,Math.ceil(l*i/1e3)));h+=1;let p=e.streams.size>=n,m=e.state===`unavailable`||e.session===void 0,{promise:g,resolve:x}=N(),S={id:`s${h}`,instanceId:e.instanceId,session:e.session,sampleRate:i,channels:o,format:s,capacityFrames:d,startFrames:f,volume:u,unavailable:m,writtenFrames:0,pendingFrames:0,consumedFrames:0,underruns:0,dropped:0,state:p?`closed`:`buffering`,drainNotified:!1,endRequested:!1,closed:p,settled:p,ended:g,resolve:x,statusListeners:/* @__PURE__ */ new Set,drainListeners:/* @__PURE__ */ new Set};if(p)x({reason:`stopped`});else if(e.streams.set(S.id,S),a.set(S.id,S),!m&&e.session!==void 0){let t=e.session;T().then(e=>e?.createStream(t,{streamId:S.id,sampleRate:i,channels:o,format:s,capacityFrames:d,startFrames:f,volume:u})).then(e=>{e?.accepted===!1&&R(S,`stopped`)}).catch(()=>void 0)}return J(S)}}}function J(e){return{id:e.id,sampleRate:e.sampleRate,channels:e.channels,format:e.format,capacityFrames:e.capacityFrames,startFrames:e.startFrames,volume:e.volume,get bufferedFrames(){return z(e)},get underruns(){return e.underruns},get dropped(){return e.dropped},get state(){return e.state},ended:e.ended,write(t){if(e.closed)return Promise.resolve(!1);let n=e.format===`s16`?Int16Array:Float32Array;if(!(t instanceof n))throw TypeError(`api.audio stream.write expects a ${n.name} for format \"${e.format}\"`);let r=t.length;if(r===0)throw RangeError(`api.audio stream.write expects at least one sample`);if(r%e.channels!==0)throw RangeError(`api.audio stream.write expects a whole number of ${e.channels}-channel frames`);let i=r/e.channels;if(i>e.capacityFrames)throw RangeError(`api.audio stream.write accepts at most ${e.capacityFrames} frames per call`);if(e.unavailable)return Promise.resolve(!1);if(z(e)+i>e.capacityFrames)return e.dropped+=1,V(e),Promise.resolve(!1);let a=e.format===`s16`?new Int16Array(t):new Float32Array(t),o=e.session??``;return e.pendingFrames+=i,T().then(async t=>{if(t===void 0||e.closed)return e.pendingFrames-=i,!1;try{let n=await t.writeStream(o,e.id,a);return e.pendingFrames-=i,n?e.writtenFrames+=i:e.dropped+=1,V(e),U(e),n}catch{return e.pendingFrames-=i,!1}})},clear(){if(!e.closed){if(e.consumedFrames=e.writtenFrames,!e.unavailable&&e.session!==void 0){let t=e.session;T().then(n=>n?.clearStream(t,e.id)).catch(()=>void 0)}V(e),U(e)}},end(){if(e.closed||e.endRequested)return;if(e.endRequested=!0,e.unavailable||e.session===void 0){R(e,`finished`);return}let t=e.session;T().then(n=>n?.endStream(t,e.id)).catch(()=>void 0)},close(){if(!e.settled){if(!e.closed&&!e.unavailable&&e.session!==void 0){let t=e.session;T().then(n=>n?.closeStream(t,e.id)).catch(()=>void 0)}R(e,`stopped`)}},onDrain(t){return k(t,`api.audio stream.onDrain(listener)`),e.drainListeners.add(t),()=>{e.drainListeners.delete(t)}},onStatus(t){return k(t,`api.audio stream.onStatus(listener)`),e.statusListeners.add(t),()=>{e.statusListeners.delete(t)}}}}function Y(e){if(typeof e!=`object`||!e||typeof e.streamId!=`string`)return;let t=a.get(e.streamId);t&&(typeof e.consumedFrames==`number`&&Number.isFinite(e.consumedFrames)&&(t.consumedFrames=Math.max(t.consumedFrames,Math.floor(e.consumedFrames))),typeof e.underruns==`number`&&Number.isFinite(e.underruns)&&(t.underruns=Math.max(0,Math.floor(e.underruns))),!t.closed&&j.includes(e.state)&&(t.state=e.state),V(t),U(t))}function X(e){if(typeof e!=`object`||!e||typeof e.id!=`string`)return;let t=M.includes(e.reason)?e.reason:`stopped`;if(e.target===`tone`){let n=i.get(e.id);n&&L(n,t);return}let n=a.get(e.id);n&&R(n,t)}function Z(e){let t=r.get(e);if(t){r.delete(e);for(let e of t.voices.values())L(e,`disposed`);t.voices.clear();for(let e of[...t.streams.values()])R(e,`disposed`);t.streams.clear(),t.stateListeners.clear()}}return{get state(){return d},api(e){return I(e).api},open(e,t){let n=I(e);n.session=t?.session,t!==void 0&&(n.state=t.state,d=t.state)},setState(e){A.includes(e)&&W(e)},attachPort(e){if(f||o!==void 0)return;let t=s(e);o=t,c=t.getProxy(p,{transfer:(e,t)=>e===`writeStream`&&F(t[2])?[t[2].buffer]:[]}),c.onDidProgress(e=>Y(e)),c.onDidEnded(e=>X(e)),l()},release:Z,dispose(){if(!f){for(let e of[...r.keys()])Z(e);f=!0,l(),o?.dispose(),o=void 0,c=void 0,i.clear(),a.clear()}}}}function F(e){return e instanceof Int16Array||e instanceof Float32Array}let I=d(`guest`),L=d(`guest-control`),R=d(`host-control`);d(`host-capabilities`);let z=d(`simulation-runtime`);function B(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function V(e){if(Array.isArray(e))return Object.freeze(e.map(e=>V(e)));if(B(e)){let t=[];for(let n of Object.keys(e))t.push([n,V(e[n])]);return Object.freeze(Object.fromEntries(t))}return e}function H(e,t){let n=/* @__PURE__ */ new Map;for(let t of Object.keys(e??{})){let r=e?.[t];r&&Object.prototype.hasOwnProperty.call(r,`default`)&&n.set(t,V(r.default))}for(let e of Object.keys(t??{}))n.set(e,t?.[e]);return Object.freeze(Object.fromEntries(n))}function U(e,t={}){let n=t.createEndpoint?.(e)??s(e);n.getProxy(f).write({level:`debug`,scope:`widget-runtime`,message:`guest-started`,data:[]}).catch(()=>void 0);let r=/* @__PURE__ */ new Map,i=t.ports?.[0],a=(e,t)=>{for(let n of[...r.get(e)??[]])try{n(t)}catch{}},o=n.getProxy(R,{transfer:(e,t)=>e===`event`&&Array.isArray(t[2])?[...t[2]]:[]}),c=!1,l=W({emit(e,t,n){if(c)throw Error(`The widget sandbox is gone`);o.event(e,t,n).catch(()=>void 0)},on(e,t){let n=r.get(e);return n||r.set(e,n=/* @__PURE__ */ new Set),n.add(t),()=>n.delete(t)}},{...t,...i===void 0?{}:{devicePort:i}}),u=()=>{if(!c){c=!0,r.clear(),l.dispose(),n.dispose();try{e.close()}catch{}try{i?.close()}catch{}}};return n.register(I,{load:e=>l.load(e),mount:async e=>{l.mount(e)},unmount:e=>l.unmount(e),resize:(e,t,n,r)=>l.resize(e,t,n,r),\"set-properties\":(e,t)=>l.setProperties(e,t),\"set-assets\":(e,t)=>l.setAssets(e,t),\"set-bindings\":(e,t)=>l.setBindings(e,t),deliver:(e,t,n,r)=>l.deliver(e,t,n,r),pointer:(e,t)=>l.pointer(e,t),configure:e=>l.configure(e),step:e=>l.step(e),\"reset-runtime\":()=>l.resetRuntime()}),n.register(L,{dispatchEvent:a,terminate:u}),n.register(m,{attachPort:e=>l.attachAudioPort(e),setState:e=>l.setAudioState(e)}),{runtime:l,dispose:u}}function W(e,n={}){let r=n.importModule??re,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Set,u=[],d=/* @__PURE__ */ new Set,f=!1,p=!1,m=n.explicitStepping===!0,h=0,g,_,v,y=()=>{};function b(e){if(g!==void 0)return _===e;let t=n.devicePort;if(t===void 0)return!1;let r=s(t);v=r;let i=r.getProxy(z);return y=i.onDidPublish(T),g=i,_=e,!0}n.device===void 0?n.directTopicService!==void 0&&b(n.directTopicService):(g=n.device,_=`simulation-runtime`,y=n.device.onDidPublish(T));function x(){g===void 0&&n.devicePort!==void 0&&b(n.directTopicService??`simulation-runtime`)}let S=P({onListenerError:(e,t)=>C(`deliver`,e,t)});function C(t,n,r){let i={instanceId:n,phase:t,error:{name:te(r),message:ne(r)}};try{e.emit(`widget:error`,i)}catch{}}function w(e,t,n,r){let i=F(e).subscriptions.get(t);if(!i||i.size===0)return;let a={simTime:r};for(let t of[...i])try{t(n,a)}catch(t){C(`deliver`,e,t)}}function T(e){p||(m?u.push(e):E(e))}function E(e){for(let t of[...c.values()])if(!t.disposed&&c.has(t.instanceId)){for(let[n,r]of Object.entries(t.bindings))if(r.symbol===e.target.symbol&&r.port===e.target.port)try{w(t.instanceId,n,e.payload,e.simTime)}catch(e){C(`deliver`,t.instanceId,e)}}}function D(e,t){let n=e.catch(e=>{C(`deliver`,t,e)});d.add(n),n.then(()=>{d.delete(n)})}async function O(){for(;d.size>0;)await Promise.all([...d])}function k(e){if(u.length===0)return;let t=Object.values(e.bindings);if(t.length===0)return;let n=[...c.values()].flatMap(e=>Object.values(e.bindings));for(let e=u.length-1;e>=0;--e){let r=u[e];r!==void 0&&t.some(e=>e.symbol===r.target.symbol&&e.port===r.target.port)&&(n.some(e=>e.symbol===r.target.symbol&&e.port===r.target.port)||u.splice(e,1))}}function A(e){e.failed||e.disposed||p||(l.add(e),!(m||f)&&(f=!0,queueMicrotask(j)))}function j(){if(f=!1,m)return;let e=[...l];l.clear();for(let t of e)M(t)}function M(e){if(e.failed||e.disposed||p)return!1;let{context:t,canvas:n}=e;typeof t.setTransform==`function`&&(t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,n.width,n.height),t.setTransform(e.dpr,0,0,e.dpr,0,0));let r=e.instance?.render;if(typeof r==`function`)try{r.call(e.instance,t)}catch(t){return e.failed=!0,l.delete(e),C(`render`,e.instanceId,t),!1}return N(e)}function N(t){let n;try{n=t.canvas.transferToImageBitmap()}catch(e){return t.failed=!0,C(`render`,t.instanceId,e),!1}let r={instanceId:t.instanceId,bitmap:n,width:t.width,height:t.height,dpr:t.dpr,...t.generation===void 0?{}:{generation:t.generation}};try{e.emit(`widget:frame`,r,[n])}catch{return ee(n),!1}return!0}function F(e){let t=c.get(e);if(!t)throw Error(`Widget instance ${JSON.stringify(e)} is not mounted`);return t}function I(e,t){let n=G(e.width,e.height,e.dpr),r=t?.properties??{};return S.open(e.instanceId,e.audio),{instanceId:e.instanceId,generation:e.generation,width:J(e.width),height:J(e.height),dpr:Y(e.dpr),props:H(r,e.props),properties:r,assets:Z(e.assets),reportedAssets:/* @__PURE__ */ new Set,canvas:n,context:K(n),subscriptions:/* @__PURE__ */ new Map,bindings:{},instance:void 0,failed:!1,disposed:!1}}function L(t,n,r){if(t.disposed||p||t.reportedAssets.has(n))return;t.reportedAssets.add(n);let i={instanceId:t.instanceId,src:n,error:{name:`Error`,message:r}};try{e.emit(`widget:asset-failed`,i)}catch{}}function R(e,t){if(typeof t!=`string`)return Promise.reject(/* @__PURE__ */ TypeError(`Widget asset src must be a string`));let n=e.assets.get(t);if(n!==void 0&&!e.disposed&&!p)return Promise.resolve(new Uint8Array(n));let r=`Widget asset ${JSON.stringify(t)} was not prefetched`;return e.disposed||p||L(e,t,r),Promise.reject(Error(r))}function B(n){return{instanceId:n.instanceId,get width(){return n.width},get height(){return n.height},get props(){return n.props},assets:{readBinary:e=>R(n,e)},audio:S.api(n.instanceId),subscribe(e,t){if(n.disposed||typeof t!=`function`)return()=>{};let r=n.subscriptions.get(e);return r||(r=/* @__PURE__ */ new Set,n.subscriptions.set(e,r)),r.add(t),()=>{n.subscriptions.get(e)?.delete(t)}},publish(r,i,a){if(n.disposed||p)return;let o={instanceId:n.instanceId,port:r,payload:i,simTime:Q(a,m?h:0)},s=n.bindings[r],c=s!==void 0&&g!==void 0;if(s!==void 0&&g!==void 0)try{D(Promise.resolve(g.deliver({target:s,payload:i,simTime:t(o.simTime)})),n.instanceId)}catch(e){C(`deliver`,n.instanceId,e)}try{e.emit(`widget:publish`,c?{...o,direct:c}:o)}catch(e){C(`deliver`,n.instanceId,e)}},invalidate(){A(n)}}}function V(e){e.disposed=!0,l.delete(e),e.subscriptions.clear(),S.release(e.instanceId);let t=e.instance;if(e.instance=void 0,t&&typeof t.dispose==`function`)try{t.dispose()}catch(t){C(`render`,e.instanceId,t)}e.assets.clear(),e.canvas.width=1,e.canvas.height=1}async function U(e,t){let n=await r(t),i=n&&typeof n==`object`?n.default:void 0;if(typeof i!=`function`)throw Error(`Widget ${JSON.stringify(e)} must default-export a factory function`);return i}return{async load(e){x();let t=Array.isArray(e.packages)?e.packages:[],n,r=!1;for(let e of t){let t=e.modules;if(t&&typeof t==`object`)for(let s of Object.keys(t)){let c=t[s];if(!c)continue;let l=`${e.id}:${s}`;if(!i.has(l))try{let e=o.get(l);e||(e=U(l,c.code),o.set(l,e)),i.set(l,await e),a.set(l,c.definition)}catch(e){r||=(n=e,!0)}finally{o.delete(l)}}}if(r)throw n},mount(e){if(p)throw Error(`The widget runtime is disposed`);let{instanceId:t,widget:n}=e;if(c.has(t))throw Error(`Widget instance ${JSON.stringify(t)} is already mounted`);let r=i.get(n);if(!r)throw Error(`Widget ${JSON.stringify(n)} is not loaded`);let o=I(e,a.get(n));c.set(t,o);try{o.instance=q(r(B(o)))}catch(e){throw c.delete(t),V(o),C(`mount`,t,e),e instanceof Error?e:Error(String(e))}if(l.delete(o),!M(o)&&m)throw c.delete(t),V(o),Error(`Widget instance ${JSON.stringify(t)} failed during its first paint`)},unmount(e){let t=c.get(e);t&&(c.delete(e),k(t),V(t))},resize(e,t,n,r){let i=F(e);i.width=J(t),i.height=J(n),i.dpr=Y(r),i.canvas.width=X(t,i.dpr),i.canvas.height=X(n,i.dpr),l.delete(i),m?l.add(i):M(i)},setProperties(e,t){let n=F(e);n.props=H(n.properties,t),A(n)},setAssets(e,t){let n=F(e);n.assets.clear(),n.reportedAssets.clear();for(let[e,r]of Z(t))n.assets.set(e,r)},setBindings(e,t){x();let n=c.get(e);n!==void 0&&(n.bindings=t??{})},deliver(e,t,n,r){x(),w(e,t,n,r)},pointer(e,t){let n=F(e);if(n.failed||n.disposed)return;let r=n.instance?.input;if(typeof r==`function`)try{r.call(n.instance,t)}catch(t){C(`deliver`,e,t)}},configure(e){return!p&&(e?.explicitStepping!==void 0&&(m=e.explicitStepping===!0),e?.directTopicService===void 0?g!==void 0:g===void 0?b(e.directTopicService):_===e.directTopicService)},async step(e){if(p)throw Error(`The widget runtime is disposed`);if(h=t(e.simTime),t(e.dt),e.mode!==`edit`&&e.mode!==`simulation`)throw TypeError(`Unknown widget step mode: ${String(e.mode)}`);if(m){await O();for(let e of u.splice(0))E(e);let e=[...l];l.clear();for(let t of e)M(t)}await O()},resetRuntime(){if(!p){l.clear(),u.length=0,d.clear();for(let e of[...c.values()])c.delete(e.instanceId),V(e);c.clear()}},dispose(){if(!p){p=!0,y(),v?.dispose(),v=void 0,g=void 0;try{n.devicePort?.close()}catch{}l.clear(),u.length=0,d.clear();for(let e of[...c.values()])V(e);c.clear(),S.dispose(),i.clear(),a.clear(),o.clear()}},attachAudioPort(e){S.attachPort(e)},setAudioState(e){S.setState(e)}}}function G(e,t,n){return new OffscreenCanvas(X(e,n),X(t,n))}function K(e){let t=e.getContext(`2d`);if(!t)throw Error(`The widget runtime needs a 2D context`);return t}function q(e){return e&&typeof e==`object`?e:{}}function J(e){return Number.isFinite(e)&&e>0?e:0}function Y(e){return Number.isFinite(e)&&e>0?e:1}function X(e,t){return Math.max(1,Math.round(J(e)*Y(t)))}function Z(e){let t=/* @__PURE__ */ new Map;if(typeof e!=`object`||!e)return t;for(let n of Object.keys(e)){let r=e[n];r instanceof Uint8Array&&t.set(n,new Uint8Array(r))}return t}function Q(e,t){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:t}function ee(e){try{e.close()}catch{}}function te(e){return e instanceof Error&&e.name?e.name:`Error`}function ne(e){return e instanceof Error&&e.message?e.message:typeof e==`string`?e:String(e)}function re(e){let t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return import(\n/* @vite-ignore */\nt).finally(()=>URL.revokeObjectURL(t))}let $=!1;self.addEventListener(`message`,e=>{if($)return;let t=e.ports[0];t!==void 0&&($=!0,U(t,{ports:e.ports.slice(1)}))})})();";
2616
1699
  /**
2617
1700
  * Creates the widget host guest worker.
2618
1701
  *
2619
- * This is the guest `WidgetHost` talks to, and it is the same one `@mica-js/canvas-editor`'s
2620
- * `SandboxHostProvider` starts by default. Hosts only start it; the RPC surface is wired by
2621
- * `createWidgetSandboxFromWorker`.
1702
+ * Hosts start the guest, then wire its RPC surface with `createWidgetSandboxFromWorker`.
2622
1703
  */
2623
1704
  function createWidgetHostGuestSandbox(options = {}) {
2624
1705
  return new SandboxWorker(widgetGuestScript, {
@@ -2627,6 +1708,6 @@ function createWidgetHostGuestSandbox(options = {}) {
2627
1708
  });
2628
1709
  }
2629
1710
  //#endregion
2630
- export { HostFsError, WidgetLoadError, createPackageWidgetProvider, createStaticWidgetProvider, createWidgetAudioWorklet, createWidgetHost, createWidgetHostGuestSandbox, createWidgetSandboxFromWorker, decodeDataUri, decodeDataUriText, fromHostFsErrorPayload, isAbsoluteHostUri, isHostFsError, loadWidgetPackage, resolveHostUri, toHostFsErrorPayload, widgetAudioWorkletUrl, widgetGuestScript };
1711
+ export { HostFsError, WidgetLoadError, WidgetRuntimeError, createPackageWidgetProvider, createStaticWidgetProvider, createWidgetAudioWorklet, createWidgetHostGuestSandbox, createWidgetRuntime, createWidgetSandboxFromWorker, decodeDataUri, decodeDataUriText, fromHostFsErrorPayload, isAbsoluteHostUri, isHostFsError, loadWidgetPackage, resolveHostUri, toHostFsErrorPayload, widgetAudioWorkletUrl, widgetConfigureMethod, widgetGuestScript, widgetSetAssetsMethod, widgetSimulationRuntimeService, widgetStepMethod };
2631
1712
 
2632
1713
  //# sourceMappingURL=index.js.map