@mica-js/widget 0.0.0-stage → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,1228 @@
1
+ import { CANVAS_VERSION, applyCanvasCommand, assertCanvasBindings, parseCanvas, parsePayloadType } from "@mica-js/core/canvas";
2
+ //#region src/errors.ts
3
+ /** Thrown when a widget reference resolves to a package that cannot be turned into a module. */
4
+ var WidgetLoadError = class extends Error {
5
+ code;
6
+ packageId;
7
+ path;
8
+ constructor(code, message, options = {}) {
9
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
10
+ this.name = "WidgetLoadError";
11
+ this.code = code;
12
+ this.packageId = options.packageId;
13
+ this.path = options.path;
14
+ }
15
+ };
16
+ //#endregion
17
+ //#region src/load-package.ts
18
+ var PACKAGE_JSON = "package.json";
19
+ var JSON_EXTENSION = ".json";
20
+ var IMPLEMENTATION_EXTENSION = ".js";
21
+ /** Package and widget ids are stable kebab-case identifiers (see #1). */
22
+ var ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
23
+ /**
24
+ * Reads a package manifest, every declared widget definition and its paired implementation.
25
+ * Only the three declared path kinds are read; the package is never enumerated.
26
+ *
27
+ * @throws {WidgetLoadError}
28
+ */
29
+ async function loadWidgetPackage(files) {
30
+ const manifest = await readManifest(files);
31
+ const modules = {};
32
+ const sources = [];
33
+ for (const entry of manifest.widgets) {
34
+ const definition = await readDefinition(files, manifest.id, entry);
35
+ const implementationPath = toImplementationPath(entry.path);
36
+ const code = await readImplementation(files, manifest.id, entry.id, implementationPath);
37
+ modules[entry.id] = {
38
+ definition,
39
+ code
40
+ };
41
+ sources.push([entry.id, code]);
42
+ }
43
+ const contentHash = await sha256Hex(JSON.stringify(sources), manifest.id);
44
+ return {
45
+ id: manifest.id,
46
+ version: manifest.version,
47
+ contentHash,
48
+ modules
49
+ };
50
+ }
51
+ async function readManifest(files) {
52
+ let bytes;
53
+ try {
54
+ bytes = await files.read(PACKAGE_JSON);
55
+ } catch (cause) {
56
+ throw new WidgetLoadError("widget/package-not-found", `Package ${JSON.stringify(files.label)} has no readable ${PACKAGE_JSON}.`, {
57
+ path: PACKAGE_JSON,
58
+ cause
59
+ });
60
+ }
61
+ const manifest = requireObject(parseJson(bytes, "widget/invalid-manifest", PACKAGE_JSON, void 0, PACKAGE_JSON), "widget/invalid-manifest", `${PACKAGE_JSON} must be a JSON object`, void 0, PACKAGE_JSON);
62
+ const id = manifest["name"];
63
+ if (typeof id !== "string" || !ID_PATTERN.test(id)) throw new WidgetLoadError("widget/invalid-manifest", `${PACKAGE_JSON} must declare a kebab-case "name".`, { path: PACKAGE_JSON });
64
+ const version = manifest["version"];
65
+ if (typeof version !== "string" || version.length === 0) throw new WidgetLoadError("widget/invalid-manifest", `Package ${JSON.stringify(id)} must declare a non-empty "version".`, {
66
+ packageId: id,
67
+ path: PACKAGE_JSON
68
+ });
69
+ const widgetsValue = manifest["widgets"];
70
+ const widgets = widgetsValue === void 0 ? {} : requireObject(widgetsValue, "widget/invalid-manifest", `Package ${JSON.stringify(id)} "widgets" must be an object`, id, PACKAGE_JSON);
71
+ return {
72
+ id,
73
+ version,
74
+ widgets: Object.keys(widgets).sort().map((widgetId) => readEntry(widgets[widgetId], widgetId, id))
75
+ };
76
+ }
77
+ function readEntry(value, widgetId, packageId) {
78
+ if (!ID_PATTERN.test(widgetId)) throw new WidgetLoadError("widget/invalid-manifest", `Package ${JSON.stringify(packageId)} declares widget id ${JSON.stringify(widgetId)}; ids must be kebab-case.`, {
79
+ packageId,
80
+ path: PACKAGE_JSON
81
+ });
82
+ const entry = requireObject(value, "widget/invalid-manifest", `Widget ${JSON.stringify(widgetId)} entry must be an object`, packageId, PACKAGE_JSON);
83
+ const path = entry["path"];
84
+ if (typeof path !== "string") throw new WidgetLoadError("widget/invalid-manifest", `Widget ${JSON.stringify(widgetId)} must declare a string "path".`, {
85
+ packageId,
86
+ path: PACKAGE_JSON
87
+ });
88
+ const problem = packagePathProblem(path);
89
+ if (problem !== void 0) throw new WidgetLoadError("widget/invalid-manifest", `Widget ${JSON.stringify(widgetId)} path ${JSON.stringify(path)} ${problem}.`, {
90
+ packageId,
91
+ path
92
+ });
93
+ if (!path.endsWith(JSON_EXTENSION)) throw new WidgetLoadError("widget/invalid-manifest", `Widget ${JSON.stringify(widgetId)} path ${JSON.stringify(path)} must point at a ${JSON_EXTENSION} description.`, {
94
+ packageId,
95
+ path
96
+ });
97
+ return {
98
+ id: widgetId,
99
+ path,
100
+ displayName: optionalString(entry, "displayName", widgetId, packageId),
101
+ description: optionalString(entry, "description", widgetId, packageId)
102
+ };
103
+ }
104
+ async function readDefinition(files, packageId, entry) {
105
+ let bytes;
106
+ try {
107
+ bytes = await files.read(entry.path);
108
+ } catch (cause) {
109
+ throw new WidgetLoadError("widget/invalid-manifest", `Widget ${JSON.stringify(entry.id)} declares a missing definition at ${JSON.stringify(entry.path)}.`, {
110
+ packageId,
111
+ path: entry.path,
112
+ cause
113
+ });
114
+ }
115
+ const record = requireObject(parseJson(bytes, "widget/invalid-definition", entry.path, packageId, entry.path), "widget/invalid-definition", `Widget definition ${JSON.stringify(entry.path)} must be a JSON object`, packageId, entry.path);
116
+ return {
117
+ properties: readProperties(record["properties"], packageId, entry.path),
118
+ ports: readPorts(record["ports"], packageId, entry.path),
119
+ ...entry.displayName === void 0 ? {} : { displayName: entry.displayName },
120
+ ...entry.description === void 0 ? {} : { description: entry.description }
121
+ };
122
+ }
123
+ function readProperties(value, packageId, path) {
124
+ if (value === void 0) return createRecord();
125
+ const record = requireObject(value, "widget/invalid-definition", `"properties" in ${JSON.stringify(path)} must be an object`, packageId, path);
126
+ const properties = createRecord();
127
+ for (const [key, raw] of Object.entries(record)) {
128
+ if (isUnsafeRecordKey(key)) continue;
129
+ const descriptor = requireObject(raw, "widget/invalid-definition", `Property ${JSON.stringify(key)} in ${JSON.stringify(path)} must be an object`, packageId, path);
130
+ const type = descriptor["type"];
131
+ if (typeof type !== "string" || type.length === 0) throw new WidgetLoadError("widget/invalid-definition", `Property ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare a non-empty string "type".`, {
132
+ packageId,
133
+ path
134
+ });
135
+ properties[key] = {
136
+ ...descriptor,
137
+ type
138
+ };
139
+ }
140
+ return properties;
141
+ }
142
+ function readPorts(value, packageId, path) {
143
+ if (value === void 0) return createRecord();
144
+ const record = requireObject(value, "widget/invalid-definition", `"ports" in ${JSON.stringify(path)} must be an object`, packageId, path);
145
+ const ports = createRecord();
146
+ for (const [key, raw] of Object.entries(record)) {
147
+ if (isUnsafeRecordKey(key)) continue;
148
+ const descriptor = requireObject(raw, "widget/invalid-definition", `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must be an object`, packageId, path);
149
+ const direction = descriptor["direction"];
150
+ if (direction !== "input" && direction !== "output") throw new WidgetLoadError("widget/invalid-definition", `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare "direction" as "input" or "output".`, {
151
+ packageId,
152
+ path
153
+ });
154
+ const typeName = descriptor["type"];
155
+ if (typeof typeName !== "string") throw new WidgetLoadError("widget/invalid-definition", `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare a string "type".`, {
156
+ packageId,
157
+ path
158
+ });
159
+ const type = parsePayloadType(typeName);
160
+ if (type === void 0) throw new WidgetLoadError("widget/invalid-definition", `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} declares unknown payload type ${JSON.stringify(typeName)}.`, {
161
+ packageId,
162
+ path
163
+ });
164
+ const title = portText(descriptor, "title", key, packageId, path);
165
+ const description = portText(descriptor, "description", key, packageId, path);
166
+ ports[key] = {
167
+ direction,
168
+ type,
169
+ ...title === void 0 ? {} : { title },
170
+ ...description === void 0 ? {} : { description }
171
+ };
172
+ }
173
+ return ports;
174
+ }
175
+ async function readImplementation(files, packageId, widgetId, path) {
176
+ try {
177
+ return decode(await files.read(path));
178
+ } catch (cause) {
179
+ throw new WidgetLoadError("widget/no-implementation", `Widget ${JSON.stringify(widgetId)} in package ${JSON.stringify(packageId)} has no implementation at ${JSON.stringify(path)}.`, {
180
+ packageId,
181
+ path,
182
+ cause
183
+ });
184
+ }
185
+ }
186
+ /** Rejects absolute paths, drive letters, backslashes and escaping `..` segments. */
187
+ function packagePathProblem(path) {
188
+ if (path.length === 0) return "must not be empty";
189
+ if (path.startsWith("/")) return "must be relative to the package root";
190
+ if (/^[A-Za-z]:/.test(path)) return "must not carry a drive letter";
191
+ if (path.includes("\\")) return "must use POSIX separators";
192
+ if (path.split("/").includes("..")) return "must stay inside the package";
193
+ }
194
+ function toImplementationPath(definitionPath) {
195
+ return definitionPath.slice(0, -5) + IMPLEMENTATION_EXTENSION;
196
+ }
197
+ /** Reads an optional manifest field; failures always point at `package.json`, where the field lives. */
198
+ function optionalString(record, key, widgetId, packageId) {
199
+ const value = record[key];
200
+ if (value === void 0) return;
201
+ if (typeof value !== "string") throw new WidgetLoadError("widget/invalid-manifest", `Widget ${JSON.stringify(widgetId)} "${key}" in ${PACKAGE_JSON} must be a string.`, {
202
+ packageId,
203
+ path: PACKAGE_JSON
204
+ });
205
+ return value;
206
+ }
207
+ function portText(record, key, portId, packageId, path) {
208
+ const value = record[key];
209
+ if (value === void 0) return;
210
+ if (typeof value !== "string") throw new WidgetLoadError("widget/invalid-definition", `Port ${JSON.stringify(portId)} "${key}" in ${JSON.stringify(path)} must be a string.`, {
211
+ packageId,
212
+ path
213
+ });
214
+ return value;
215
+ }
216
+ function parseJson(bytes, code, what, packageId, path) {
217
+ try {
218
+ return JSON.parse(decode(bytes));
219
+ } catch (cause) {
220
+ throw new WidgetLoadError(code, `${what} is not valid JSON.`, {
221
+ path,
222
+ cause,
223
+ ...packageId === void 0 ? {} : { packageId }
224
+ });
225
+ }
226
+ }
227
+ function requireObject(value, code, message, packageId, path) {
228
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new WidgetLoadError(code, `${message}.`, {
229
+ path,
230
+ ...packageId === void 0 ? {} : { packageId }
231
+ });
232
+ return value;
233
+ }
234
+ function decode(bytes) {
235
+ return new TextDecoder().decode(bytes);
236
+ }
237
+ /**
238
+ * Record for keys taken from untrusted definition JSON: no inherited setter can intercept an
239
+ * assignment, so a declared entry can never become an object prototype.
240
+ */
241
+ function createRecord() {
242
+ return Object.create(null);
243
+ }
244
+ /** `__proto__` is never a stable widget key, and on any object it would shadow the prototype. */
245
+ function isUnsafeRecordKey(key) {
246
+ return key === "__proto__";
247
+ }
248
+ async function sha256Hex(text, packageId) {
249
+ const subtle = globalThis.crypto?.subtle;
250
+ if (subtle === void 0) throw new WidgetLoadError("widget/load-failed", "Computing the widget package content hash requires Web Crypto (globalThis.crypto.subtle).", {
251
+ packageId,
252
+ path: PACKAGE_JSON
253
+ });
254
+ const digest = await subtle.digest("SHA-256", new TextEncoder().encode(text));
255
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
256
+ }
257
+ //#endregion
258
+ //#region src/provider/static.ts
259
+ /** Provider over a fixed module table, used for builtin widgets and tests. */
260
+ function createStaticWidgetProvider(modules) {
261
+ const index = new Map(Object.entries(modules));
262
+ return { resolve(ref) {
263
+ return Promise.resolve(index.get(ref));
264
+ } };
265
+ }
266
+ //#endregion
267
+ //#region src/provider/package.ts
268
+ /**
269
+ * Loads every package up front and indexes its widgets under `<packageId>:<widgetId>`.
270
+ * Resolution never touches the file system again, and unknown references return `undefined`.
271
+ *
272
+ * @throws {WidgetLoadError}
273
+ */
274
+ async function createPackageWidgetProvider(options) {
275
+ const filesList = Array.isArray(options.files) ? options.files : [options.files];
276
+ const index = /* @__PURE__ */ new Map();
277
+ const packageIds = /* @__PURE__ */ new Set();
278
+ for (const files of filesList) {
279
+ const widgetPackage = await loadWidgetPackage(withPathCache(files));
280
+ if (packageIds.has(widgetPackage.id)) throw new WidgetLoadError("widget/invalid-manifest", `Package id ${JSON.stringify(widgetPackage.id)} is provided more than once.`, {
281
+ packageId: widgetPackage.id,
282
+ path: "package.json"
283
+ });
284
+ packageIds.add(widgetPackage.id);
285
+ for (const [widgetId, module] of Object.entries(widgetPackage.modules)) index.set(`${widgetPackage.id}:${widgetId}`, module);
286
+ }
287
+ return { resolve(ref) {
288
+ return Promise.resolve(index.get(ref));
289
+ } };
290
+ }
291
+ /** Reads each path at most once for the lifetime of the provider. */
292
+ function withPathCache(files) {
293
+ const cache = /* @__PURE__ */ new Map();
294
+ return {
295
+ label: files.label,
296
+ read(path) {
297
+ const cached = cache.get(path);
298
+ if (cached !== void 0) return cached;
299
+ const pending = files.read(path);
300
+ cache.set(path, pending);
301
+ return pending;
302
+ }
303
+ };
304
+ }
305
+ //#endregion
306
+ //#region src/runtime/protocol.ts
307
+ /**
308
+ * Guest event names. The sandbox reserves the `mica:` namespace for its own traffic: guest events
309
+ * with that prefix never reach host listeners, and `sandbox.on('mica:...')` throws. Widget traffic
310
+ * therefore lives in the `widget:` namespace.
311
+ */
312
+ var WIDGET_FRAME_EVENT = "widget:frame";
313
+ var WIDGET_PUBLISH_EVENT = "widget:publish";
314
+ var WIDGET_ERROR_EVENT = "widget:error";
315
+ /** A resource the guest could not hand to a widget; non-fatal, the instance keeps running. */
316
+ var WIDGET_ASSET_FAILED_EVENT = "widget:asset-failed";
317
+ /** Guest methods the host reaches through `sandbox.call()`. */
318
+ var WIDGET_LOAD_METHOD = "load";
319
+ var WIDGET_MOUNT_METHOD = "mount";
320
+ var WIDGET_UNMOUNT_METHOD = "unmount";
321
+ var WIDGET_RESIZE_METHOD = "resize";
322
+ var WIDGET_SET_PROPERTIES_METHOD = "set-properties";
323
+ var WIDGET_DELIVER_METHOD = "deliver";
324
+ var WIDGET_POINTER_METHOD = "pointer";
325
+ /**
326
+ * Releases every instance without terminating the guest. Widget modules stay evaluated, so the next
327
+ * `load` reuses their factories and only fresh instances are created.
328
+ */
329
+ var WIDGET_RESET_RUNTIME_METHOD = "reset-runtime";
330
+ //#endregion
331
+ //#region src/runtime/props.ts
332
+ function isPlainObject(value) {
333
+ if (typeof value !== "object" || value === null) return false;
334
+ const prototype = Object.getPrototypeOf(value);
335
+ return prototype === Object.prototype || prototype === null;
336
+ }
337
+ /**
338
+ * Deep-copies plain data and freezes every container on the way back up. Typed arrays and other
339
+ * objects are returned untouched: they are not part of the JSON-shaped property format, and
340
+ * freezing a typed array with elements throws.
341
+ */
342
+ function cloneFrozen(value) {
343
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => cloneFrozen(item)));
344
+ if (isPlainObject(value)) {
345
+ const entries = [];
346
+ for (const key of Object.keys(value)) entries.push([key, cloneFrozen(value[key])]);
347
+ return Object.freeze(Object.fromEntries(entries));
348
+ }
349
+ return value;
350
+ }
351
+ function isAssetMode(value) {
352
+ return value === "file" || value === "inline" || value === "store";
353
+ }
354
+ /**
355
+ * Merges `definition.properties[*].default` under the props a document supplied.
356
+ *
357
+ * A key present in `props` wins, even when its value is `undefined`; a key is only filled from the
358
+ * definition when the descriptor declares `default` itself, so `default: null` and "no default"
359
+ * stay distinguishable. Defaults are cloned and deeply frozen per instance, so a widget cannot
360
+ * mutate the definition or leak changes into another instance.
361
+ */
362
+ function mergeProperties(properties, props) {
363
+ const merged = /* @__PURE__ */ new Map();
364
+ for (const key of Object.keys(properties ?? {})) {
365
+ const descriptor = properties?.[key];
366
+ if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, "default")) continue;
367
+ merged.set(key, cloneFrozen(descriptor.default));
368
+ }
369
+ for (const key of Object.keys(props ?? {})) merged.set(key, props?.[key]);
370
+ return Object.freeze(Object.fromEntries(merged));
371
+ }
372
+ /**
373
+ * Collects image / binary property values (`{ src, mode }`) from nested objects and arrays.
374
+ * Results are keyed by `src`, so one resource referenced twice is only read once.
375
+ */
376
+ function collectAssetRefs(value, found = /* @__PURE__ */ new Map(), seen = /* @__PURE__ */ new Set()) {
377
+ if (typeof value !== "object" || value === null) return found;
378
+ if (seen.has(value)) return found;
379
+ seen.add(value);
380
+ if (Array.isArray(value)) {
381
+ for (const item of value) collectAssetRefs(item, found, seen);
382
+ return found;
383
+ }
384
+ if (!isPlainObject(value)) return found;
385
+ const candidate = value;
386
+ if (typeof candidate.src === "string" && isAssetMode(candidate.mode)) {
387
+ if (!found.has(candidate.src)) found.set(candidate.src, {
388
+ src: candidate.src,
389
+ mode: candidate.mode
390
+ });
391
+ }
392
+ for (const key of Object.keys(value)) collectAssetRefs(value[key], found, seen);
393
+ return found;
394
+ }
395
+ //#endregion
396
+ //#region src/host/layers.ts
397
+ /**
398
+ * Layer table owned by the host. Records mutate in place, so callers holding a layer from `get()`
399
+ * or `list()` observe later frames without re-reading the table.
400
+ */
401
+ var WidgetLayerStore = class {
402
+ #records = /* @__PURE__ */ new Map();
403
+ #listeners = /* @__PURE__ */ new Set();
404
+ list() {
405
+ return [...this.#records.values()];
406
+ }
407
+ get(instanceId) {
408
+ return this.#records.get(instanceId);
409
+ }
410
+ subscribe(listener) {
411
+ this.#listeners.add(listener);
412
+ return () => {
413
+ this.#listeners.delete(listener);
414
+ };
415
+ }
416
+ add(init) {
417
+ this.remove(init.instanceId);
418
+ const record = {
419
+ instanceId: init.instanceId,
420
+ width: init.width,
421
+ height: init.height,
422
+ dpr: init.dpr,
423
+ bitmap: void 0,
424
+ sequence: 0
425
+ };
426
+ this.#records.set(init.instanceId, record);
427
+ this.#emit({
428
+ type: "added",
429
+ instanceId: init.instanceId
430
+ });
431
+ return record;
432
+ }
433
+ setSize(instanceId, width, height) {
434
+ const record = this.#records.get(instanceId);
435
+ if (!record || record.width === width && record.height === height) return;
436
+ record.width = width;
437
+ record.height = height;
438
+ this.#emit({
439
+ type: "updated",
440
+ instanceId
441
+ });
442
+ }
443
+ setDpr(instanceId, dpr) {
444
+ const record = this.#records.get(instanceId);
445
+ if (!record || record.dpr === dpr) return;
446
+ record.dpr = dpr;
447
+ this.#emit({
448
+ type: "updated",
449
+ instanceId
450
+ });
451
+ }
452
+ /** Installs a frame, closing the one it replaces, and bumps the sequence. */
453
+ setBitmap(instanceId, bitmap) {
454
+ const record = this.#records.get(instanceId);
455
+ if (!record) {
456
+ closeBitmap(bitmap);
457
+ return;
458
+ }
459
+ const previous = record.bitmap;
460
+ record.bitmap = bitmap;
461
+ record.sequence += 1;
462
+ closeBitmap(previous);
463
+ this.#emit({
464
+ type: "updated",
465
+ instanceId
466
+ });
467
+ }
468
+ remove(instanceId) {
469
+ const record = this.#records.get(instanceId);
470
+ if (!record) return;
471
+ this.#records.delete(instanceId);
472
+ closeBitmap(record.bitmap);
473
+ record.bitmap = void 0;
474
+ this.#emit({
475
+ type: "removed",
476
+ instanceId
477
+ });
478
+ }
479
+ /**
480
+ * Rewrites drawing order to `instanceIds` without touching a frame.
481
+ *
482
+ * Ids the table does not hold are skipped, and records the caller did not list keep their
483
+ * relative order at the end: a mount in flight owns a layer before the document instance that
484
+ * created it is reconciled.
485
+ */
486
+ reorder(instanceIds) {
487
+ const ordered = /* @__PURE__ */ new Map();
488
+ for (const instanceId of instanceIds) {
489
+ const record = this.#records.get(instanceId);
490
+ if (record !== void 0) ordered.set(instanceId, record);
491
+ }
492
+ for (const [instanceId, record] of this.#records) if (!ordered.has(instanceId)) ordered.set(instanceId, record);
493
+ if (sameOrder([...this.#records.keys()], [...ordered.keys()])) return;
494
+ this.#records.clear();
495
+ for (const [instanceId, record] of ordered) this.#records.set(instanceId, record);
496
+ this.#emit({ type: "reordered" });
497
+ }
498
+ clear() {
499
+ for (const instanceId of [...this.#records.keys()]) this.remove(instanceId);
500
+ }
501
+ #emit(change) {
502
+ for (const listener of [...this.#listeners]) try {
503
+ listener(change);
504
+ } catch (error) {
505
+ console.error("[@mica-js/widget] layer listener threw", error);
506
+ }
507
+ }
508
+ };
509
+ /** Closes a bitmap without letting a double close escape. */
510
+ function closeBitmap(bitmap) {
511
+ if (!bitmap) return;
512
+ try {
513
+ bitmap.close();
514
+ } catch {}
515
+ }
516
+ function sameOrder(left, right) {
517
+ return left.length === right.length && left.every((id, index) => id === right[index]);
518
+ }
519
+ //#endregion
520
+ //#region src/internal/runtime-source.ts
521
+ /** ESM guest runtime for widget instances, bundled at build time by `vite.plugins.ts`. */
522
+ var WIDGET_RUNTIME_SOURCE = "//#region src/runtime/protocol.ts\n/**\n* Guest event names. The sandbox reserves the `mica:` namespace for its own traffic: guest events\n* with that prefix never reach host listeners, and `sandbox.on('mica:...')` throws. Widget traffic\n* therefore lives in the `widget:` namespace.\n*/\nconst WIDGET_FRAME_EVENT = \"widget:frame\";\nconst WIDGET_PUBLISH_EVENT = \"widget:publish\";\nconst WIDGET_ERROR_EVENT = \"widget:error\";\n/** A resource the guest could not hand to a widget; non-fatal, the instance keeps running. */\nconst WIDGET_ASSET_FAILED_EVENT = \"widget:asset-failed\";\n/** Guest methods the host reaches through `sandbox.call()`. */\nconst WIDGET_LOAD_METHOD = \"load\";\nconst WIDGET_MOUNT_METHOD = \"mount\";\nconst WIDGET_UNMOUNT_METHOD = \"unmount\";\nconst WIDGET_RESIZE_METHOD = \"resize\";\nconst WIDGET_SET_PROPERTIES_METHOD = \"set-properties\";\nconst WIDGET_DELIVER_METHOD = \"deliver\";\nconst WIDGET_POINTER_METHOD = \"pointer\";\n/**\n* Releases every instance without terminating the guest. Widget modules stay evaluated, so the next\n* `load` reuses their factories and only fresh instances are created.\n*/\nconst WIDGET_RESET_RUNTIME_METHOD = \"reset-runtime\";\n//#endregion\n//#region src/runtime/props.ts\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n/**\n* Deep-copies plain data and freezes every container on the way back up. Typed arrays and other\n* objects are returned untouched: they are not part of the JSON-shaped property format, and\n* freezing a typed array with elements throws.\n*/\nfunction cloneFrozen(value) {\n if (Array.isArray(value)) return Object.freeze(value.map((item) => cloneFrozen(item)));\n if (isPlainObject(value)) {\n const entries = [];\n for (const key of Object.keys(value)) entries.push([key, cloneFrozen(value[key])]);\n return Object.freeze(Object.fromEntries(entries));\n }\n return value;\n}\n/**\n* Merges `definition.properties[*].default` under the props a document supplied.\n*\n* A key present in `props` wins, even when its value is `undefined`; a key is only filled from the\n* definition when the descriptor declares `default` itself, so `default: null` and \"no default\"\n* stay distinguishable. Defaults are cloned and deeply frozen per instance, so a widget cannot\n* mutate the definition or leak changes into another instance.\n*/\nfunction mergeProperties(properties, props) {\n const merged = /* @__PURE__ */ new Map();\n for (const key of Object.keys(properties ?? {})) {\n const descriptor = properties?.[key];\n if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, \"default\")) continue;\n merged.set(key, cloneFrozen(descriptor.default));\n }\n for (const key of Object.keys(props ?? {})) merged.set(key, props?.[key]);\n return Object.freeze(Object.fromEntries(merged));\n}\n//#endregion\n//#region src/runtime/worker-entry.ts\nconst DEFAULT_DPR = 1;\n/**\n* Guest entry point: the sandbox module loader looks for this export.\n*\n* The runtime is also reusable from tests, because it owns no module-level state.\n*/\nfunction setup(ctx) {\n const runtime = createWidgetRuntime(ctx);\n ctx.handle(WIDGET_LOAD_METHOD, (request) => runtime.load(request));\n ctx.handle(WIDGET_MOUNT_METHOD, (request) => runtime.mount(request));\n ctx.handle(WIDGET_UNMOUNT_METHOD, (instanceId) => runtime.unmount(instanceId));\n ctx.handle(WIDGET_RESIZE_METHOD, (instanceId, width, height, dpr) => runtime.resize(instanceId, width, height, dpr));\n ctx.handle(WIDGET_SET_PROPERTIES_METHOD, (instanceId, props) => runtime.setProperties(instanceId, props));\n ctx.handle(WIDGET_DELIVER_METHOD, (instanceId, port, payload, simTime) => runtime.deliver(instanceId, port, payload, simTime));\n ctx.handle(WIDGET_POINTER_METHOD, (instanceId, event) => runtime.pointer(instanceId, event));\n ctx.handle(WIDGET_RESET_RUNTIME_METHOD, () => runtime.resetRuntime());\n ctx.signal.addEventListener(\"abort\", () => runtime.dispose(), { once: true });\n}\n/** Creates an isolated runtime instance; each sandbox (and each test) gets its own. */\nfunction createWidgetRuntime(ctx, options = {}) {\n const importModule = options.importModule ?? importBlobModule;\n const factories = /* @__PURE__ */ new Map();\n const definitions = /* @__PURE__ */ new Map();\n const pendingFactories = /* @__PURE__ */ new Map();\n const sessions = /* @__PURE__ */ new Map();\n const dirty = /* @__PURE__ */ new Set();\n let scheduled = false;\n let disposed = false;\n function report(phase, instanceId, error) {\n const payload = {\n instanceId,\n phase,\n error: {\n name: errorName(error),\n message: errorMessage(error)\n }\n };\n try {\n ctx.emit(WIDGET_ERROR_EVENT, payload);\n } catch {}\n }\n function invalidate(session) {\n if (session.failed || session.disposed || disposed) return;\n dirty.add(session);\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(flush);\n }\n function flush() {\n scheduled = false;\n const pending = [...dirty];\n dirty.clear();\n for (const session of pending) paint(session);\n }\n function paint(session) {\n if (session.failed || session.disposed || disposed) return;\n const { context, canvas } = session;\n if (typeof context.setTransform === \"function\") {\n context.setTransform(1, 0, 0, 1, 0, 0);\n context.clearRect(0, 0, canvas.width, canvas.height);\n context.setTransform(session.dpr, 0, 0, session.dpr, 0, 0);\n }\n const render = session.instance?.render;\n if (typeof render === \"function\") try {\n render.call(session.instance, context);\n } catch (error) {\n session.failed = true;\n dirty.delete(session);\n report(\"render\", session.instanceId, error);\n return;\n }\n commit(session);\n }\n function commit(session) {\n let bitmap;\n try {\n bitmap = session.canvas.transferToImageBitmap();\n } catch (error) {\n session.failed = true;\n report(\"render\", session.instanceId, error);\n return;\n }\n const payload = {\n instanceId: session.instanceId,\n bitmap,\n width: session.width,\n height: session.height,\n dpr: session.dpr\n };\n try {\n ctx.emit(WIDGET_FRAME_EVENT, payload, [bitmap]);\n } catch {\n closeBitmap(bitmap);\n }\n }\n function requireSession(instanceId) {\n const session = sessions.get(instanceId);\n if (!session) throw new Error(`Widget instance ${JSON.stringify(instanceId)} is not mounted`);\n return session;\n }\n function createSession(request, definition) {\n const canvas = createCanvas(request.width, request.height, request.dpr);\n const properties = definition?.properties ?? {};\n return {\n instanceId: request.instanceId,\n width: toLogicalSize(request.width),\n height: toLogicalSize(request.height),\n dpr: toDpr(request.dpr),\n props: mergeProperties(properties, request.props),\n properties,\n assets: toAssetMap(request.assets),\n reportedAssets: /* @__PURE__ */ new Set(),\n canvas,\n context: contextOf(canvas),\n subscriptions: /* @__PURE__ */ new Map(),\n instance: void 0,\n failed: false,\n disposed: false\n };\n }\n function reportAssetFailure(session, src, message) {\n if (session.disposed || disposed || session.reportedAssets.has(src)) return;\n session.reportedAssets.add(src);\n const payload = {\n instanceId: session.instanceId,\n src,\n error: {\n name: \"Error\",\n message\n }\n };\n try {\n ctx.emit(WIDGET_ASSET_FAILED_EVENT, payload);\n } catch {}\n }\n function readAsset(session, src) {\n if (typeof src !== \"string\") return Promise.reject(/* @__PURE__ */ new TypeError(\"Widget asset src must be a string\"));\n const bytes = session.assets.get(src);\n if (bytes !== void 0 && !session.disposed && !disposed) return Promise.resolve(new Uint8Array(bytes));\n const message = `Widget asset ${JSON.stringify(src)} was not prefetched`;\n if (session.disposed || disposed) return Promise.reject(new Error(message));\n reportAssetFailure(session, src, message);\n return Promise.reject(new Error(message));\n }\n function createApi(session) {\n return {\n instanceId: session.instanceId,\n get width() {\n return session.width;\n },\n get height() {\n return session.height;\n },\n get props() {\n return session.props;\n },\n assets: { readBinary: (src) => readAsset(session, src) },\n subscribe(port, listener) {\n if (session.disposed || typeof listener !== \"function\") return () => {};\n let listeners = session.subscriptions.get(port);\n if (!listeners) {\n listeners = /* @__PURE__ */ new Set();\n session.subscriptions.set(port, listeners);\n }\n listeners.add(listener);\n return () => {\n session.subscriptions.get(port)?.delete(listener);\n };\n },\n publish(port, payload, simTime) {\n if (session.disposed || disposed) return;\n const message = {\n instanceId: session.instanceId,\n port,\n payload,\n simTime: toSimTime(simTime)\n };\n try {\n ctx.emit(WIDGET_PUBLISH_EVENT, message);\n } catch (error) {\n report(\"deliver\", session.instanceId, error);\n }\n },\n invalidate() {\n invalidate(session);\n }\n };\n }\n function release(session) {\n session.disposed = true;\n dirty.delete(session);\n session.subscriptions.clear();\n const instance = session.instance;\n session.instance = void 0;\n if (instance && typeof instance.dispose === \"function\") try {\n instance.dispose();\n } catch (error) {\n report(\"render\", session.instanceId, error);\n }\n session.assets.clear();\n session.canvas.width = 1;\n session.canvas.height = 1;\n }\n async function evaluate(ref, code) {\n const loaded = await importModule(code);\n const factory = loaded && typeof loaded === \"object\" ? loaded.default : void 0;\n if (typeof factory !== \"function\") throw new Error(`Widget ${JSON.stringify(ref)} must default-export a factory function`);\n return factory;\n }\n return {\n async load(request) {\n const packages = Array.isArray(request.packages) ? request.packages : [];\n let failure;\n let failed = false;\n for (const pkg of packages) {\n const modules = pkg.modules;\n if (!modules || typeof modules !== \"object\") continue;\n for (const widgetId of Object.keys(modules)) {\n const widgetModule = modules[widgetId];\n if (!widgetModule) continue;\n const ref = `${pkg.id}:${widgetId}`;\n if (factories.has(ref)) continue;\n try {\n let pending = pendingFactories.get(ref);\n if (!pending) {\n pending = evaluate(ref, widgetModule.code);\n pendingFactories.set(ref, pending);\n }\n factories.set(ref, await pending);\n definitions.set(ref, widgetModule.definition);\n } catch (error) {\n if (!failed) {\n failure = error;\n failed = true;\n }\n } finally {\n pendingFactories.delete(ref);\n }\n }\n }\n if (failed) throw failure;\n },\n mount(request) {\n if (disposed) throw new Error(\"The widget runtime is disposed\");\n const { instanceId, widget } = request;\n if (sessions.has(instanceId)) throw new Error(`Widget instance ${JSON.stringify(instanceId)} is already mounted`);\n const factory = factories.get(widget);\n if (!factory) throw new Error(`Widget ${JSON.stringify(widget)} is not loaded`);\n const session = createSession(request, definitions.get(widget));\n sessions.set(instanceId, session);\n try {\n session.instance = toWidgetInstance(factory(createApi(session)));\n } catch (error) {\n sessions.delete(instanceId);\n release(session);\n report(\"mount\", instanceId, error);\n throw error instanceof Error ? error : new Error(String(error));\n }\n dirty.delete(session);\n paint(session);\n },\n unmount(instanceId) {\n const session = sessions.get(instanceId);\n if (!session) return;\n sessions.delete(instanceId);\n release(session);\n },\n resize(instanceId, width, height, dpr) {\n const session = requireSession(instanceId);\n session.width = toLogicalSize(width);\n session.height = toLogicalSize(height);\n session.dpr = toDpr(dpr);\n session.canvas.width = toPixelSize(width, session.dpr);\n session.canvas.height = toPixelSize(height, session.dpr);\n dirty.delete(session);\n paint(session);\n },\n setProperties(instanceId, props) {\n const session = requireSession(instanceId);\n session.props = mergeProperties(session.properties, props);\n invalidate(session);\n },\n deliver(instanceId, port, payload, simTime) {\n const listeners = requireSession(instanceId).subscriptions.get(port);\n if (!listeners || listeners.size === 0) return;\n const meta = { simTime };\n for (const listener of [...listeners]) try {\n listener(payload, meta);\n } catch (error) {\n report(\"deliver\", instanceId, error);\n }\n },\n pointer(instanceId, event) {\n const session = requireSession(instanceId);\n if (session.failed || session.disposed) return;\n const handler = session.instance?.input;\n if (typeof handler !== \"function\") return;\n try {\n handler.call(session.instance, event);\n } catch (error) {\n report(\"deliver\", instanceId, error);\n }\n },\n resetRuntime() {\n if (disposed) return;\n dirty.clear();\n for (const session of [...sessions.values()]) {\n sessions.delete(session.instanceId);\n release(session);\n }\n sessions.clear();\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n dirty.clear();\n for (const session of [...sessions.values()]) release(session);\n sessions.clear();\n factories.clear();\n definitions.clear();\n pendingFactories.clear();\n }\n };\n}\nfunction createCanvas(width, height, dpr) {\n return new OffscreenCanvas(toPixelSize(width, dpr), toPixelSize(height, dpr));\n}\nfunction contextOf(canvas) {\n const context = canvas.getContext(\"2d\");\n if (!context) throw new Error(\"The widget runtime needs a 2D context\");\n return context;\n}\nfunction toWidgetInstance(value) {\n return value && typeof value === \"object\" ? value : {};\n}\nfunction toLogicalSize(value) {\n return Number.isFinite(value) && value > 0 ? value : 0;\n}\nfunction toDpr(value) {\n return Number.isFinite(value) && value > 0 ? value : DEFAULT_DPR;\n}\nfunction toPixelSize(logical, dpr) {\n return Math.max(1, Math.round(toLogicalSize(logical) * toDpr(dpr)));\n}\nfunction toAssetMap(assets) {\n const map = /* @__PURE__ */ new Map();\n if (typeof assets !== \"object\" || assets === null) return map;\n for (const key of Object.keys(assets)) {\n const bytes = assets[key];\n if (bytes instanceof Uint8Array) map.set(key, new Uint8Array(bytes));\n }\n return map;\n}\nfunction toSimTime(value) {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\nfunction closeBitmap(bitmap) {\n try {\n bitmap.close();\n } catch {}\n}\nfunction errorName(error) {\n return error instanceof Error && error.name ? error.name : \"Error\";\n}\nfunction errorMessage(error) {\n if (error instanceof Error && error.message) return error.message;\n return typeof error === \"string\" ? error : String(error);\n}\nfunction importBlobModule(code) {\n const url = URL.createObjectURL(new Blob([code], { type: \"text/javascript\" }));\n return import(\n /* @vite-ignore */\n url\n).finally(() => URL.revokeObjectURL(url));\n}\n//#endregion\nexport { createWidgetRuntime, setup };\n";
523
+ //#endregion
524
+ //#region src/host/sandbox.ts
525
+ /**
526
+ * Default sandbox over `@mica-js/sandbox`.
527
+ *
528
+ * The import stays dynamic on purpose: consumers that inject their own sandbox never load it, and
529
+ * Node-side consumers can import this package without a DOM.
530
+ */
531
+ var createDefaultWidgetSandbox = async (options) => {
532
+ const { createSandbox } = await import("@mica-js/sandbox");
533
+ const handle = await createSandbox({
534
+ name: "mica-widget-runtime",
535
+ source: {
536
+ type: "module",
537
+ code: WIDGET_RUNTIME_SOURCE
538
+ },
539
+ captureConsole: false,
540
+ ...options.container === void 0 ? {} : { container: options.container }
541
+ });
542
+ return {
543
+ get state() {
544
+ return handle.state;
545
+ },
546
+ call: (method, ...args) => handle.request(method, args),
547
+ on: (type, listener) => handle.on(type, listener),
548
+ terminate: (reason) => handle.terminate(reason)
549
+ };
550
+ };
551
+ //#endregion
552
+ //#region src/host/create-widget-host.ts
553
+ /** Host state before any document was loaded. */
554
+ var EMPTY_DOCUMENT = {
555
+ version: CANVAS_VERSION,
556
+ widgets: []
557
+ };
558
+ /** Startup or shutdown failure; already reported, so call sites must not report it twice. */
559
+ var WidgetRuntimeError = class extends Error {
560
+ constructor(message, options) {
561
+ super(message, options);
562
+ this.name = "WidgetRuntimeError";
563
+ }
564
+ };
565
+ /**
566
+ * The instance was removed (or the host disposed) while its mount was in flight. Rejecting keeps
567
+ * `mount()` honest instead of resolving for an instance that no longer has a layer.
568
+ */
569
+ var WidgetMountCancelledError = class extends Error {
570
+ constructor(instanceId) {
571
+ super(`Mount of widget instance "${instanceId}" was cancelled before it finished`);
572
+ this.name = "WidgetMountCancelledError";
573
+ }
574
+ };
575
+ /**
576
+ * Creates the widget host.
577
+ *
578
+ * The document is the single source of truth: instances are mounted, resized, repropped and
579
+ * reordered to match it. The sandbox starts lazily on the first instance and every concurrent mount
580
+ * shares that one startup, so a host with no instances never pays for an iframe and a worker. After
581
+ * a crash the next reconciliation starts a fresh sandbox instead of rebuilding instances
582
+ * automatically.
583
+ */
584
+ function createWidgetHost(options) {
585
+ return new WidgetHostImpl(options);
586
+ }
587
+ var WidgetHostImpl = class {
588
+ #provider;
589
+ #container;
590
+ #onDiagnostic;
591
+ #onPublish;
592
+ #assets;
593
+ #catalog;
594
+ #simulation;
595
+ #createSandbox;
596
+ #layerStore = new WidgetLayerStore();
597
+ #instances = /* @__PURE__ */ new Map();
598
+ #detachers = [];
599
+ #documentListeners = /* @__PURE__ */ new Set();
600
+ #document = EMPTY_DOCUMENT;
601
+ #unsubscribeSimulation;
602
+ #reconcilePending = false;
603
+ /** The next coordination pass has to reset the guest before it syncs instances. */
604
+ #resetPending = false;
605
+ #reconcilePass;
606
+ /** Identifies the drain that owns {@link #reconcilePass}; only that drain may release it. */
607
+ #reconcileOwner = 0;
608
+ #sandbox;
609
+ #starting;
610
+ #disposing;
611
+ #disposed = false;
612
+ #dpr;
613
+ constructor(options) {
614
+ this.#provider = options.provider;
615
+ this.#container = options.container;
616
+ this.#onDiagnostic = options.onDiagnostic;
617
+ this.#onPublish = options.onPublish;
618
+ this.#assets = options.assets;
619
+ this.#catalog = options.catalog;
620
+ this.#simulation = options.simulation;
621
+ this.#createSandbox = options.sandbox ?? createDefaultWidgetSandbox;
622
+ this.#dpr = options.dpr ?? currentDevicePixelRatio();
623
+ this.#unsubscribeSimulation = this.#simulation?.onPublish((publish) => {
624
+ this.#onSimulationPublish(publish);
625
+ });
626
+ }
627
+ getDocument() {
628
+ return this.#document;
629
+ }
630
+ getLayers() {
631
+ return this.#layerStore;
632
+ }
633
+ async loadDocument(document) {
634
+ const parsed = parseCanvas(document);
635
+ this.#assertBindings(parsed);
636
+ this.#commit(parsed);
637
+ const pass = this.#scheduleReconcile();
638
+ this.#emitDocument(parsed);
639
+ await pass;
640
+ }
641
+ applyCommand(command) {
642
+ const document = applyCanvasCommand(this.#document, command);
643
+ this.#assertBindings(document);
644
+ this.#commit(document);
645
+ this.#scheduleReconcile();
646
+ this.#emitDocument(document);
647
+ }
648
+ onDocumentChange(listener) {
649
+ this.#documentListeners.add(listener);
650
+ return () => {
651
+ this.#documentListeners.delete(listener);
652
+ };
653
+ }
654
+ reset() {
655
+ if (this.#disposed) return Promise.reject(new WidgetRuntimeError("Widget host is disposed"));
656
+ this.#instances.clear();
657
+ this.#layerStore.clear();
658
+ this.#resetPending = true;
659
+ return this.#scheduleReconcile();
660
+ }
661
+ deliver(instanceId, port, payload, simTime) {
662
+ if (!this.#requireInstance(instanceId)) return;
663
+ this.#fire("widget/deliver-failed", WIDGET_DELIVER_METHOD, [
664
+ instanceId,
665
+ port,
666
+ payload,
667
+ simTime
668
+ ], instanceId);
669
+ }
670
+ dispatch(instanceId, event) {
671
+ if (!this.#requireInstance(instanceId)) return;
672
+ this.#fire("widget/deliver-failed", WIDGET_POINTER_METHOD, [instanceId, event], instanceId);
673
+ }
674
+ resize(dpr) {
675
+ if (!Number.isFinite(dpr) || dpr <= 0 || dpr === this.#dpr) return;
676
+ this.#dpr = dpr;
677
+ for (const layer of this.#layerStore.list()) {
678
+ this.#layerStore.setDpr(layer.instanceId, dpr);
679
+ this.#fire("widget/render-failed", WIDGET_RESIZE_METHOD, [
680
+ layer.instanceId,
681
+ layer.width,
682
+ layer.height,
683
+ dpr
684
+ ], layer.instanceId);
685
+ }
686
+ }
687
+ dispose() {
688
+ const pending = this.#disposing ?? this.#shutdown();
689
+ this.#disposing = pending;
690
+ return pending;
691
+ }
692
+ /** Runs the binding checks both document entry points share; nothing needs them without a catalog. */
693
+ #assertBindings(document) {
694
+ assertCanvasBindings(document, this.#catalog === void 0 ? {} : { catalog: this.#catalog });
695
+ }
696
+ /**
697
+ * Makes `document` the new snapshot and drops the instances it no longer lists.
698
+ *
699
+ * Removal is synchronous on purpose: a mount still in flight for a removed id has to be cancelled
700
+ * right away, while the coordination pass that would have removed it may be blocked on it.
701
+ */
702
+ #commit(document) {
703
+ this.#document = document;
704
+ const live = new Set(document.widgets.map((widget) => widget.id));
705
+ for (const instanceId of [...this.#instances.keys()]) if (!live.has(instanceId)) this.#unmount(instanceId);
706
+ }
707
+ /**
708
+ * Queues a coordination pass and returns the running queue.
709
+ *
710
+ * A pass reads {@link document} per instance, so everything committed while it waits is coalesced
711
+ * into the next iteration; the promise settles only once the queue has caught up.
712
+ *
713
+ * The drain starts on a microtask instead of from here: {@link #syncInstances} notifies the layer
714
+ * store synchronously from inside a guest await, and a subscriber that applies a command from that
715
+ * notification would otherwise re-enter while the slot below is still empty and start a second,
716
+ * concurrent drain.
717
+ */
718
+ #scheduleReconcile() {
719
+ this.#reconcilePending = true;
720
+ this.#reconcilePass ??= Promise.resolve().then(() => this.#drainReconcile());
721
+ return this.#reconcilePass;
722
+ }
723
+ async #drainReconcile() {
724
+ const owner = ++this.#reconcileOwner;
725
+ try {
726
+ while (this.#reconcilePending && !this.#disposed) {
727
+ this.#reconcilePending = false;
728
+ if (this.#resetPending) {
729
+ this.#resetPending = false;
730
+ await this.#resetGuestRuntime();
731
+ }
732
+ await this.#syncInstances();
733
+ }
734
+ } finally {
735
+ if (this.#reconcileOwner === owner) {
736
+ this.#reconcilePending = false;
737
+ this.#reconcilePass = void 0;
738
+ }
739
+ }
740
+ }
741
+ /** Mounts, resizes, sets properties and reorders instances to match the document. */
742
+ async #syncInstances() {
743
+ for (const { id: instanceId } of this.#document.widgets) {
744
+ if (this.#disposed) return;
745
+ const widget = this.#document.widgets.find((entry) => entry.id === instanceId);
746
+ if (widget === void 0) continue;
747
+ await this.#syncInstance(widget);
748
+ }
749
+ this.#layerStore.reorder(this.#document.widgets.map((widget) => widget.id));
750
+ }
751
+ async #syncInstance(widget) {
752
+ const existing = this.#instances.get(widget.id);
753
+ if (existing === void 0) {
754
+ await this.#mount(widget);
755
+ return;
756
+ }
757
+ if (existing.widget !== widget.widget) {
758
+ this.#unmount(widget.id);
759
+ await this.#mount(widget);
760
+ return;
761
+ }
762
+ const placement = placementOf(widget);
763
+ if (placement.width !== existing.placement.width || placement.height !== existing.placement.height) this.#update(widget.id, {
764
+ width: placement.width,
765
+ height: placement.height
766
+ });
767
+ existing.placement = placement;
768
+ const props = widget.properties ?? {};
769
+ if (!sameProperties(existing.props, props)) {
770
+ if (this.#referencesUnprefetchedAsset(existing, props)) {
771
+ this.#unmount(widget.id);
772
+ await this.#mount(widget);
773
+ return;
774
+ }
775
+ this.#setProperties(widget.id, props);
776
+ }
777
+ }
778
+ #referencesUnprefetchedAsset(existing, props) {
779
+ if (this.#assets === void 0) return false;
780
+ for (const src of collectAssetRefs(props).keys()) if (!existing.assets.has(src)) return true;
781
+ return false;
782
+ }
783
+ /**
784
+ * Mounts one document instance. Failures stay inside that instance: the mount attempt already
785
+ * reported its own diagnostic, and the document is never rolled back for it.
786
+ */
787
+ async #mount(widget) {
788
+ try {
789
+ await this.#startInstance(widget);
790
+ } catch {}
791
+ }
792
+ async #startInstance(widget) {
793
+ const { id: instanceId, widget: ref } = widget;
794
+ if (this.#disposed) {
795
+ this.#report("widget/runtime-failed", "The widget host is disposed.", {
796
+ instanceId,
797
+ widget: ref
798
+ });
799
+ throw new WidgetRuntimeError("Widget host is disposed");
800
+ }
801
+ if (this.#instances.has(instanceId)) {
802
+ this.#report("widget/instance-exists", `Widget instance "${instanceId}" is already mounted.`, {
803
+ instanceId,
804
+ widget: ref
805
+ });
806
+ return;
807
+ }
808
+ const record = {
809
+ widget: ref,
810
+ token: Symbol(instanceId),
811
+ placement: placementOf(widget),
812
+ props: widget.properties ?? {},
813
+ assets: /* @__PURE__ */ new Set()
814
+ };
815
+ this.#instances.set(instanceId, record);
816
+ this.#layerStore.add({
817
+ instanceId,
818
+ width: widget.width,
819
+ height: widget.height,
820
+ dpr: this.#dpr
821
+ });
822
+ this.#layerStore.reorder(this.#document.widgets.map((entry) => entry.id));
823
+ let mounted = false;
824
+ try {
825
+ mounted = await this.#mountInstance(instanceId, ref, record);
826
+ } finally {
827
+ if (!mounted) this.#forget(instanceId, record);
828
+ }
829
+ }
830
+ /**
831
+ * Runs one mount attempt; every await re-checks that this attempt still owns the id.
832
+ *
833
+ * @returns always `true`; a cancelled attempt throws instead of reporting success.
834
+ */
835
+ async #mountInstance(instanceId, ref, record) {
836
+ let module;
837
+ try {
838
+ module = await this.#provider.resolve(ref);
839
+ } catch (error) {
840
+ this.#report("widget/mount-failed", `Widget "${ref}" could not be resolved: ${describeError(error)}`, {
841
+ instanceId,
842
+ widget: ref
843
+ });
844
+ throw error;
845
+ }
846
+ const resolved = module === void 0 ? void 0 : splitRef(ref);
847
+ if (module === void 0 || resolved === void 0) {
848
+ this.#report("widget/unknown-widget", module === void 0 ? `No widget is registered as "${ref}".` : `Widget reference "${ref}" must use the "<package>:<widget>" form.`, {
849
+ instanceId,
850
+ widget: ref
851
+ });
852
+ return false;
853
+ }
854
+ this.#requireOwnership(instanceId, record);
855
+ const sandbox = await this.#ensureSandbox();
856
+ this.#requireOwnership(instanceId, record);
857
+ try {
858
+ await sandbox.call(WIDGET_LOAD_METHOD, { packages: [{
859
+ id: resolved.packageId,
860
+ modules: { [resolved.widgetId]: {
861
+ definition: module.definition,
862
+ code: module.code
863
+ } }
864
+ }] });
865
+ this.#requireOwnership(instanceId, record);
866
+ const props = mergeProperties(module.definition?.properties, record.props);
867
+ const assets = await this.#prefetchAssets(instanceId, ref, props);
868
+ record.assets = new Set(collectAssetRefs(props).keys());
869
+ this.#requireOwnership(instanceId, record);
870
+ const layer = this.#layerStore.get(instanceId);
871
+ if (!layer) throw new WidgetMountCancelledError(instanceId);
872
+ await sandbox.call(WIDGET_MOUNT_METHOD, {
873
+ instanceId,
874
+ widget: ref,
875
+ width: layer.width,
876
+ height: layer.height,
877
+ dpr: layer.dpr,
878
+ props,
879
+ ...assets === void 0 ? {} : { assets }
880
+ });
881
+ } catch (error) {
882
+ if (error instanceof WidgetRuntimeError) throw error;
883
+ if (error instanceof WidgetMountCancelledError) throw error;
884
+ if (this.#disposed) throw new WidgetMountCancelledError(instanceId);
885
+ if (this.#isTerminated()) {
886
+ this.#failRuntime("The widget sandbox terminated during mount.");
887
+ throw error;
888
+ }
889
+ this.#report("widget/mount-failed", `Widget "${ref}" failed to mount: ${describeError(error)}`, {
890
+ instanceId,
891
+ widget: ref
892
+ });
893
+ throw error;
894
+ }
895
+ if (!this.#owns(instanceId, record)) {
896
+ if (!this.#instances.has(instanceId)) await releaseGuestInstance(sandbox, instanceId);
897
+ throw new WidgetMountCancelledError(instanceId);
898
+ }
899
+ return true;
900
+ }
901
+ #unmount(instanceId) {
902
+ const instance = this.#instances.get(instanceId);
903
+ if (!instance) {
904
+ this.#report("widget/instance-not-found", `Widget instance "${instanceId}" is not mounted.`, { instanceId });
905
+ return;
906
+ }
907
+ this.#forget(instanceId, instance);
908
+ this.#fire(void 0, WIDGET_UNMOUNT_METHOD, [instanceId], instanceId);
909
+ }
910
+ #update(instanceId, size) {
911
+ if (!this.#requireInstance(instanceId)) return;
912
+ this.#layerStore.setSize(instanceId, size.width, size.height);
913
+ const layer = this.#layerStore.get(instanceId);
914
+ if (!layer) return;
915
+ this.#fire("widget/render-failed", WIDGET_RESIZE_METHOD, [
916
+ instanceId,
917
+ layer.width,
918
+ layer.height,
919
+ layer.dpr
920
+ ], instanceId);
921
+ }
922
+ #setProperties(instanceId, props) {
923
+ const instance = this.#requireInstance(instanceId);
924
+ if (!instance) return;
925
+ instance.props = props;
926
+ this.#fire("widget/render-failed", WIDGET_SET_PROPERTIES_METHOD, [instanceId, props], instanceId);
927
+ }
928
+ #requireInstance(instanceId) {
929
+ const instance = this.#instances.get(instanceId);
930
+ if (!instance) this.#report("widget/instance-not-found", `Widget instance "${instanceId}" is not mounted.`, { instanceId });
931
+ return instance;
932
+ }
933
+ /** True while `record` is still the live record for this id in an undisposed host. */
934
+ #owns(instanceId, record) {
935
+ return !this.#disposed && this.#instances.get(instanceId) === record;
936
+ }
937
+ /** Aborts a mount attempt whose instance was removed or replaced while it awaited. */
938
+ #requireOwnership(instanceId, record) {
939
+ if (!this.#owns(instanceId, record)) throw new WidgetMountCancelledError(instanceId);
940
+ }
941
+ /** Drops this attempt's reservation and layer; a newer record for the same id is left alone. */
942
+ #forget(instanceId, record) {
943
+ if (this.#instances.get(instanceId) !== record) return;
944
+ this.#instances.delete(instanceId);
945
+ this.#layerStore.remove(instanceId);
946
+ }
947
+ /**
948
+ * Asks the guest to release its sessions.
949
+ *
950
+ * The guest keeps its evaluated modules: a reset rebuilds instances, so module-level state is out
951
+ * of scope by contract and the factories stay warm. A host without a sandbox has nothing to
952
+ * reset: no instance ever mounted, so the following sync pass simply mounts into a fresh runtime.
953
+ * Failures are reported, never thrown: the remount below resumes from whatever state the guest is
954
+ * in.
955
+ */
956
+ async #resetGuestRuntime() {
957
+ if (!this.#sandbox && !this.#starting) return;
958
+ try {
959
+ const sandbox = await this.#ensureSandbox();
960
+ if (this.#disposed) return;
961
+ await sandbox.call(WIDGET_RESET_RUNTIME_METHOD);
962
+ } catch (error) {
963
+ if (this.#disposed || error instanceof WidgetRuntimeError) return;
964
+ if (this.#isTerminated()) {
965
+ this.#failRuntime("The widget sandbox terminated during reset.");
966
+ return;
967
+ }
968
+ this.#report("widget/runtime-failed", `The widget runtime could not be reset: ${describeError(error)}`);
969
+ }
970
+ }
971
+ #ensureSandbox() {
972
+ if (this.#disposed) return Promise.reject(new WidgetRuntimeError("Widget host is disposed"));
973
+ const existing = this.#sandbox;
974
+ if (existing) {
975
+ if (existing.state === "terminated") return Promise.reject(this.#failRuntime("The widget sandbox terminated unexpectedly."));
976
+ return Promise.resolve(existing);
977
+ }
978
+ if (!this.#starting) {
979
+ const pending = this.#createSandbox(this.#container === void 0 ? {} : { container: this.#container }).catch((error) => {
980
+ throw this.#failRuntime(`The widget sandbox failed to start: ${describeError(error)}`, error);
981
+ }).then(async (sandbox) => {
982
+ if (this.#disposed) {
983
+ await terminate(sandbox);
984
+ throw new WidgetRuntimeError("Widget host is disposed");
985
+ }
986
+ this.#sandbox = sandbox;
987
+ this.#attach(sandbox);
988
+ return sandbox;
989
+ });
990
+ this.#starting = pending;
991
+ const settle = () => {
992
+ if (this.#starting === pending) this.#starting = void 0;
993
+ };
994
+ pending.then(settle, settle);
995
+ }
996
+ return this.#starting;
997
+ }
998
+ /**
999
+ * Reads every asset reference found in the merged props. Failures are reported and skipped:
1000
+ * a missing image must not stop the instance from mounting.
1001
+ */
1002
+ async #prefetchAssets(instanceId, ref, props) {
1003
+ const source = this.#assets;
1004
+ if (!source) return void 0;
1005
+ const refs = collectAssetRefs(props);
1006
+ const entries = await Promise.all([...refs.values()].map(async (assetRef) => {
1007
+ try {
1008
+ const bytes = await source.resolve(assetRef);
1009
+ if (!(bytes instanceof Uint8Array)) throw new TypeError("WidgetAssetProvider.resolve() must resolve to a Uint8Array");
1010
+ return [assetRef.src, bytes];
1011
+ } catch (error) {
1012
+ this.#report("widget/asset-failed", `Widget asset "${assetRef.src}" for "${ref}" could not be read: ${describeError(error)}`, {
1013
+ instanceId,
1014
+ widget: ref
1015
+ });
1016
+ return;
1017
+ }
1018
+ }));
1019
+ return Object.fromEntries(entries.filter((entry) => entry !== void 0));
1020
+ }
1021
+ #attach(sandbox) {
1022
+ this.#detachers.push(sandbox.on(WIDGET_FRAME_EVENT, (payload) => this.#onFrame(payload)), sandbox.on(WIDGET_PUBLISH_EVENT, (payload) => this.#onPublishMessage(payload)), sandbox.on(WIDGET_ERROR_EVENT, (payload) => this.#onErrorMessage(payload)), sandbox.on(WIDGET_ASSET_FAILED_EVENT, (payload) => this.#onAssetFailedMessage(payload)));
1023
+ }
1024
+ #detach() {
1025
+ for (const detach of this.#detachers.splice(0)) try {
1026
+ detach();
1027
+ } catch {}
1028
+ }
1029
+ #onFrame(payload) {
1030
+ const frame = payload;
1031
+ if (!frame || typeof frame !== "object" || typeof frame.instanceId !== "string") return;
1032
+ if (!isBitmap(frame.bitmap)) return;
1033
+ this.#layerStore.setBitmap(frame.instanceId, frame.bitmap);
1034
+ }
1035
+ #onPublishMessage(payload) {
1036
+ const message = payload;
1037
+ if (!message || typeof message !== "object") return;
1038
+ if (typeof message.instanceId !== "string" || typeof message.port !== "string") return;
1039
+ const publish = {
1040
+ instanceId: message.instanceId,
1041
+ port: message.port,
1042
+ payload: message.payload,
1043
+ simTime: typeof message.simTime === "number" && Number.isFinite(message.simTime) ? message.simTime : 0
1044
+ };
1045
+ this.#forwardToSimulation(publish);
1046
+ this.#onPublish?.(publish);
1047
+ }
1048
+ /** Sends a widget publish to the endpoint its port is bound to; unbound ports stay host-local. */
1049
+ #forwardToSimulation(publish) {
1050
+ const simulation = this.#simulation;
1051
+ if (simulation === void 0) return;
1052
+ const widget = this.#document.widgets.find((candidate) => candidate.id === publish.instanceId);
1053
+ const target = widget?.bindings?.[publish.port];
1054
+ if (target === void 0) return;
1055
+ try {
1056
+ simulation.deliver(target, publish.payload);
1057
+ } catch (error) {
1058
+ this.#report("widget/deliver-failed", `Publish from "${publish.instanceId}" could not reach ${target.symbol}.${target.port}: ${describeError(error)}`, {
1059
+ instanceId: publish.instanceId,
1060
+ widget: widget?.widget
1061
+ });
1062
+ }
1063
+ }
1064
+ /** Fans a device publish out to every widget port bound to its endpoint. */
1065
+ #onSimulationPublish(publish) {
1066
+ if (this.#disposed) return;
1067
+ const { target } = publish;
1068
+ for (const widget of this.#document.widgets) {
1069
+ const bindings = widget.bindings;
1070
+ if (bindings === void 0) continue;
1071
+ for (const port of Object.keys(bindings)) {
1072
+ const bound = bindings[port];
1073
+ if (bound === void 0 || bound.symbol !== target.symbol || bound.port !== target.port) continue;
1074
+ this.deliver(widget.id, port, publish.payload, publish.simTime);
1075
+ }
1076
+ }
1077
+ }
1078
+ #onAssetFailedMessage(payload) {
1079
+ const message = payload;
1080
+ if (!message || typeof message !== "object") return;
1081
+ if (typeof message.instanceId !== "string") return;
1082
+ const src = typeof message.src === "string" ? message.src : "unknown";
1083
+ const name = message.error?.name ?? "Error";
1084
+ const text = message.error?.message ?? "Unknown asset failure";
1085
+ this.#report("widget/asset-failed", `Widget "${message.instanceId}" could not read asset "${src}": ${name}: ${text}`, {
1086
+ instanceId: message.instanceId,
1087
+ widget: this.#instances.get(message.instanceId)?.widget
1088
+ });
1089
+ }
1090
+ #onErrorMessage(payload) {
1091
+ const message = payload;
1092
+ if (!message || typeof message !== "object") return;
1093
+ if (typeof message.instanceId !== "string") return;
1094
+ if (message.phase !== "render" && message.phase !== "deliver") return;
1095
+ const code = message.phase === "render" ? "widget/render-failed" : "widget/deliver-failed";
1096
+ const name = message.error?.name ?? "Error";
1097
+ const text = message.error?.message ?? "Unknown widget failure";
1098
+ this.#report(code, `Widget "${message.instanceId}" failed during ${message.phase}: ${name}: ${text}`, {
1099
+ instanceId: message.instanceId,
1100
+ widget: this.#instances.get(message.instanceId)?.widget
1101
+ });
1102
+ }
1103
+ #fire(code, method, args, instanceId) {
1104
+ if (this.#disposed) return;
1105
+ if (!this.#sandbox && !this.#starting) return;
1106
+ this.#ensureSandbox().then((sandbox) => sandbox.call(method, ...args)).catch((error) => {
1107
+ if (this.#disposed || error instanceof WidgetRuntimeError) return;
1108
+ if (this.#isTerminated()) {
1109
+ this.#failRuntime("The widget sandbox terminated unexpectedly.");
1110
+ return;
1111
+ }
1112
+ if (code === void 0) return;
1113
+ this.#report(code, `Widget call "${method}" failed for "${instanceId}": ${describeError(error)}`, {
1114
+ instanceId,
1115
+ widget: this.#instances.get(instanceId)?.widget
1116
+ });
1117
+ });
1118
+ }
1119
+ #isTerminated() {
1120
+ return this.#sandbox?.state === "terminated";
1121
+ }
1122
+ /** Abandons the runtime: layers are cleared and the failure is reported once. */
1123
+ #failRuntime(message, cause) {
1124
+ this.#sandbox = void 0;
1125
+ this.#starting = void 0;
1126
+ this.#detach();
1127
+ this.#layerStore.clear();
1128
+ this.#instances.clear();
1129
+ if (!this.#disposed) this.#report("widget/runtime-failed", message);
1130
+ return new WidgetRuntimeError(message, cause === void 0 ? void 0 : { cause });
1131
+ }
1132
+ async #shutdown() {
1133
+ this.#disposed = true;
1134
+ this.#detach();
1135
+ this.#unsubscribeSimulation?.();
1136
+ this.#unsubscribeSimulation = void 0;
1137
+ this.#layerStore.clear();
1138
+ this.#instances.clear();
1139
+ const pending = this.#starting;
1140
+ const sandbox = this.#sandbox;
1141
+ this.#starting = void 0;
1142
+ this.#sandbox = void 0;
1143
+ if (sandbox) {
1144
+ await terminate(sandbox);
1145
+ return;
1146
+ }
1147
+ if (pending) {
1148
+ const late = await pending.catch(() => void 0);
1149
+ if (late) await terminate(late);
1150
+ }
1151
+ }
1152
+ #report(code, message, ids = {}) {
1153
+ const diagnostic = {
1154
+ code,
1155
+ message,
1156
+ ...ids.instanceId === void 0 ? {} : { instanceId: ids.instanceId },
1157
+ ...ids.widget === void 0 ? {} : { widget: ids.widget }
1158
+ };
1159
+ try {
1160
+ this.#onDiagnostic?.(diagnostic);
1161
+ } catch (error) {
1162
+ console.error("[@mica-js/widget] diagnostic handler threw", error);
1163
+ }
1164
+ }
1165
+ #emitDocument(document) {
1166
+ for (const listener of [...this.#documentListeners]) try {
1167
+ listener(document);
1168
+ } catch (error) {
1169
+ console.error("[@mica-js/widget] document listener threw", error);
1170
+ }
1171
+ }
1172
+ };
1173
+ function placementOf(widget) {
1174
+ return {
1175
+ x: widget.x,
1176
+ y: widget.y,
1177
+ width: widget.width,
1178
+ height: widget.height,
1179
+ rotation: widget.rotation
1180
+ };
1181
+ }
1182
+ /**
1183
+ * Shallow comparison of two property maps.
1184
+ *
1185
+ * The document owns property values, so a nested object only counts as changed when the caller
1186
+ * replaced the object itself; deep equality would swallow those edits. The key sets matter as much
1187
+ * as the values, because a missing key falls back to the definition default while an explicit
1188
+ * `undefined` overrides it.
1189
+ */
1190
+ function sameProperties(left, right) {
1191
+ if (left === right) return true;
1192
+ const keys = Object.keys(left);
1193
+ return keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && Object.is(left[key], right[key]));
1194
+ }
1195
+ function splitRef(ref) {
1196
+ const separator = ref.indexOf(":");
1197
+ if (separator <= 0 || separator === ref.length - 1) return void 0;
1198
+ return {
1199
+ packageId: ref.slice(0, separator),
1200
+ widgetId: ref.slice(separator + 1)
1201
+ };
1202
+ }
1203
+ function currentDevicePixelRatio() {
1204
+ const ratio = globalThis.devicePixelRatio;
1205
+ return typeof ratio === "number" && Number.isFinite(ratio) && ratio > 0 ? ratio : 1;
1206
+ }
1207
+ function isBitmap(value) {
1208
+ return typeof value === "object" && value !== null && typeof value.close === "function";
1209
+ }
1210
+ function describeError(error) {
1211
+ if (error instanceof Error && error.message) return error.message;
1212
+ return typeof error === "string" ? error : String(error);
1213
+ }
1214
+ async function terminate(sandbox) {
1215
+ try {
1216
+ await sandbox.terminate("widget host disposed");
1217
+ } catch {}
1218
+ }
1219
+ /** Asks the guest to drop an instance the host has already given up on. */
1220
+ async function releaseGuestInstance(sandbox, instanceId) {
1221
+ try {
1222
+ await sandbox.call(WIDGET_UNMOUNT_METHOD, instanceId);
1223
+ } catch {}
1224
+ }
1225
+ //#endregion
1226
+ export { WIDGET_RUNTIME_SOURCE, WidgetLoadError, createDefaultWidgetSandbox, createPackageWidgetProvider, createStaticWidgetProvider, createWidgetHost, loadWidgetPackage };
1227
+
1228
+ //# sourceMappingURL=index.js.map