@mica-js/widget 0.1.1 → 0.2.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.d.ts CHANGED
@@ -1,16 +1,13 @@
1
1
  import { CanvasBindingCatalog } from '@mica-js/core/canvas';
2
- import { CanvasBindingTarget } from '@mica-js/core/canvas';
3
2
  import { CanvasCommand } from '@mica-js/core/canvas';
4
3
  import { CanvasDocument } from '@mica-js/core/canvas';
4
+ import { DeliveryKind } from '@mica-js/core/canvas';
5
+ import { DeviceSimulationHost } from '@mica-js/simulator';
6
+ import { Disposable } from '@mica-js/core/lifecycle';
7
+ import { Event as Event_2 } from '@mica-js/core/lifecycle';
5
8
  import { PayloadType } from '@mica-js/core/canvas';
6
-
7
- /**
8
- * Default sandbox over `@mica-js/sandbox`.
9
- *
10
- * The import stays dynamic on purpose: consumers that inject their own sandbox never load it, and
11
- * Node-side consumers can import this package without a DOM.
12
- */
13
- export declare const createDefaultWidgetSandbox: WidgetSandboxFactory;
9
+ import { SandboxWorker } from '@mica-js/sandbox';
10
+ import { SandboxWorkerOptions } from '@mica-js/sandbox';
14
11
 
15
12
  /**
16
13
  * Loads every package up front and indexes its widgets under `<packageId>:<widgetId>`.
@@ -23,6 +20,14 @@ export declare function createPackageWidgetProvider(options: PackageWidgetProvid
23
20
  /** Provider over a fixed module table, used for builtin widgets and tests. */
24
21
  export declare function createStaticWidgetProvider(modules: Readonly<Record<string, WidgetModule>>): WidgetProvider;
25
22
 
23
+ /**
24
+ * Loads the packaged processor into `context` and creates its node.
25
+ *
26
+ * Pass it as `getAudioWorklet` wherever a `WidgetHost` or `CanvasEditor` asks for one; hosts that
27
+ * provide no loader of their own use the same processor internally.
28
+ */
29
+ export declare function createWidgetAudioWorklet(context: AudioContext): Promise<AudioWorkletNode>;
30
+
26
31
  /**
27
32
  * Creates the widget host.
28
33
  *
@@ -32,7 +37,92 @@ export declare function createStaticWidgetProvider(modules: Readonly<Record<stri
32
37
  * a crash the next reconciliation starts a fresh sandbox instead of rebuilding instances
33
38
  * automatically.
34
39
  */
35
- export declare function createWidgetHost(options: WidgetHostOptions): WidgetHost;
40
+ export declare function createWidgetHost(options: WidgetHostOptions, createSandbox: WidgetSandboxFactory): WidgetHost;
41
+
42
+ /**
43
+ * Creates the widget host guest worker.
44
+ *
45
+ * This is the guest `WidgetHost` talks to, and it is the same one `@mica-js/canvas-editor`'s
46
+ * `SandboxHostProvider` starts by default. Hosts only start it; the RPC surface is wired by
47
+ * `createWidgetSandboxFromWorker`.
48
+ */
49
+ export declare function createWidgetHostGuestSandbox(options?: SandboxWorkerOptions): SandboxWorker;
50
+
51
+ /** Adapts a provider-created widget worker to WidgetHost's RPC-facing surface. */
52
+ export declare function createWidgetSandboxFromWorker(worker: SandboxWorker, options: WidgetSandboxHostOptions): Promise<WidgetSandbox>;
53
+
54
+ /**
55
+ * Decodes a self-contained `data:` URI to its bytes.
56
+ *
57
+ * `data:` resources never reach `HostFs`: the bytes travel with the reference, so the host decodes
58
+ * them locally. `;base64` payloads are decoded from base64; other payloads are percent-decoded,
59
+ * while characters that need no escaping are encoded as UTF-8. The URI fragment is ignored.
60
+ *
61
+ * @throws TypeError when the URI has no payload separator or the payload is not decodable.
62
+ */
63
+ export declare function decodeDataUri(uri: string): Uint8Array;
64
+
65
+ /**
66
+ * Decodes a self-contained `data:` URI to its text payload.
67
+ *
68
+ * The decoded bytes are read as UTF-8, so a payload that carries binary or malformed UTF-8 is a
69
+ * decode failure rather than replacement characters.
70
+ *
71
+ * @throws TypeError when the URI has no payload separator, the payload is not decodable, or the
72
+ * bytes are not UTF-8.
73
+ */
74
+ export declare function decodeDataUriText(uri: string): string;
75
+
76
+ export { Disposable }
77
+
78
+ export { Event_2 as Event }
79
+
80
+ /** Rebuilds a `HostFsError` from its payload, rejecting codes outside the contract. */
81
+ export declare function fromHostFsErrorPayload(payload: HostFsErrorPayload): HostFsError;
82
+
83
+ /**
84
+ * Host-side, read-only access to the bytes a document references.
85
+ *
86
+ * `read` takes an absolute URI and resolves to the complete bytes of that resource; relative
87
+ * references are resolved by the caller (see `resolveHostUri`) and `data:` URIs are decoded by the
88
+ * caller instead of being passed here. Text decoding, structured parsing and base64 handling stay
89
+ * with the caller. Failures reject with a `HostFsError`.
90
+ */
91
+ export declare interface HostFs {
92
+ read(uri: string): Promise<Uint8Array>;
93
+ }
94
+
95
+ /** Rejection of `HostFs.read`: `code` classifies the failure, `uri` names the resource. */
96
+ export declare class HostFsError extends Error {
97
+ readonly code: HostFsErrorCode;
98
+ readonly uri: string;
99
+ constructor(code: HostFsErrorCode, uri: string, message?: string, options?: HostFsErrorOptions);
100
+ }
101
+
102
+ /** Failure classification of a `HostFs.read` rejection. */
103
+ export declare type HostFsErrorCode = 'FileNotFound' | 'NoPermissions' | 'NoFileSystem' | 'Unavailable';
104
+
105
+ export declare interface HostFsErrorOptions {
106
+ readonly cause?: unknown;
107
+ }
108
+
109
+ /**
110
+ * Structured-clone payload for a `HostFsError` that crosses a thread boundary.
111
+ *
112
+ * The receiving side rebuilds the instance from `code`; `message` keeps the original wording when
113
+ * it survives the transport and falls back to the default message for the code otherwise.
114
+ */
115
+ export declare interface HostFsErrorPayload {
116
+ readonly code: HostFsErrorCode;
117
+ readonly uri: string;
118
+ readonly message?: string;
119
+ }
120
+
121
+ /** Whether `uri` carries a scheme, i.e. is absolute rather than a relative reference. */
122
+ export declare function isAbsoluteHostUri(uri: string): boolean;
123
+
124
+ /** Narrows an unknown rejection to a `HostFsError` created in this realm. */
125
+ export declare function isHostFsError(value: unknown): value is HostFsError;
36
126
 
37
127
  /**
38
128
  * Reads a package manifest, every declared widget definition and its paired implementation.
@@ -59,6 +149,12 @@ export declare interface PortDefinition {
59
149
  readonly description?: string;
60
150
  readonly direction: 'input' | 'output';
61
151
  readonly type: PayloadType;
152
+ /**
153
+ * How publishes become deliveries (RFC 0017). Omitted means the payload type decides:
154
+ * `boolean` / `number` / `vec2d` / `vec3d` are `level`, the text and byte payloads are `message`.
155
+ * The field is orthogonal to `type`, so any combination is valid.
156
+ */
157
+ readonly delivery?: DeliveryKind;
62
158
  }
63
159
 
64
160
  /** Property descriptor from the shared descriptor contract (#7); fields pass through untouched. */
@@ -69,15 +165,50 @@ declare interface PropertyDefinition_2 {
69
165
  }
70
166
  export { PropertyDefinition_2 as PropertyDefinition }
71
167
 
72
- /** One payload a simulation published for an endpoint the canvas can bind to. */
73
- export declare interface SimulationPublish {
74
- readonly target: CanvasBindingTarget;
75
- readonly payload: unknown;
76
- readonly simTime: number;
77
- }
168
+ /**
169
+ * Resolves a document reference against the absolute URI of the document that contains it.
170
+ *
171
+ * - a reference with a scheme is an absolute URI and is returned unchanged;
172
+ * - a reference starting with `/` replaces the path and keeps the base scheme and authority;
173
+ * - any other reference is merged with the base directory and normalized.
174
+ *
175
+ * The result always keeps the scheme and authority of `baseUri`, so a `//host/path` reference
176
+ * stays inside the base authority instead of replacing it. Hosts pass a base URI whose path is
177
+ * not empty; a base with an authority and an empty path resolves relative references under that
178
+ * authority.
179
+ *
180
+ * @throws TypeError when `baseUri` is not an absolute URI.
181
+ */
182
+ export declare function resolveHostUri(baseUri: string, reference: string): string;
183
+
184
+ /** Copies the fields a thread hop must carry; the instance itself does not survive a structured clone. */
185
+ export declare function toHostFsErrorPayload(error: HostFsError): HostFsErrorPayload;
78
186
 
79
- /** ESM guest runtime for widget instances, bundled at build time by `vite.plugins.ts`. */
80
- export declare const WIDGET_RUNTIME_SOURCE: string;
187
+ /**
188
+ * Complete drawing state of one mounted instance (RFC 0018).
189
+ *
190
+ * Every widget event carries this shape, so a subscriber never has to read the host again: geometry
191
+ * and properties change through the same event, `sequence` says whether the bitmap is new.
192
+ */
193
+ export declare interface Widget {
194
+ readonly instanceId: string;
195
+ /** Widget reference: `<packageId>:<widgetId>` or `builtin:<widgetId>`. */
196
+ readonly widget: string;
197
+ /** Top-left corner, logical units. */
198
+ readonly x: number;
199
+ readonly y: number;
200
+ readonly width: number;
201
+ readonly height: number;
202
+ /** Degrees, clockwise, around the rectangle center. */
203
+ readonly rotation: number;
204
+ readonly dpr: number;
205
+ readonly properties: Readonly<Record<string, unknown>>;
206
+ readonly bindings: Readonly<Record<string, WidgetBinding>>;
207
+ /** Latest frame; `undefined` until the instance produced a bitmap. */
208
+ readonly bitmap: ImageBitmap | undefined;
209
+ /** Increments with every frame, for deciding whether a repaint is needed. */
210
+ readonly sequence: number;
211
+ }
81
212
 
82
213
  /**
83
214
  * Reads resources the host prefetched when the instance was mounted. Guests have no network and
@@ -116,6 +247,190 @@ export declare interface WidgetAssetRef {
116
247
  readonly mode: 'file' | 'inline' | 'store';
117
248
  }
118
249
 
250
+ /** Instance-level audio API behind `api.audio`. */
251
+ export declare interface WidgetAudioApi {
252
+ readonly state: WidgetAudioState;
253
+ /** Subscribes to availability changes; the returned function unsubscribes. */
254
+ onStateChange(listener: (state: WidgetAudioState) => void): () => void;
255
+ /** Starts a continuous oscillator. */
256
+ tone(options: WidgetAudioToneOptions): WidgetAudioTone;
257
+ /** Opens a PCM stream. */
258
+ createStream(options: WidgetAudioStreamOptions): WidgetAudioStream;
259
+ }
260
+
261
+ /** `WidgetHost.audio` — controls every instance of one widget host. */
262
+ export declare interface WidgetAudioControls {
263
+ /** Mirror of the state the guest reads from `api.audio.state`. */
264
+ readonly state: WidgetAudioState;
265
+ /** Mutes every instance without touching buffers; PCM keeps flowing into the worklet. */
266
+ setMuted(muted: boolean): void;
267
+ /**
268
+ * Scales one instance inside the worklet.
269
+ *
270
+ * @throws {TypeError} when `volume` is not a number.
271
+ * @throws {RangeError} when it is outside `[0, 1]`.
272
+ */
273
+ setInstanceVolume(instanceId: string, volume: number): void;
274
+ /**
275
+ * Freezes all widget audio, for example while a simulation is paused.
276
+ *
277
+ * Tones go silent and the worklet pauses consumption while keeping the PCM it already buffered.
278
+ * The caller's `AudioContext` is left alone.
279
+ */
280
+ suspend(): void;
281
+ resume(): void;
282
+ }
283
+
284
+ export declare interface WidgetAudioEnded {
285
+ readonly reason: WidgetAudioEndReason;
286
+ }
287
+
288
+ /** Why a tone or stream stopped. */
289
+ export declare type WidgetAudioEndReason = 'finished' | 'stopped' | 'dropped' | 'error' | 'unavailable' | 'disposed';
290
+
291
+ /** Sample layout of a PCM stream. */
292
+ export declare type WidgetAudioFormat = 's16' | 'f32';
293
+
294
+ /** Per-instance ceilings; a host may tighten them through its options. */
295
+ export declare interface WidgetAudioLimits {
296
+ readonly maxVoices: number;
297
+ readonly maxStreams: number;
298
+ }
299
+
300
+ /**
301
+ * Host audio configuration for `createWidgetHost` (RFC 0016).
302
+ *
303
+ * Omit it and `api.audio.state` is `unavailable`: every method still returns a usable handle, but
304
+ * nothing is ever played.
305
+ */ export declare interface WidgetAudioOptions {
306
+ /** Context all audio renders into. The caller owns it; the host never closes it. */
307
+ readonly context: AudioContext;
308
+ /** Where the host's master gain ends up; defaults to `context.destination`. */
309
+ readonly destination?: AudioNode;
310
+ /** Creates the worklet node after the host has created the context. */
311
+ readonly getAudioWorklet?: (context: AudioContext) => Promise<AudioWorkletNode>;
312
+ /** Tightens the defaults (8 voices, 4 PCM streams per instance). */
313
+ readonly limits?: Partial<WidgetAudioLimits>;
314
+ }
315
+
316
+ export declare interface WidgetAudioRampOptions {
317
+ /** Smoothing window in milliseconds, `0`–`10000`; `0` when omitted. */
318
+ readonly rampMs?: number;
319
+ }
320
+
321
+ /** Availability of the host audio path. */
322
+ export declare type WidgetAudioState = 'unavailable' | 'suspended' | 'running';
323
+
324
+ export declare interface WidgetAudioStopOptions {
325
+ /** Fade-out in milliseconds, `0`–`10000`; `0` when omitted. */
326
+ readonly fadeMs?: number;
327
+ }
328
+
329
+ /** Handle for one PCM stream. Every method is safe to call after the stream closed. */
330
+ export declare interface WidgetAudioStream {
331
+ readonly id: string;
332
+ readonly sampleRate: number;
333
+ readonly channels: 1 | 2;
334
+ readonly format: WidgetAudioFormat;
335
+ readonly capacityFrames: number;
336
+ readonly startFrames: number;
337
+ readonly volume: number;
338
+ /** Accepted frames the worklet has not reported as consumed yet. */
339
+ readonly bufferedFrames: number;
340
+ readonly underruns: number;
341
+ readonly dropped: number;
342
+ readonly state: WidgetAudioStreamState;
343
+ /** Settles when the stream finished, was closed or its instance went away. */
344
+ readonly ended: Promise<WidgetAudioEnded>;
345
+ /**
346
+ * Appends one block of interleaved samples.
347
+ *
348
+ * The promise resolves with the worklet's answer: `true` when the whole block entered the ring
349
+ * buffer, `false` when it lacked room and the block was discarded whole. It never means "played".
350
+ * Shape errors are thrown synchronously, before anything is sent.
351
+ */
352
+ write(samples: Int16Array | Float32Array): Promise<boolean>;
353
+ /** Drops everything that has not played yet and keeps the stream open. */
354
+ clear(): void;
355
+ /** Plays the remaining data and then ends with `finished`. Idempotent. */
356
+ end(): void;
357
+ /** Stops immediately and discards the remaining data. Idempotent. */
358
+ close(): void;
359
+ /** Fires once each time the buffer drains to half its capacity. */
360
+ onDrain(listener: () => void): () => void;
361
+ /** Fires when `state` or `underruns` changed. */
362
+ onStatus(listener: (status: WidgetAudioStreamStatus) => void): () => void;
363
+ }
364
+
365
+ export declare interface WidgetAudioStreamOptions {
366
+ /** Integer source rate in Hz, `8000`–`96000`; required. */
367
+ readonly sampleRate: number;
368
+ /** `1` (default) or `2`; multi-channel samples are interleaved. */
369
+ readonly channels?: 1 | 2;
370
+ /** `f32` (default) or `s16`. */
371
+ readonly format?: WidgetAudioFormat;
372
+ /** Worklet buffer window in milliseconds, `50`–`2000`; `500` when omitted. */
373
+ readonly bufferMs?: number;
374
+ /** Frames that must be buffered before (re)starting playback, **not** more than `bufferMs`. */
375
+ readonly startMs?: number;
376
+ /** `0`–`1`; `1` when omitted. */
377
+ readonly volume?: number;
378
+ }
379
+
380
+ /** Playback state of a PCM stream, as the guest sees it. */
381
+ export declare type WidgetAudioStreamState = 'buffering' | 'playing' | 'ended' | 'closed';
382
+
383
+ /** Read-only snapshot of one stream. */
384
+ export declare interface WidgetAudioStreamStatus {
385
+ readonly state: WidgetAudioStreamState;
386
+ readonly underruns: number;
387
+ readonly dropped: number;
388
+ readonly bufferedFrames: number;
389
+ readonly capacityFrames: number;
390
+ }
391
+
392
+ /** Voice handle of a continuous oscillator, with live parameter updates. */
393
+ export declare interface WidgetAudioTone extends WidgetAudioVoice {
394
+ set(settings: WidgetAudioVoiceSettings, options?: WidgetAudioRampOptions): void;
395
+ }
396
+
397
+ export declare interface WidgetAudioToneOptions {
398
+ /** `sine` when omitted. */
399
+ readonly type?: WidgetOscillatorType;
400
+ /** Hz, `(0, 24000]`. */
401
+ readonly frequency: number;
402
+ /** `0`–`1`; `1` when omitted. */
403
+ readonly volume?: number;
404
+ }
405
+
406
+ /** Handle for one voice; closing it is idempotent. */
407
+ export declare interface WidgetAudioVoice {
408
+ readonly id: string;
409
+ /** Settles once the worklet (or the guest, when audio is unavailable) stopped the voice. */
410
+ readonly ended: Promise<WidgetAudioEnded>;
411
+ stop(options?: WidgetAudioStopOptions): void;
412
+ }
413
+
414
+ export declare interface WidgetAudioVoiceSettings {
415
+ readonly volume?: number;
416
+ readonly frequency?: number;
417
+ }
418
+
419
+ /**
420
+ * Blob URL of the packaged `AudioWorkletProcessor` script.
421
+ *
422
+ * The script is bundled and minified into this module while the package is built, so an
423
+ * `AudioContext` can load it through `addModule()` without the package publishing a separate
424
+ * `*.worklet.js` asset. The URL is created once per page and reused by every host.
425
+ */
426
+ export declare function widgetAudioWorkletUrl(): string;
427
+
428
+ /** Endpoint of a widget port: a port of one symbol instance in the bound schematic (RFC 0010). */
429
+ export declare interface WidgetBinding {
430
+ readonly symbol: string;
431
+ readonly port: string;
432
+ }
433
+
119
434
  export declare interface WidgetDefinition {
120
435
  readonly properties: Readonly<Record<string, PropertyDefinition_2>>;
121
436
  readonly ports: Readonly<Record<string, PortDefinition>>;
@@ -133,13 +448,24 @@ export declare interface WidgetDiagnostic {
133
448
  readonly code: WidgetDiagnosticCode;
134
449
  readonly instanceId?: string;
135
450
  readonly widget?: string;
451
+ readonly bindingCode?: string;
452
+ readonly pointer?: string;
136
453
  readonly message: string;
137
454
  }
138
455
 
139
- export declare type WidgetDiagnosticCode = 'widget/runtime-failed' | 'widget/unknown-widget' | 'widget/instance-exists' | 'widget/instance-not-found' | 'widget/mount-failed' | 'widget/render-failed' | 'widget/deliver-failed' | 'widget/asset-failed';
456
+ export declare type WidgetDiagnosticCode = 'widget/runtime-failed' | 'widget/unknown-widget' | 'widget/instance-exists' | 'widget/instance-not-found' | 'widget/mount-failed' | 'widget/binding-failed' | 'widget/render-failed' | 'widget/deliver-failed' | 'widget/asset-failed' | 'widget/audio-failed' | 'widget/audio-limit';
140
457
 
141
458
  /** Default export of a widget implementation module. */
142
- export declare type WidgetFactory = (api: WidgetInstanceApi) => WidgetInstance | void;
459
+ export declare type WidgetFactory = (api: WidgetInstanceApi) => WidgetImplementation | void;
460
+
461
+ /**
462
+ * The widget guest worker script, bundled and minified into this module by
463
+ * `@mica-js/sandbox/vite` while the package itself is built.
464
+ *
465
+ * It is a classic script: every dependency is inlined, so the sandbox can run it without a module
466
+ * loader and the package publishes no separate `*.sandbox.js` file.
467
+ */
468
+ export declare const widgetGuestScript: string;
143
469
 
144
470
  export declare interface WidgetHost {
145
471
  /**
@@ -150,19 +476,31 @@ export declare interface WidgetHost {
150
476
  */
151
477
  getDocument(): CanvasDocument;
152
478
  /**
153
- * Commits an already parsed document and mounts the instances it lists.
479
+ * Commits a document and mounts the instances it lists.
480
+ *
481
+ * Accepts an already parsed `CanvasDocument`, or the absolute URI of a `.cnv` resource. The URI
482
+ * form reads the bytes through `WidgetHostOptions.fs` (a `data:` URI is decoded locally),
483
+ * decodes them as UTF-8 text, parses with `parseCanvas`, and then runs the same validation and
484
+ * mount flow as the parsed form.
154
485
  *
155
- * Parsing stays with the caller (`parseCanvas`): the host still re-validates the snapshot it is
156
- * handed, but it never guesses whether a value is text or a document.
486
+ * The document's `schematic` is resolved against the document URI and loaded through
487
+ * `deviceHost` before any instance mounts (RFC 0018 step 2), regardless of the current host mode.
157
488
  *
158
489
  * Resolves once the instances of this first pass finished mounting. A widget that fails to mount
159
490
  * is reported through `onDiagnostic` and left out of `getLayers()` instead of rejecting this
160
491
  * promise.
161
492
  *
162
- * @throws {SchematicError} when `document` is not a valid `.cnv` document or the bindings do not
163
- * validate; neither the document nor the instances change in that case.
493
+ * Binding endpoint and type diagnostics skip only the affected instances and are reported through
494
+ * `onDiagnostic`; valid instances still mount. Schema, schematic-loading, and other document-level
495
+ * errors reject the call and leave the previous document and instances unchanged.
496
+ * @throws {HostFsError} when reading the URI fails, or when no `fs` is configured for a
497
+ * non-`data:` URI.
498
+ * @throws {TypeError} when the URI is relative or a `data:` URI is malformed.
499
+ * @throws whatever `DeviceSimulationHost.loadSchematic` rejects with when a device host is configured;
500
+ * the document and the instances keep the state they had before the call.
164
501
  */
165
502
  loadDocument(document: CanvasDocument): Promise<void>;
503
+ loadDocument(uri: string): Promise<void>;
166
504
  /**
167
505
  * Applies one command to the current document.
168
506
  *
@@ -170,15 +508,24 @@ export declare interface WidgetHost {
170
508
  * instances runs in the background and never rolls the document back. A rejected command leaves
171
509
  * both the document and the instances untouched.
172
510
  *
173
- * @throws {SchematicError} when the command is invalid or the resulting bindings do not validate.
511
+ * Binding endpoint and type diagnostics skip only affected instances and are reported through
512
+ * `onDiagnostic`; other invalid commands and document-level diagnostics still throw.
174
513
  */
175
514
  applyCommand(command: CanvasCommand): void;
515
+ /** Current widget runtime mode; only `simulation` advances the device host. */
516
+ getMode(): WidgetHostMode;
517
+ /** Switches widget runtime modes and resets the device and widget state. */
518
+ setMode(mode: WidgetHostMode): Promise<void>;
176
519
  /** Subscribes to committed snapshots; returns the unsubscribe function. */
177
520
  onDocumentChange(listener: (document: CanvasDocument) => void): () => void;
178
521
  /**
179
522
  * Drops every instance and mounts the current document again, so widgets restart from their
180
523
  * initial state. Layers are emptied and repopulated.
181
524
  *
525
+ * With a URI-loaded document this re-executes `loadDocument`: the bytes are read and parsed
526
+ * again, and the document's schematic is handed to the device host once more, so the simulation
527
+ * does not keep the state of a killed widget.
528
+ *
182
529
  * Each mount runs the widget factory again (fresh closure, canvas and subscriptions, initial
183
530
  * props), but the guest keeps its module cache: a widget module is evaluated once per session.
184
531
  * Module-level state is therefore not reset — the contract puts instance state in the factory.
@@ -188,59 +535,124 @@ export declare interface WidgetHost {
188
535
  */
189
536
  reset(): Promise<void>;
190
537
  deliver(instanceId: string, port: string, payload: unknown, simTime: number): void;
538
+ /**
539
+ * Hands one input event to an instance.
540
+ *
541
+ * The event is queued and dispatched at the start of the next step (RFC 0018).
542
+ */
191
543
  dispatch(instanceId: string, event: WidgetInputEvent): void;
544
+ /** Bulk instance projection in drawing order; carries no bitmaps. */
545
+ listInstances(): readonly WidgetInstance[];
546
+ /** Fires once the instance is mounted, with its complete state. */
547
+ readonly onDidAddWidget: Event_2<Widget>;
548
+ /** Fires when geometry, properties, bindings, the pixel ratio or the bitmap changed. */
549
+ readonly onDidChangeWidget: Event_2<Widget>;
550
+ /** Fires when an instance is unloaded; the payload is the `instanceId`. */
551
+ readonly onDidRemoveWidget: Event_2<string>;
552
+ /** Fires with the new drawing order; the elements are `instanceId`s. */
553
+ readonly onDidReorderWidgets: Event_2<readonly string[]>;
554
+ /** Requests a full sync: every instance is reported as removed and then added, in current order. */
555
+ invalidate(): void;
192
556
  /** Bitmaps in document order; the same store for the lifetime of the host. */
193
557
  getLayers(): WidgetLayers;
194
558
  /** Changes the device pixel ratio of every layer and repaints all instances. */
195
559
  resize(dpr: number): void;
560
+ /** Freezes the frame clock; the document and the instances stay untouched. */
561
+ pause(): void;
562
+ /** Resumes the frame clock and re-times it from now. */
563
+ resume(): void;
564
+ /**
565
+ * Audio controls for every instance (RFC 0016). Without `WidgetHostOptions.audio` the state stays
566
+ * `unavailable` and the controls are no-ops.
567
+ */
568
+ readonly audio: WidgetAudioControls;
196
569
  /** Terminates the sandbox and closes every bitmap. */
197
570
  dispose(): Promise<void>;
198
571
  }
199
572
 
573
+ /**
574
+ * Frame clock policy. The host decides how much one frame advances; the backlog of a stalled frame
575
+ * is dropped instead of being simulated later.
576
+ */
577
+ export declare interface WidgetHostFrameOptions {
578
+ /** Length of one fixed step, in milliseconds. Defaults to 25 ms. */
579
+ readonly stepMs?: number;
580
+ /** Frame scheduler; the default uses `setTimeout` with the configured step duration. */
581
+ readonly requestFrame?: (callback: () => void) => () => void;
582
+ }
583
+
584
+ export declare type WidgetHostMode = 'edit' | 'simulation';
585
+
200
586
  export declare interface WidgetHostOptions {
201
- readonly provider: WidgetProvider;
587
+ /** Widget definitions and implementations (RFC 0014). Required together with {@link provider}. */
588
+ readonly widgetProvider?: WidgetProvider;
589
+ /** @deprecated Use {@link widgetProvider}. */
590
+ readonly provider?: WidgetProvider;
591
+ /**
592
+ * Simulation runtime kept loaded by the widget host in both edit and simulation modes.
593
+ */
594
+ readonly deviceHost: DeviceSimulationHost;
595
+ /** Initial runtime mode. Defaults to `simulation`. */
596
+ readonly mode?: WidgetHostMode;
597
+ /**
598
+ * Reads the bytes of a document URI for `loadDocument(uri)`. `data:` URIs are decoded locally
599
+ * and never reach `fs`; without this option only `data:` URIs and the parsed-document form work.
600
+ */
601
+ readonly fs?: HostFs;
202
602
  readonly container?: HTMLElement;
203
603
  /** Device pixel ratio for new layers. Defaults to `devicePixelRatio`, or 1 outside a browser. */
204
604
  readonly dpr?: number;
205
605
  /** Receives failures that must not interrupt the caller. */
606
+ readonly onDidReportDiagnostic?: (diagnostic: WidgetDiagnostic) => void;
607
+ /** @deprecated Use {@link onDidReportDiagnostic}. */
206
608
  readonly onDiagnostic?: (diagnostic: WidgetDiagnostic) => void;
207
- /** Receives port payloads published by widgets; topic routing is out of scope here. */
609
+ /** Receives port payloads published by widgets outside every binding. */
610
+ readonly onDidPublish?: (publish: WidgetPublish) => void;
611
+ /** @deprecated Use {@link onDidPublish}. */
208
612
  readonly onPublish?: (publish: WidgetPublish) => void;
209
- /**
210
- * Simulation the host is wired to: device publishes reach the widgets bound to their endpoint,
211
- * and widget publishes reach the device bound to their port. Without it the host only reports
212
- * publishes through `onPublish` and delivers what the host asks for.
213
- */
214
- readonly simulation?: WidgetHostSimulation;
613
+ /** Frame clock policy. */
614
+ readonly frame?: WidgetHostFrameOptions;
215
615
  /**
216
616
  * Prefetches image / binary property values when an instance mounts. Without it nothing is
217
617
  * prefetched and `api.assets.readBinary` rejects.
218
618
  */
219
619
  readonly assets?: WidgetAssetProvider;
220
620
  /**
221
- * Resolves widget definitions and schematic symbols for binding validation.
621
+ * Overrides the binding catalog the host assembles itself (RFC 0018).
222
622
  *
223
- * Without it `loadDocument` / `applyCommand` only run the structural checks of the `.cnv`
224
- * format; the reference checks that need the registry and the schematic are skipped.
623
+ * By default the host validates every `loadDocument` / `applyCommand` against the definitions
624
+ * resolved through `widgetProvider`, the endpoints `deviceHost.getTopics()` reports when a device
625
+ * host is configured, and the schematic the device host loaded.
626
+ *
627
+ * Pass a catalog to validate against a different registry — for example a static list of
628
+ * endpoints before a simulation exists.
225
629
  */
226
630
  readonly catalog?: CanvasBindingCatalog;
227
- /** Replaces the sandbox implementation; the default starts `@mica-js/sandbox` lazily. */
228
- readonly sandbox?: WidgetSandboxFactory;
631
+ /**
632
+ * One end of the direct device channel between the widget guest and the device guest (RFC 0018).
633
+ *
634
+ * Handed to the first sandbox the host starts and never reused: a guest restarted after a crash
635
+ * runs without it, and the host relays topic traffic as before.
636
+ */
637
+ readonly devicePort?: MessagePort;
638
+ /**
639
+ * Enables `api.audio`. Without it every widget sees `api.audio.state === 'unavailable'`.
640
+ *
641
+ * The host never closes the `AudioContext`: the caller keeps ownership, including the user
642
+ * gesture that unlocks it.
643
+ */
644
+ readonly audio?: WidgetAudioOptions;
229
645
  }
230
646
 
231
647
  /**
232
- * Simulation the host is connected to, so bound endpoints reach the widgets without a routing
233
- * layer in between.
234
- *
235
- * Both sides live on this thread: the host resolves the binding synchronously and hands the
236
- * payload to the widget sandbox, which is the only hop left (a microtask, not a worker). A
237
- * `DeviceSimExecutor` from `@mica-js/simulator` satisfies this interface structurally.
648
+ * Object a widget factory may return. Every hook is optional, so a pure-logic widget can return
649
+ * nothing at all; an instance without `render` still produces one blank frame per repaint.
238
650
  */
239
- export declare interface WidgetHostSimulation {
240
- /** Publishes from the simulation; the returned function unsubscribes. */
241
- onPublish(listener: (publish: SimulationPublish) => void): () => void;
242
- /** Forwards a widget payload to the endpoint its port is bound to. */
243
- deliver(target: CanvasBindingTarget, payload: unknown): void;
651
+ export declare interface WidgetImplementation {
652
+ /** Draws using logical units; the context is already scaled by the device pixel ratio. */
653
+ render?(context: OffscreenCanvasRenderingContext2D): void;
654
+ input?(event: WidgetInputEvent): void;
655
+ dispose?(): void;
244
656
  }
245
657
 
246
658
  /** Pointer or keyboard input forwarded to one instance. */
@@ -262,16 +674,8 @@ export declare interface WidgetInputEvent {
262
674
  readonly shiftKey?: boolean;
263
675
  }
264
676
 
265
- /**
266
- * Object a widget factory may return. Every hook is optional, so a pure-logic widget can return
267
- * nothing at all; an instance without `render` still produces one blank frame per repaint.
268
- */
269
- export declare interface WidgetInstance {
270
- /** Draws using logical units; the context is already scaled by the device pixel ratio. */
271
- render?(context: OffscreenCanvasRenderingContext2D): void;
272
- input?(event: WidgetInputEvent): void;
273
- dispose?(): void;
274
- }
677
+ /** Bulk projection of a mounted instance; the same shape without the bitmap (RFC 0018). */
678
+ export declare type WidgetInstance = Omit<Widget, 'bitmap'>;
275
679
 
276
680
  /**
277
681
  * Per-instance API handed to a widget factory. Sizes are logical units: the guest runtime applies
@@ -285,13 +689,15 @@ export declare interface WidgetInstanceApi {
285
689
  readonly props: Readonly<Record<string, unknown>>;
286
690
  /** Prefetched image / binary resources for this instance. */
287
691
  readonly assets: WidgetAssetApi;
692
+ /** Voices, oscillators and PCM streams (RFC 0016). */
693
+ readonly audio: WidgetAudioApi;
288
694
  /** Subscribes to one input port; the returned function unsubscribes. */
289
695
  subscribe(port: string, listener: WidgetPortListener): () => void;
290
696
  /**
291
697
  * Sends a payload out of one output port.
292
698
  *
293
- * `simTime` is the simulation time the widget reacted to. The current host has no simulation
294
- * clock, so an omitted value is published as `0`.
699
+ * `simTime` is the simulation time the widget reacted to; an omitted value takes the last time
700
+ * the device host reported.
295
701
  */
296
702
  publish(port: string, payload: unknown, simTime?: number): void;
297
703
  /** Requests a repaint; repeated calls in the same tick coalesce into one frame. */
@@ -340,7 +746,9 @@ export declare class WidgetLoadError extends Error {
340
746
  constructor(code: WidgetLoadErrorCode, message: string, options?: WidgetLoadErrorOptions);
341
747
  }
342
748
 
343
- export declare type WidgetLoadErrorCode = 'widget/package-not-found' | 'widget/invalid-manifest' | 'widget/invalid-definition' | 'widget/no-implementation' | 'widget/not-self-contained' | 'widget/load-failed';
749
+ export declare type WidgetLoadErrorCode = 'widget/package-not-found' | 'widget/invalid-manifest' | 'widget/invalid-definition' | 'widget/no-implementation' | 'widget/not-self-contained' | 'widget/load-failed'
750
+ /** A descriptor field carries a value outside its closed set (RFC 0017 `delivery`). */
751
+ | 'schema/invalid-value';
344
752
 
345
753
  export declare interface WidgetLoadErrorOptions {
346
754
  /** Package id, when the package was already identified. */
@@ -358,6 +766,9 @@ export declare interface WidgetModule {
358
766
  readonly code: string;
359
767
  }
360
768
 
769
+ /** Waveforms the worklet synthesizes for `api.audio.tone()`. */
770
+ export declare type WidgetOscillatorType = 'sine' | 'square' | 'triangle' | 'sawtooth';
771
+
361
772
  export declare interface WidgetPackage {
362
773
  readonly id: string;
363
774
  readonly version: string;
@@ -388,20 +799,50 @@ export declare interface WidgetPublish {
388
799
 
389
800
  /**
390
801
  * Minimal sandbox surface the host depends on. The default implementation wraps
391
- * `@mica-js/sandbox` through `createSandbox`; tests inject a fake with the same shape.
802
+ * `@mica-js/sandbox` through `SandboxWorker` plus a typed RPC adapter; tests inject a fake with the same shape.
392
803
  */
393
804
  export declare interface WidgetSandbox {
394
805
  readonly state: 'ready' | 'terminated';
395
806
  call(method: string, ...args: unknown[]): Promise<unknown>;
396
807
  on(type: string, listener: (payload: unknown) => void): () => void;
808
+ /** Sends a host event into the guest; events are the lane for widget-level notifications. */
809
+ emit?(type: string, payload?: unknown, transfer?: readonly Transferable[]): void;
810
+ /** Host → guest audio lane; without it `api.audio` stays `unavailable`. */
811
+ readonly audio?: WidgetSandboxAudio;
812
+ /**
813
+ * The guest holds the direct device channel (RFC 0018), so it delivers widget publishes to the
814
+ * device guest and fans device publishes out to its instances itself. The host then keeps the
815
+ * binding map, the level cache and the diagnostics, and stops relaying topic traffic.
816
+ */
817
+ readonly directDevice?: boolean;
397
818
  terminate(reason?: string): Promise<void>;
398
819
  }
399
820
 
821
+ /**
822
+ * Typed host → guest audio lane (RFC 0016).
823
+ *
824
+ * `attachPort` transfers the direct worker ↔ worklet port; `setState` pushes availability changes
825
+ * that happen after the instance mounted.
826
+ */
827
+ export declare interface WidgetSandboxAudio {
828
+ attachPort(port: MessagePort): void;
829
+ setState(state: WidgetAudioState): void;
830
+ }
831
+
400
832
  export declare type WidgetSandboxFactory = (options: WidgetSandboxHostOptions) => Promise<WidgetSandbox>;
401
833
 
402
834
  export declare interface WidgetSandboxHostOptions {
403
835
  /** Element that hosts the hidden sandbox iframe. */
404
836
  readonly container?: HTMLElement;
837
+ /** Host file system exposed to the generated sandbox runtime. */
838
+ readonly fs?: HostFs;
839
+ /**
840
+ * One end of the direct device channel, transferred to the guest with its first message.
841
+ *
842
+ * A port can be transferred once, so the host hands it to the first sandbox it starts; a sandbox
843
+ * started after a crash runs without one and the host relays topic traffic again.
844
+ */
845
+ readonly devicePort?: MessagePort;
405
846
  }
406
847
 
407
848
  export { }