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