@mica-js/widget 0.3.1 → 0.5.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/audio-guest.d.ts +168 -0
- package/dist/audio-guest.js +586 -0
- package/dist/audio-guest.js.map +1 -0
- package/dist/audio-host.d.ts +163 -0
- package/dist/audio-host.js +1 -0
- package/dist/engine-6tEkErMg.js +331 -0
- package/dist/engine-6tEkErMg.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +6 -347
- package/dist/index.js.map +1 -1
- package/dist/protocol-BuE4pcSf.js +23 -0
- package/dist/protocol-BuE4pcSf.js.map +1 -0
- package/package.json +12 -4
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
declare interface AudioContextLike {
|
|
2
|
+
readonly sampleRate: number;
|
|
3
|
+
/** `suspended` | `running` | `closed` for a real context. */
|
|
4
|
+
readonly state: string;
|
|
5
|
+
readonly destination: AudioNodeLike;
|
|
6
|
+
readonly audioWorklet?: {
|
|
7
|
+
addModule(url: string): Promise<void>;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Fired by a real context whenever the browser suspends or resumes it on its own (autoplay
|
|
11
|
+
* policy, hidden page, a caller calling `suspend()` / `resume()`). Used as a fallback when the
|
|
12
|
+
* context lacks `addEventListener`; fakes may leave it `null`.
|
|
13
|
+
*/
|
|
14
|
+
onstatechange?: ((event: Event) => void) | null;
|
|
15
|
+
/** Preferred over `onstatechange`: subscribing must not clobber the caller's own handler. */
|
|
16
|
+
addEventListener?(type: 'statechange', listener: () => void): void;
|
|
17
|
+
removeEventListener?(type: 'statechange', listener: () => void): void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Structural stand-ins for the Web Audio nodes the engine touches; tests inject fakes. */
|
|
21
|
+
declare interface AudioNodeLike {
|
|
22
|
+
connect(destination: AudioNodeLike): unknown;
|
|
23
|
+
disconnect?(): void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
declare interface AudioWorkletNodeLike extends AudioNodeLike {
|
|
27
|
+
readonly port: MessagePort;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
declare interface MessageChannelLike {
|
|
31
|
+
readonly port1: MessagePort;
|
|
32
|
+
readonly port2: MessagePort;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** `IWidgetRuntime.audio` controls every instance owned by the runtime. */
|
|
36
|
+
export declare interface WidgetAudioControls {
|
|
37
|
+
/** Mirror of the state the guest reads from `api.audio.state`. */
|
|
38
|
+
readonly state: WidgetAudioState;
|
|
39
|
+
/** Mutes every instance without touching buffers; PCM keeps flowing into the worklet. */
|
|
40
|
+
setMuted(muted: boolean): void;
|
|
41
|
+
/**
|
|
42
|
+
* Scales one instance inside the worklet.
|
|
43
|
+
*
|
|
44
|
+
* @throws {TypeError} when `volume` is not a number.
|
|
45
|
+
* @throws {RangeError} when it is outside `[0, 1]`.
|
|
46
|
+
*/
|
|
47
|
+
setInstanceVolume(instanceId: string, volume: number): void;
|
|
48
|
+
/**
|
|
49
|
+
* Freezes all widget audio, for example while a simulation is paused.
|
|
50
|
+
*
|
|
51
|
+
* Tones go silent and the worklet pauses consumption while keeping the PCM it already buffered.
|
|
52
|
+
* The caller's `AudioContext` is left alone.
|
|
53
|
+
*/
|
|
54
|
+
suspend(): void;
|
|
55
|
+
resume(): void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Diagnostic codes the audio path reports. */
|
|
59
|
+
declare type WidgetAudioDiagnosticCode = 'widget/audio-failed' | 'widget/audio-limit';
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Host half of the audio path (RFC 0016).
|
|
63
|
+
*
|
|
64
|
+
* Owns the one `AudioWorkletNode`, the session tokens, and the two RPC endpoints that reach the
|
|
65
|
+
* worklet: host controls over the node port, and the direct guest channel it hands to the sandbox.
|
|
66
|
+
* No audio node other than that worklet is created here: tones, mixing and volume all live inside
|
|
67
|
+
* the worklet.
|
|
68
|
+
*/
|
|
69
|
+
export declare class WidgetAudioEngine {
|
|
70
|
+
#private;
|
|
71
|
+
constructor(options: WidgetAudioEngineOptions);
|
|
72
|
+
/**
|
|
73
|
+
* Current availability.
|
|
74
|
+
*
|
|
75
|
+
* `unavailable` means "no audio at all": the host configured none, the browser lacks
|
|
76
|
+
* `AudioWorklet`, or the worklet module failed to load.
|
|
77
|
+
*/
|
|
78
|
+
get state(): WidgetAudioState;
|
|
79
|
+
/** Limits in force, so a caller can mirror them in its own UI. */
|
|
80
|
+
get limits(): WidgetAudioLimits;
|
|
81
|
+
/**
|
|
82
|
+
* Opens the mount generation of one instance.
|
|
83
|
+
*
|
|
84
|
+
* Resolves once the worklet registered the session token, so the `mount` request that carries it
|
|
85
|
+
* can never arrive after the first guest call of that generation.
|
|
86
|
+
*/
|
|
87
|
+
open(instanceId: string): Promise<WidgetAudioMountInfo>;
|
|
88
|
+
setMuted(muted: boolean): void;
|
|
89
|
+
setInstanceVolume(instanceId: string, volume: number): void;
|
|
90
|
+
/** Freezes audio without touching the caller's `AudioContext`. */
|
|
91
|
+
suspend(): void;
|
|
92
|
+
resume(): void;
|
|
93
|
+
/**
|
|
94
|
+
* Closes the instance only when it still belongs to `session`.
|
|
95
|
+
*
|
|
96
|
+
* A mount attempt that lost its id may have opened its own audio generation after the host's
|
|
97
|
+
* cleanup sweep; closing by id alone would tear down the replacement instead.
|
|
98
|
+
*/
|
|
99
|
+
closeSession(instanceId: string, session: string): void;
|
|
100
|
+
/** Drops one instance: its session token is revoked and the worklet ends its voices and streams. */
|
|
101
|
+
close(instanceId: string): void;
|
|
102
|
+
/**
|
|
103
|
+
* Drops every instance and hands the worklet a fresh guest channel.
|
|
104
|
+
*
|
|
105
|
+
* Called when the sandbox goes away: the old guest port died with it, and the next sandbox needs
|
|
106
|
+
* a port of its own.
|
|
107
|
+
*/
|
|
108
|
+
reset(): void;
|
|
109
|
+
dispose(): void;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export declare interface WidgetAudioEngineOptions {
|
|
113
|
+
readonly context: AudioContextLike;
|
|
114
|
+
readonly destination?: AudioNodeLike;
|
|
115
|
+
readonly limits?: Partial<WidgetAudioLimits>;
|
|
116
|
+
readonly report: (code: WidgetAudioDiagnosticCode, instanceId: string, message: string) => void;
|
|
117
|
+
readonly notify: WidgetAudioNotifier;
|
|
118
|
+
/** Loads the audio worklet node; tests or applications may provide their own loader. */
|
|
119
|
+
readonly loadWorklet?: () => Promise<AudioWorkletNodeLike>;
|
|
120
|
+
readonly createChannel?: () => MessageChannelLike;
|
|
121
|
+
readonly createWorkletNode?: (context: AudioContextLike, name: string) => AudioWorkletNodeLike;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Per-instance ceilings; a host may tighten them through its options. */
|
|
125
|
+
declare interface WidgetAudioLimits {
|
|
126
|
+
readonly maxVoices: number;
|
|
127
|
+
readonly maxStreams: number;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Attached to `mount` so the factory can read `api.audio.state` synchronously. */
|
|
131
|
+
export declare interface WidgetAudioMountInfo {
|
|
132
|
+
readonly state: WidgetAudioState;
|
|
133
|
+
/** One-shot token this mount generation uses on the direct port. */
|
|
134
|
+
readonly session?: string;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Host-side sinks the engine reports into; the widget host owns the sandbox plumbing. */
|
|
138
|
+
declare interface WidgetAudioNotifier {
|
|
139
|
+
/** Hands the direct guest ↔ worklet port to the sandbox. */
|
|
140
|
+
emitPort(port: MessagePort): void;
|
|
141
|
+
emitState(state: WidgetAudioState): void;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Audio configuration for `createWidgetRuntime` (RFC 0016).
|
|
146
|
+
*
|
|
147
|
+
* Omit it and `api.audio.state` is `unavailable`: every method still returns a usable handle, but
|
|
148
|
+
* nothing is ever played.
|
|
149
|
+
*/ export declare interface WidgetAudioOptions {
|
|
150
|
+
/** Context all audio renders into. The caller owns it; the host never closes it. */
|
|
151
|
+
readonly context: AudioContext;
|
|
152
|
+
/** Where the host's master gain ends up; defaults to `context.destination`. */
|
|
153
|
+
readonly destination?: AudioNode;
|
|
154
|
+
/** Creates the worklet node using the caller-owned context. */
|
|
155
|
+
readonly getAudioWorklet?: (context: AudioContext) => Promise<AudioWorkletNode>;
|
|
156
|
+
/** Tightens the defaults (8 voices, 4 PCM streams per instance). */
|
|
157
|
+
readonly limits?: Partial<WidgetAudioLimits>;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Availability of the host audio path. */
|
|
161
|
+
export declare type WidgetAudioState = 'unavailable' | 'suspended' | 'running';
|
|
162
|
+
|
|
163
|
+
export { }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as WidgetAudioEngine } from "./engine-6tEkErMg.js";
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { r as widgetAudioWorkletProcessor, t as widgetAudioControlService } from "./protocol-BuE4pcSf.js";
|
|
2
|
+
import { createRpc } from "@mica-js/core/rpc";
|
|
3
|
+
//#region \0mica-widget-audio-worklet-code:/home/runner/work/mica-js/mica-js/packages/widget/src/guest/audio/entry.ts
|
|
4
|
+
var entry_default = "(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)})();";
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region src/host/audio/worklet.ts
|
|
7
|
+
var objectUrl;
|
|
8
|
+
/**
|
|
9
|
+
* Blob URL of the packaged `AudioWorkletProcessor` script.
|
|
10
|
+
*
|
|
11
|
+
* The script is bundled and minified into this module while the package is built, so an
|
|
12
|
+
* `AudioContext` can load it through `addModule()` without the package publishing a separate
|
|
13
|
+
* `*.worklet.js` asset. The URL is created once per page and reused by every host.
|
|
14
|
+
*/
|
|
15
|
+
function widgetAudioWorkletUrl() {
|
|
16
|
+
objectUrl ??= URL.createObjectURL(new Blob([entry_default], { type: "text/javascript" }));
|
|
17
|
+
return objectUrl;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Loads the packaged processor into `context` and creates its node.
|
|
21
|
+
*
|
|
22
|
+
* Pass it as `WidgetAudioOptions.getAudioWorklet`; runtimes that provide no loader of their
|
|
23
|
+
* own use the same processor internally.
|
|
24
|
+
*/
|
|
25
|
+
async function createWidgetAudioWorklet(context) {
|
|
26
|
+
if (typeof context.audioWorklet?.addModule !== "function") throw new Error("The AudioContext does not support AudioWorklet.addModule().");
|
|
27
|
+
await context.audioWorklet.addModule(widgetAudioWorkletUrl());
|
|
28
|
+
return new AudioWorkletNode(context, widgetAudioWorkletProcessor);
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/host/audio/engine.ts
|
|
32
|
+
/**
|
|
33
|
+
* Host half of the audio path (RFC 0016).
|
|
34
|
+
*
|
|
35
|
+
* Owns the one `AudioWorkletNode`, the session tokens, and the two RPC endpoints that reach the
|
|
36
|
+
* worklet: host controls over the node port, and the direct guest channel it hands to the sandbox.
|
|
37
|
+
* No audio node other than that worklet is created here: tones, mixing and volume all live inside
|
|
38
|
+
* the worklet.
|
|
39
|
+
*/
|
|
40
|
+
var WidgetAudioEngine = class {
|
|
41
|
+
#context;
|
|
42
|
+
#destination;
|
|
43
|
+
#report;
|
|
44
|
+
#notify;
|
|
45
|
+
#limits;
|
|
46
|
+
#loadWorklet;
|
|
47
|
+
#createChannel;
|
|
48
|
+
#createWorkletNode;
|
|
49
|
+
#runtimeId = `r${Math.random().toString(36).slice(2, 10)}`;
|
|
50
|
+
#instances = /* @__PURE__ */ new Map();
|
|
51
|
+
#worklet;
|
|
52
|
+
#endpoint;
|
|
53
|
+
#control;
|
|
54
|
+
#booting;
|
|
55
|
+
#available;
|
|
56
|
+
#muted = false;
|
|
57
|
+
#suspended = false;
|
|
58
|
+
#sessionCounter = 0;
|
|
59
|
+
#disposed = false;
|
|
60
|
+
#lastState;
|
|
61
|
+
#detachStateListener;
|
|
62
|
+
/** Context state moved without an engine call; guests get the same ordered notification. */
|
|
63
|
+
#onContextStateChange = () => {
|
|
64
|
+
if (this.#disposed) return;
|
|
65
|
+
if (this.#context.state === "closed") for (const instanceId of this.#instances.keys()) this.#report("widget/audio-failed", instanceId, "The host AudioContext was closed.");
|
|
66
|
+
this.#syncState();
|
|
67
|
+
};
|
|
68
|
+
constructor(options) {
|
|
69
|
+
this.#context = options.context;
|
|
70
|
+
this.#destination = options.destination ?? options.context.destination;
|
|
71
|
+
this.#report = options.report;
|
|
72
|
+
this.#notify = options.notify;
|
|
73
|
+
this.#limits = {
|
|
74
|
+
maxVoices: Math.max(1, Math.floor(options.limits?.maxVoices ?? 8)),
|
|
75
|
+
maxStreams: Math.max(1, Math.floor(options.limits?.maxStreams ?? 4))
|
|
76
|
+
};
|
|
77
|
+
this.#loadWorklet = options.loadWorklet;
|
|
78
|
+
this.#createChannel = options.createChannel ?? (() => {
|
|
79
|
+
const channel = new MessageChannel();
|
|
80
|
+
return {
|
|
81
|
+
port1: channel.port1,
|
|
82
|
+
port2: channel.port2
|
|
83
|
+
};
|
|
84
|
+
});
|
|
85
|
+
this.#createWorkletNode = options.createWorkletNode ?? ((context, name) => {
|
|
86
|
+
const ctor = globalThis.AudioWorkletNode;
|
|
87
|
+
if (!ctor) throw new Error("AudioWorkletNode is not available");
|
|
88
|
+
return new ctor(context, name, {
|
|
89
|
+
numberOfInputs: 0,
|
|
90
|
+
numberOfOutputs: 1,
|
|
91
|
+
outputChannelCount: [2]
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Current availability.
|
|
97
|
+
*
|
|
98
|
+
* `unavailable` means "no audio at all": the host configured none, the browser lacks
|
|
99
|
+
* `AudioWorklet`, or the worklet module failed to load.
|
|
100
|
+
*/
|
|
101
|
+
get state() {
|
|
102
|
+
if (this.#disposed || this.#available === false || this.#context.state === "closed") return "unavailable";
|
|
103
|
+
if (this.#available !== true || this.#suspended) return "suspended";
|
|
104
|
+
return this.#context.state === "running" ? "running" : "suspended";
|
|
105
|
+
}
|
|
106
|
+
/** Limits in force, so a caller can mirror them in its own UI. */
|
|
107
|
+
get limits() {
|
|
108
|
+
return this.#limits;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Opens the mount generation of one instance.
|
|
112
|
+
*
|
|
113
|
+
* Resolves once the worklet registered the session token, so the `mount` request that carries it
|
|
114
|
+
* can never arrive after the first guest call of that generation.
|
|
115
|
+
*/
|
|
116
|
+
async open(instanceId) {
|
|
117
|
+
if (this.#disposed) return { state: "unavailable" };
|
|
118
|
+
if (!await this.#boot()) return { state: "unavailable" };
|
|
119
|
+
this.close(instanceId);
|
|
120
|
+
this.#sessionCounter += 1;
|
|
121
|
+
const session = `${this.#runtimeId}-${this.#sessionCounter}`;
|
|
122
|
+
this.#instances.set(instanceId, {
|
|
123
|
+
instanceId,
|
|
124
|
+
session
|
|
125
|
+
});
|
|
126
|
+
try {
|
|
127
|
+
await this.#control?.openSession({
|
|
128
|
+
session,
|
|
129
|
+
runtimeId: this.#runtimeId,
|
|
130
|
+
instanceId,
|
|
131
|
+
maxVoices: this.#limits.maxVoices,
|
|
132
|
+
maxStreams: this.#limits.maxStreams
|
|
133
|
+
});
|
|
134
|
+
} catch (error) {
|
|
135
|
+
this.#report("widget/audio-failed", instanceId, `The audio worklet rejected the session: ${describe(error)}`);
|
|
136
|
+
}
|
|
137
|
+
this.#syncState();
|
|
138
|
+
return {
|
|
139
|
+
state: this.state,
|
|
140
|
+
session
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
setMuted(muted) {
|
|
144
|
+
this.#muted = muted === true;
|
|
145
|
+
this.#call((control) => control.setMuted(this.#muted));
|
|
146
|
+
}
|
|
147
|
+
setInstanceVolume(instanceId, volume) {
|
|
148
|
+
if (typeof volume !== "number") throw new TypeError("WidgetAudioControls.setInstanceVolume expects a number");
|
|
149
|
+
if (!Number.isFinite(volume) || volume < 0 || volume > 1) throw new RangeError("WidgetAudioControls.setInstanceVolume expects a value in [0, 1]");
|
|
150
|
+
const instance = this.#instances.get(instanceId);
|
|
151
|
+
if (!instance) return;
|
|
152
|
+
this.#call((control) => control.setSessionVolume(instance.session, volume));
|
|
153
|
+
}
|
|
154
|
+
/** Freezes audio without touching the caller's `AudioContext`. */
|
|
155
|
+
suspend() {
|
|
156
|
+
if (this.#disposed || this.#suspended) return;
|
|
157
|
+
this.#suspended = true;
|
|
158
|
+
this.#call((control) => control.suspend());
|
|
159
|
+
this.#syncState();
|
|
160
|
+
}
|
|
161
|
+
resume() {
|
|
162
|
+
if (this.#disposed) return;
|
|
163
|
+
this.#suspended = false;
|
|
164
|
+
this.#call((control) => control.resume());
|
|
165
|
+
this.#syncState();
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Closes the instance only when it still belongs to `session`.
|
|
169
|
+
*
|
|
170
|
+
* A mount attempt that lost its id may have opened its own audio generation after the host's
|
|
171
|
+
* cleanup sweep; closing by id alone would tear down the replacement instead.
|
|
172
|
+
*/
|
|
173
|
+
closeSession(instanceId, session) {
|
|
174
|
+
const instance = this.#instances.get(instanceId);
|
|
175
|
+
if (!instance || instance.session !== session) return;
|
|
176
|
+
this.close(instanceId);
|
|
177
|
+
}
|
|
178
|
+
/** Drops one instance: its session token is revoked and the worklet ends its voices and streams. */
|
|
179
|
+
close(instanceId) {
|
|
180
|
+
const instance = this.#instances.get(instanceId);
|
|
181
|
+
if (!instance) return;
|
|
182
|
+
this.#instances.delete(instanceId);
|
|
183
|
+
this.#call((control) => control.closeSession(instance.session));
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Drops every instance and hands the worklet a fresh guest channel.
|
|
187
|
+
*
|
|
188
|
+
* Called when the sandbox goes away: the old guest port died with it, and the next sandbox needs
|
|
189
|
+
* a port of its own.
|
|
190
|
+
*/
|
|
191
|
+
reset() {
|
|
192
|
+
for (const instanceId of [...this.#instances.keys()]) this.close(instanceId);
|
|
193
|
+
if (this.#available === true && this.#control !== void 0) this.#restartRuntime();
|
|
194
|
+
}
|
|
195
|
+
dispose() {
|
|
196
|
+
if (this.#disposed) return;
|
|
197
|
+
for (const instanceId of [...this.#instances.keys()]) this.close(instanceId);
|
|
198
|
+
this.#call((control) => control.detachGuestPort(this.#runtimeId));
|
|
199
|
+
this.#disposed = true;
|
|
200
|
+
this.#detachStateListener?.();
|
|
201
|
+
this.#detachStateListener = void 0;
|
|
202
|
+
this.#endpoint?.dispose();
|
|
203
|
+
this.#endpoint = void 0;
|
|
204
|
+
this.#control = void 0;
|
|
205
|
+
const worklet = this.#worklet;
|
|
206
|
+
this.#worklet = void 0;
|
|
207
|
+
if (worklet !== void 0) {
|
|
208
|
+
closePort(worklet.port);
|
|
209
|
+
try {
|
|
210
|
+
worklet.disconnect?.();
|
|
211
|
+
} catch {}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/** Boots the worklet once; a failure is permanent for the lifetime of the engine. */
|
|
215
|
+
#boot() {
|
|
216
|
+
this.#booting ??= this.#start().catch((error) => {
|
|
217
|
+
this.#available = false;
|
|
218
|
+
if (!this.#disposed) this.#report("widget/audio-failed", "", `Widget audio is unavailable: ${describe(error)}`);
|
|
219
|
+
return false;
|
|
220
|
+
});
|
|
221
|
+
return this.#booting;
|
|
222
|
+
}
|
|
223
|
+
async #start() {
|
|
224
|
+
if (this.#loadWorklet === void 0 && typeof this.#context.audioWorklet?.addModule !== "function") {
|
|
225
|
+
this.#available = false;
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
this.#listenForContextState();
|
|
229
|
+
const worklet = await (this.#loadWorklet?.() ?? this.#loadDefaultWorklet());
|
|
230
|
+
if (this.#disposed) {
|
|
231
|
+
closePort(worklet.port);
|
|
232
|
+
try {
|
|
233
|
+
worklet.disconnect?.();
|
|
234
|
+
} catch {}
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
this.#worklet = worklet;
|
|
238
|
+
const endpoint = createRpc(worklet.port);
|
|
239
|
+
this.#endpoint = endpoint;
|
|
240
|
+
const control = endpoint.getProxy(widgetAudioControlService, { transfer: (member, args) => member === "attachGuestPort" ? [args[1]] : [] });
|
|
241
|
+
this.#control = control;
|
|
242
|
+
control.onDidDiagnostic((diagnostic) => this.#onDiagnostic(diagnostic));
|
|
243
|
+
worklet.connect(this.#destination);
|
|
244
|
+
await this.#attachRuntime();
|
|
245
|
+
if (this.#suspended) await control.suspend();
|
|
246
|
+
this.#available = true;
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Mirrors the context's own `statechange` onto mounted guests.
|
|
251
|
+
*
|
|
252
|
+
* The caller owns the `AudioContext`, so its state can move without the engine asking: autoplay
|
|
253
|
+
* policy keeping it suspended, the browser suspending a hidden page, or the caller calling
|
|
254
|
+
* `resume()`. Guests read `api.audio.state` and `onStateChange`, so those moves must be forwarded.
|
|
255
|
+
*/
|
|
256
|
+
#listenForContextState() {
|
|
257
|
+
if (this.#detachStateListener) return;
|
|
258
|
+
const context = this.#context;
|
|
259
|
+
if (typeof context.addEventListener === "function") {
|
|
260
|
+
context.addEventListener("statechange", this.#onContextStateChange);
|
|
261
|
+
this.#detachStateListener = () => context.removeEventListener?.("statechange", this.#onContextStateChange);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (!("onstatechange" in context)) return;
|
|
265
|
+
const previous = context.onstatechange;
|
|
266
|
+
context.onstatechange = this.#onContextStateChange;
|
|
267
|
+
this.#detachStateListener = () => {
|
|
268
|
+
if (context.onstatechange === this.#onContextStateChange) context.onstatechange = previous;
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
/** Worklet → host diagnostics, attributed back to the instance that owns the session. */
|
|
272
|
+
#onDiagnostic(diagnostic) {
|
|
273
|
+
const owner = [...this.#instances.values()].find((entry) => entry.session === diagnostic.session);
|
|
274
|
+
if (!owner) return;
|
|
275
|
+
this.#report(diagnostic.code, owner.instanceId, diagnostic.message);
|
|
276
|
+
}
|
|
277
|
+
async #loadDefaultWorklet() {
|
|
278
|
+
await this.#context.audioWorklet?.addModule(widgetAudioWorkletUrl());
|
|
279
|
+
return this.#createWorkletNode(this.#context, widgetAudioWorkletProcessor);
|
|
280
|
+
}
|
|
281
|
+
async #restartRuntime() {
|
|
282
|
+
const control = this.#control;
|
|
283
|
+
if (control === void 0) return;
|
|
284
|
+
try {
|
|
285
|
+
await control.detachGuestPort(this.#runtimeId);
|
|
286
|
+
} catch {}
|
|
287
|
+
await this.#attachRuntime();
|
|
288
|
+
}
|
|
289
|
+
/** Transfers a fresh port to the worklet and hands the other end to the guest. */
|
|
290
|
+
async #attachRuntime() {
|
|
291
|
+
const control = this.#control;
|
|
292
|
+
if (control === void 0 || this.#disposed) return;
|
|
293
|
+
const channel = this.#createChannel();
|
|
294
|
+
try {
|
|
295
|
+
await control.attachGuestPort(this.#runtimeId, channel.port1);
|
|
296
|
+
} catch (error) {
|
|
297
|
+
closePort(channel.port1);
|
|
298
|
+
closePort(channel.port2);
|
|
299
|
+
this.#report("widget/audio-failed", "", `The audio worklet rejected the guest port: ${describe(error)}`);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
this.#notify.emitPort(channel.port2);
|
|
303
|
+
}
|
|
304
|
+
/** Fires one host → worklet call; a missing or closed worklet is not a widget failure. */
|
|
305
|
+
#call(run) {
|
|
306
|
+
const control = this.#control;
|
|
307
|
+
if (control === void 0 || this.#disposed) return;
|
|
308
|
+
try {
|
|
309
|
+
run(control).catch(() => void 0);
|
|
310
|
+
} catch {}
|
|
311
|
+
}
|
|
312
|
+
#syncState() {
|
|
313
|
+
const next = this.state;
|
|
314
|
+
if (next === this.#lastState) return;
|
|
315
|
+
this.#lastState = next;
|
|
316
|
+
this.#notify.emitState(next);
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
function closePort(port) {
|
|
320
|
+
try {
|
|
321
|
+
port.close();
|
|
322
|
+
} catch {}
|
|
323
|
+
}
|
|
324
|
+
function describe(error) {
|
|
325
|
+
if (error instanceof Error && error.message) return error.message;
|
|
326
|
+
return typeof error === "string" ? error : String(error);
|
|
327
|
+
}
|
|
328
|
+
//#endregion
|
|
329
|
+
export { createWidgetAudioWorklet as n, widgetAudioWorkletUrl as r, WidgetAudioEngine as t };
|
|
330
|
+
|
|
331
|
+
//# sourceMappingURL=engine-6tEkErMg.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"engine-6tEkErMg.js","names":["workletScript"],"sources":["../src/host/audio/worklet.ts","../src/host/audio/engine.ts"],"sourcesContent":["import workletScript from '../../guest/audio/entry.ts?audio-worklet-code';\nimport { widgetAudioWorkletProcessor } from '../../guest/audio/protocol';\n\nlet objectUrl: string | undefined;\n\n/**\n * Blob URL of the packaged `AudioWorkletProcessor` script.\n *\n * The script is bundled and minified into this module while the package is built, so an\n * `AudioContext` can load it through `addModule()` without the package publishing a separate\n * `*.worklet.js` asset. The URL is created once per page and reused by every host.\n */\nexport function widgetAudioWorkletUrl(): string {\n objectUrl ??= URL.createObjectURL(new Blob([workletScript], { type: 'text/javascript' }));\n return objectUrl;\n}\n\n/**\n * Loads the packaged processor into `context` and creates its node.\n *\n * Pass it as `WidgetAudioOptions.getAudioWorklet`; runtimes that provide no loader of their\n * own use the same processor internally.\n */\nexport async function createWidgetAudioWorklet(context: AudioContext): Promise<AudioWorkletNode> {\n if (typeof context.audioWorklet?.addModule !== 'function') {\n throw new Error('The AudioContext does not support AudioWorklet.addModule().');\n }\n await context.audioWorklet.addModule(widgetAudioWorkletUrl());\n return new AudioWorkletNode(context, widgetAudioWorkletProcessor);\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint, RpcProxy } from '@mica-js/core/rpc';\nimport {\n defaultMaxStreams,\n defaultMaxVoices,\n widgetAudioControlService,\n widgetAudioWorkletProcessor,\n} from '../../guest/audio/protocol';\nimport type {\n WidgetAudioControlService,\n WidgetAudioDiagnostic,\n WidgetAudioDiagnosticCode,\n WidgetAudioLimits,\n WidgetAudioMountInfo,\n WidgetAudioState,\n} from '../../guest/audio/protocol';\nimport { widgetAudioWorkletUrl } from './worklet';\n\n/** Structural stand-ins for the Web Audio nodes the engine touches; tests inject fakes. */\nexport interface AudioNodeLike {\n connect(destination: AudioNodeLike): unknown;\n disconnect?(): void;\n}\n\nexport interface AudioContextLike {\n readonly sampleRate: number;\n /** `suspended` | `running` | `closed` for a real context. */\n readonly state: string;\n readonly destination: AudioNodeLike;\n readonly audioWorklet?: { addModule(url: string): Promise<void> };\n /**\n * Fired by a real context whenever the browser suspends or resumes it on its own (autoplay\n * policy, hidden page, a caller calling `suspend()` / `resume()`). Used as a fallback when the\n * context lacks `addEventListener`; fakes may leave it `null`.\n */\n onstatechange?: ((event: Event) => void) | null;\n /** Preferred over `onstatechange`: subscribing must not clobber the caller's own handler. */\n addEventListener?(type: 'statechange', listener: () => void): void;\n removeEventListener?(type: 'statechange', listener: () => void): void;\n}\n\nexport interface AudioWorkletNodeLike extends AudioNodeLike {\n readonly port: MessagePort;\n}\n\nexport interface MessageChannelLike {\n readonly port1: MessagePort;\n readonly port2: MessagePort;\n}\n\n/** Host-side sinks the engine reports into; the widget host owns the sandbox plumbing. */\nexport interface WidgetAudioNotifier {\n /** Hands the direct guest ↔ worklet port to the sandbox. */\n emitPort(port: MessagePort): void;\n emitState(state: WidgetAudioState): void;\n}\n\nexport interface WidgetAudioEngineOptions {\n readonly context: AudioContextLike;\n readonly destination?: AudioNodeLike;\n readonly limits?: Partial<WidgetAudioLimits>;\n readonly report: (code: WidgetAudioDiagnosticCode, instanceId: string, message: string) => void;\n readonly notify: WidgetAudioNotifier;\n /** Loads the audio worklet node; tests or applications may provide their own loader. */\n readonly loadWorklet?: () => Promise<AudioWorkletNodeLike>;\n readonly createChannel?: () => MessageChannelLike;\n readonly createWorkletNode?: (context: AudioContextLike, name: string) => AudioWorkletNodeLike;\n}\n\ninterface InstanceAudio {\n readonly instanceId: string;\n readonly session: string;\n}\n\n/**\n * Host half of the audio path (RFC 0016).\n *\n * Owns the one `AudioWorkletNode`, the session tokens, and the two RPC endpoints that reach the\n * worklet: host controls over the node port, and the direct guest channel it hands to the sandbox.\n * No audio node other than that worklet is created here: tones, mixing and volume all live inside\n * the worklet.\n */\nexport class WidgetAudioEngine {\n readonly #context: AudioContextLike;\n readonly #destination: AudioNodeLike;\n readonly #report: WidgetAudioEngineOptions['report'];\n readonly #notify: WidgetAudioNotifier;\n readonly #limits: WidgetAudioLimits;\n readonly #loadWorklet: (() => Promise<AudioWorkletNodeLike>) | undefined;\n readonly #createChannel: () => MessageChannelLike;\n readonly #createWorkletNode: (context: AudioContextLike, name: string) => AudioWorkletNodeLike;\n readonly #runtimeId = `r${Math.random().toString(36).slice(2, 10)}`;\n readonly #instances = new Map<string, InstanceAudio>();\n #worklet: AudioWorkletNodeLike | undefined;\n #endpoint: RpcEndpoint | undefined;\n #control: RpcProxy<WidgetAudioControlService> | undefined;\n #booting: Promise<boolean> | undefined;\n #available: boolean | undefined;\n #muted = false;\n #suspended = false;\n #sessionCounter = 0;\n #disposed = false;\n #lastState: WidgetAudioState | undefined;\n #detachStateListener: (() => void) | undefined;\n /** Context state moved without an engine call; guests get the same ordered notification. */\n readonly #onContextStateChange = (): void => {\n if (this.#disposed) return;\n if (this.#context.state === 'closed') {\n for (const instanceId of this.#instances.keys()) {\n this.#report('widget/audio-failed', instanceId, 'The host AudioContext was closed.');\n }\n }\n this.#syncState();\n };\n\n constructor(options: WidgetAudioEngineOptions) {\n this.#context = options.context;\n this.#destination = options.destination ?? options.context.destination;\n this.#report = options.report;\n this.#notify = options.notify;\n this.#limits = {\n maxVoices: Math.max(1, Math.floor(options.limits?.maxVoices ?? defaultMaxVoices)),\n maxStreams: Math.max(1, Math.floor(options.limits?.maxStreams ?? defaultMaxStreams)),\n };\n this.#loadWorklet = options.loadWorklet;\n this.#createChannel =\n options.createChannel ??\n (() => {\n const channel = new MessageChannel();\n return { port1: channel.port1, port2: channel.port2 };\n });\n this.#createWorkletNode =\n options.createWorkletNode ??\n ((context, name) => {\n const ctor = (\n globalThis as {\n AudioWorkletNode?: new (\n context: unknown,\n name: string,\n options: unknown,\n ) => AudioWorkletNodeLike;\n }\n ).AudioWorkletNode;\n if (!ctor) throw new Error('AudioWorkletNode is not available');\n return new ctor(context, name, {\n numberOfInputs: 0,\n numberOfOutputs: 1,\n outputChannelCount: [2],\n });\n });\n }\n\n /**\n * Current availability.\n *\n * `unavailable` means \"no audio at all\": the host configured none, the browser lacks\n * `AudioWorklet`, or the worklet module failed to load.\n */\n get state(): WidgetAudioState {\n if (this.#disposed || this.#available === false || this.#context.state === 'closed')\n return 'unavailable';\n if (this.#available !== true || this.#suspended) return 'suspended';\n return this.#context.state === 'running' ? 'running' : 'suspended';\n }\n\n /** Limits in force, so a caller can mirror them in its own UI. */\n get limits(): WidgetAudioLimits {\n return this.#limits;\n }\n\n /**\n * Opens the mount generation of one instance.\n *\n * Resolves once the worklet registered the session token, so the `mount` request that carries it\n * can never arrive after the first guest call of that generation.\n */\n async open(instanceId: string): Promise<WidgetAudioMountInfo> {\n if (this.#disposed) return { state: 'unavailable' };\n const available = await this.#boot();\n if (!available) return { state: 'unavailable' };\n\n this.close(instanceId);\n this.#sessionCounter += 1;\n const session = `${this.#runtimeId}-${this.#sessionCounter}`;\n this.#instances.set(instanceId, { instanceId, session });\n try {\n await this.#control?.openSession({\n session,\n runtimeId: this.#runtimeId,\n instanceId,\n maxVoices: this.#limits.maxVoices,\n maxStreams: this.#limits.maxStreams,\n });\n } catch (error) {\n this.#report(\n 'widget/audio-failed',\n instanceId,\n `The audio worklet rejected the session: ${describe(error)}`,\n );\n }\n this.#syncState();\n return { state: this.state, session };\n }\n\n setMuted(muted: boolean): void {\n this.#muted = muted === true;\n this.#call((control) => control.setMuted(this.#muted));\n }\n\n setInstanceVolume(instanceId: string, volume: number): void {\n if (typeof volume !== 'number') {\n throw new TypeError('WidgetAudioControls.setInstanceVolume expects a number');\n }\n if (!Number.isFinite(volume) || volume < 0 || volume > 1) {\n throw new RangeError('WidgetAudioControls.setInstanceVolume expects a value in [0, 1]');\n }\n const instance = this.#instances.get(instanceId);\n if (!instance) return;\n this.#call((control) => control.setSessionVolume(instance.session, volume));\n }\n\n /** Freezes audio without touching the caller's `AudioContext`. */\n suspend(): void {\n if (this.#disposed || this.#suspended) return;\n this.#suspended = true;\n this.#call((control) => control.suspend());\n this.#syncState();\n }\n\n resume(): void {\n if (this.#disposed) return;\n this.#suspended = false;\n this.#call((control) => control.resume());\n this.#syncState();\n }\n\n /**\n * Closes the instance only when it still belongs to `session`.\n *\n * A mount attempt that lost its id may have opened its own audio generation after the host's\n * cleanup sweep; closing by id alone would tear down the replacement instead.\n */\n closeSession(instanceId: string, session: string): void {\n const instance = this.#instances.get(instanceId);\n if (!instance || instance.session !== session) return;\n this.close(instanceId);\n }\n\n /** Drops one instance: its session token is revoked and the worklet ends its voices and streams. */\n close(instanceId: string): void {\n const instance = this.#instances.get(instanceId);\n if (!instance) return;\n this.#instances.delete(instanceId);\n this.#call((control) => control.closeSession(instance.session));\n }\n\n /**\n * Drops every instance and hands the worklet a fresh guest channel.\n *\n * Called when the sandbox goes away: the old guest port died with it, and the next sandbox needs\n * a port of its own.\n */\n reset(): void {\n for (const instanceId of [...this.#instances.keys()]) {\n this.close(instanceId);\n }\n if (this.#available === true && this.#control !== undefined) {\n void this.#restartRuntime();\n }\n }\n\n dispose(): void {\n if (this.#disposed) return;\n for (const instanceId of [...this.#instances.keys()]) {\n this.close(instanceId);\n }\n // Sent before the flag flips: the worklet drops the runtime, its sessions and its guest port.\n this.#call((control) => control.detachGuestPort(this.#runtimeId));\n this.#disposed = true;\n this.#detachStateListener?.();\n this.#detachStateListener = undefined;\n this.#endpoint?.dispose();\n this.#endpoint = undefined;\n this.#control = undefined;\n const worklet = this.#worklet;\n this.#worklet = undefined;\n if (worklet !== undefined) {\n closePort(worklet.port);\n try {\n worklet.disconnect?.();\n } catch {\n // Already detached.\n }\n }\n }\n\n /** Boots the worklet once; a failure is permanent for the lifetime of the engine. */\n #boot(): Promise<boolean> {\n this.#booting ??= this.#start().catch((error: unknown) => {\n this.#available = false;\n // A load that fails after `dispose()` is not a widget problem and has no live host to hear it.\n if (!this.#disposed) {\n this.#report('widget/audio-failed', '', `Widget audio is unavailable: ${describe(error)}`);\n }\n return false;\n });\n return this.#booting;\n }\n\n async #start(): Promise<boolean> {\n if (\n this.#loadWorklet === undefined &&\n typeof this.#context.audioWorklet?.addModule !== 'function'\n ) {\n this.#available = false;\n return false;\n }\n\n this.#listenForContextState();\n const worklet = await (this.#loadWorklet?.() ?? this.#loadDefaultWorklet());\n if (this.#disposed) {\n // `dispose()` ran while the module was loading: release the node instead of wiring it up.\n closePort(worklet.port);\n try {\n worklet.disconnect?.();\n } catch {\n // Already detached.\n }\n return false;\n }\n this.#worklet = worklet;\n const endpoint = createRpc(worklet.port);\n this.#endpoint = endpoint;\n const control = endpoint.getProxy(widgetAudioControlService, {\n transfer: (member, args) => (member === 'attachGuestPort' ? [args[1] as MessagePort] : []),\n });\n this.#control = control;\n control.onDidDiagnostic((diagnostic) => this.#onDiagnostic(diagnostic));\n worklet.connect(this.#destination);\n await this.#attachRuntime();\n if (this.#suspended) await control.suspend();\n this.#available = true;\n return true;\n }\n\n /**\n * Mirrors the context's own `statechange` onto mounted guests.\n *\n * The caller owns the `AudioContext`, so its state can move without the engine asking: autoplay\n * policy keeping it suspended, the browser suspending a hidden page, or the caller calling\n * `resume()`. Guests read `api.audio.state` and `onStateChange`, so those moves must be forwarded.\n */\n #listenForContextState(): void {\n if (this.#detachStateListener) return;\n const context = this.#context;\n if (typeof context.addEventListener === 'function') {\n context.addEventListener('statechange', this.#onContextStateChange);\n this.#detachStateListener = () =>\n context.removeEventListener?.('statechange', this.#onContextStateChange);\n return;\n }\n if (!('onstatechange' in context)) return;\n // Contexts that only expose the handler property keep the caller's value for `dispose()`.\n const previous = context.onstatechange;\n context.onstatechange = this.#onContextStateChange;\n this.#detachStateListener = () => {\n if (context.onstatechange === this.#onContextStateChange) context.onstatechange = previous;\n };\n }\n\n /** Worklet → host diagnostics, attributed back to the instance that owns the session. */\n #onDiagnostic(diagnostic: WidgetAudioDiagnostic): void {\n const owner = [...this.#instances.values()].find(\n (entry) => entry.session === diagnostic.session,\n );\n // A revoked token means the message is late; the RFC drops it instead of raising diagnostics.\n if (!owner) return;\n this.#report(diagnostic.code, owner.instanceId, diagnostic.message);\n }\n\n async #loadDefaultWorklet(): Promise<AudioWorkletNodeLike> {\n await this.#context.audioWorklet?.addModule(widgetAudioWorkletUrl());\n return this.#createWorkletNode(this.#context, widgetAudioWorkletProcessor);\n }\n\n async #restartRuntime(): Promise<void> {\n const control = this.#control;\n if (control === undefined) return;\n try {\n await control.detachGuestPort(this.#runtimeId);\n } catch {\n // The worklet already forgot the runtime; a new channel follows anyway.\n }\n await this.#attachRuntime();\n }\n\n /** Transfers a fresh port to the worklet and hands the other end to the guest. */\n async #attachRuntime(): Promise<void> {\n const control = this.#control;\n if (control === undefined || this.#disposed) return;\n const channel = this.#createChannel();\n try {\n await control.attachGuestPort(this.#runtimeId, channel.port1);\n } catch (error) {\n closePort(channel.port1);\n closePort(channel.port2);\n this.#report(\n 'widget/audio-failed',\n '',\n `The audio worklet rejected the guest port: ${describe(error)}`,\n );\n return;\n }\n this.#notify.emitPort(channel.port2);\n }\n\n /** Fires one host → worklet call; a missing or closed worklet is not a widget failure. */\n #call(run: (control: RpcProxy<WidgetAudioControlService>) => Promise<unknown>): void {\n const control = this.#control;\n if (control === undefined || this.#disposed) return;\n try {\n void run(control).catch(() => undefined);\n } catch {\n // The endpoint is already closed.\n }\n }\n\n #syncState(): void {\n const next = this.state;\n if (next === this.#lastState) return;\n this.#lastState = next;\n this.#notify.emitState(next);\n }\n}\n\nfunction closePort(port: MessagePort): void {\n try {\n port.close();\n } catch {\n // Already closed.\n }\n}\n\nfunction describe(error: unknown): string {\n if (error instanceof Error && error.message) return error.message;\n return typeof error === 'string' ? error : String(error);\n}\n"],"mappings":";;;;;;AAGA,IAAI;;;;;;;;AASJ,SAAgB,wBAAgC;CAC9C,cAAc,IAAI,gBAAgB,IAAI,KAAK,CAACA,aAAa,GAAG,EAAE,MAAM,kBAAkB,CAAC,CAAC;CACxF,OAAO;AACT;;;;;;;AAQA,eAAsB,yBAAyB,SAAkD;CAC/F,IAAI,OAAO,QAAQ,cAAc,cAAc,YAC7C,MAAM,IAAI,MAAM,6DAA6D;CAE/E,MAAM,QAAQ,aAAa,UAAU,sBAAsB,CAAC;CAC5D,OAAO,IAAI,iBAAiB,SAAS,2BAA2B;AAClE;;;;;;;;;;;ACqDA,IAAa,oBAAb,MAA+B;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,aAAsB,IAAI,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,EAAE;CAChE,6BAAsB,IAAI,IAA2B;CACrD;CACA;CACA;CACA;CACA;CACA,SAAS;CACT,aAAa;CACb,kBAAkB;CAClB,YAAY;CACZ;CACA;;CAEA,8BAA6C;EAC3C,IAAI,KAAK,WAAW;EACpB,IAAI,KAAK,SAAS,UAAU,UAC1B,KAAK,MAAM,cAAc,KAAK,WAAW,KAAK,GAC5C,KAAK,QAAQ,uBAAuB,YAAY,mCAAmC;EAGvF,KAAK,WAAW;CAClB;CAEA,YAAY,SAAmC;EAC7C,KAAK,WAAW,QAAQ;EACxB,KAAK,eAAe,QAAQ,eAAe,QAAQ,QAAQ;EAC3D,KAAK,UAAU,QAAQ;EACvB,KAAK,UAAU,QAAQ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U,KAAK;EACrB,IAAI,YAAY,KAAA,KAAa,KAAK,WAAW;EAC7C,MAAM,UAAU,KAAK,eAAe;EACpC,IAAI;GACF,MAAM,QAAQ,gBAAgB,KAAK,YAAY,QAAQ,KAAK;EAC9D,SAAS,OAAO;GACd,UAAU,QAAQ,KAAK;GACvB,UAAU,QAAQ,KAAK;GACvB,KAAK,QACH,uBACA,IACA,8CAA8C,SAAS,KAAK,GAC9D;GACA;EACF;EACA,KAAK,QAAQ,SAAS,QAAQ,KAAK;CACrC;;CAGA,MAAM,KAA+E;EACnF,MAAM,UAAU,KAAK;EACrB,IAAI,YAAY,KAAA,KAAa,KAAK,WAAW;EAC7C,IAAI;GACF,IAAS,OAAO,CAAC,CAAC,YAAY,KAAA,CAAS;EACzC,QAAQ,CAER;CACF;CAEA,aAAmB;EACjB,MAAM,OAAO,KAAK;EAClB,IAAI,SAAS,KAAK,YAAY;EAC9B,KAAK,aAAa;EAClB,KAAK,QAAQ,UAAU,IAAI;CAC7B;AACF;AAEA,SAAS,UAAU,MAAyB;CAC1C,IAAI;EACF,KAAK,MAAM;CACb,QAAQ,CAER;AACF;AAEA,SAAS,SAAS,OAAwB;CACxC,IAAI,iBAAiB,SAAS,MAAM,SAAS,OAAO,MAAM;CAC1D,OAAO,OAAO,UAAU,WAAW,QAAQ,OAAO,KAAK;AACzD"}
|
package/dist/index.d.ts
CHANGED
|
@@ -295,6 +295,8 @@ export declare interface IWidgetSimulationRuntimeChannel {
|
|
|
295
295
|
deliver(message: IWidgetSimulationPublish): Promise<void>;
|
|
296
296
|
/** Subscribes to simulation publishes; the guest fans them out to its bound instances. */
|
|
297
297
|
onDidPublish(listener: (publish: IWidgetSimulationPublish) => void): () => void;
|
|
298
|
+
/** Waits until earlier simulation publishes have reached this guest. */
|
|
299
|
+
flushPublishes(): Promise<void>;
|
|
298
300
|
}
|
|
299
301
|
|
|
300
302
|
/**
|