@mica-js/widget 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["workletScript","guestScript"],"sources":["../src/errors.ts","../src/package/load.ts","../src/package/static-provider.ts","../src/package/package-provider.ts","../src/host-fs/errors.ts","../src/host-fs/data-uri.ts","../src/host-fs/uri.ts","../src/guest/widget/protocol.ts","../src/guest/audio/protocol.ts","../src/host/audio/worklet.ts","../src/host/audio/engine.ts","../src/host/audio/noop.ts","../src/guest/widget/props.ts","../src/host/catalog.ts","../src/host/widgets.ts","../src/host/widget-host.ts","../src/host/sandbox.ts","../src/host/guest.ts"],"sourcesContent":["export type WidgetLoadErrorCode =\n | 'widget/package-not-found'\n | 'widget/invalid-manifest'\n | 'widget/invalid-definition'\n | 'widget/no-implementation'\n | 'widget/not-self-contained'\n | 'widget/load-failed'\n /** A descriptor field carries a value outside its closed set (RFC 0017 `delivery`). */\n | 'schema/invalid-value';\n\nexport interface WidgetLoadErrorOptions {\n /** Package id, when the package was already identified. */\n readonly packageId?: string;\n /** Package-relative path the failure refers to. */\n readonly path?: string;\n readonly cause?: unknown;\n}\n\n/** Thrown when a widget reference resolves to a package that cannot be turned into a module. */\nexport class WidgetLoadError extends Error {\n readonly code: WidgetLoadErrorCode;\n readonly packageId: string | undefined;\n readonly path: string | undefined;\n\n constructor(code: WidgetLoadErrorCode, message: string, options: WidgetLoadErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'WidgetLoadError';\n this.code = code;\n this.packageId = options.packageId;\n this.path = options.path;\n }\n}\n","import { parseDeliveryKind, parsePayloadType } from '@mica-js/core/canvas';\nimport { WidgetLoadError, type WidgetLoadErrorCode } from '../errors';\nimport type { PortDefinition, PropertyDefinition, WidgetDefinition, WidgetModule } from '../types';\n\n/** Read-only view of the files that make up one package. */\nexport interface PackageFiles {\n /** Human-readable label used in diagnostics. */\n readonly label: string;\n /** Reads a package-relative POSIX path and resolves to its bytes. */\n read(path: string): Promise<Uint8Array>;\n}\n\nexport interface WidgetPackage {\n readonly id: string;\n readonly version: string;\n /**\n * SHA-256 (hex) over the `[widget id, source]` pairs in widget-id order, so distinct package\n * contents never collide and reordering the manifest does not change the hash.\n */\n readonly contentHash: string;\n readonly modules: Readonly<Record<string, WidgetModule>>;\n}\n\nconst PACKAGE_JSON = 'package.json';\nconst JSON_EXTENSION = '.json';\nconst IMPLEMENTATION_EXTENSION = '.js';\n/** Package and widget ids are stable kebab-case identifiers (see #1). */\nconst ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/;\n\ninterface WidgetEntry {\n readonly id: string;\n readonly path: string;\n readonly displayName: string | undefined;\n readonly description: string | undefined;\n}\n\ninterface PackageManifest {\n readonly id: string;\n readonly version: string;\n readonly widgets: readonly WidgetEntry[];\n}\n\n/**\n * Reads a package manifest, every declared widget definition and its paired implementation.\n * Only the three declared path kinds are read; the package is never enumerated.\n *\n * @throws {WidgetLoadError}\n */\nexport async function loadWidgetPackage(files: PackageFiles): Promise<WidgetPackage> {\n const manifest = await readManifest(files);\n const modules: Record<string, WidgetModule> = {};\n const sources: (readonly [string, string])[] = [];\n\n for (const entry of manifest.widgets) {\n const definition = await readDefinition(files, manifest.id, entry);\n const implementationPath = toImplementationPath(entry.path);\n const code = await readImplementation(files, manifest.id, entry.id, implementationPath);\n modules[entry.id] = { definition, code };\n sources.push([entry.id, code]);\n }\n\n // Ids travel with each source, so the digest separates adjacent widgets and empty files.\n const contentHash = await sha256Hex(JSON.stringify(sources), manifest.id);\n return { id: manifest.id, version: manifest.version, contentHash, modules };\n}\n\nasync function readManifest(files: PackageFiles): Promise<PackageManifest> {\n let bytes: Uint8Array;\n try {\n bytes = await files.read(PACKAGE_JSON);\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/package-not-found',\n `Package ${JSON.stringify(files.label)} has no readable ${PACKAGE_JSON}.`,\n { path: PACKAGE_JSON, cause },\n );\n }\n\n const manifest = requireObject(\n parseJson(bytes, 'widget/invalid-manifest', PACKAGE_JSON, undefined, PACKAGE_JSON),\n 'widget/invalid-manifest',\n `${PACKAGE_JSON} must be a JSON object`,\n undefined,\n PACKAGE_JSON,\n );\n\n const id = manifest['name'];\n if (typeof id !== 'string' || !ID_PATTERN.test(id)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `${PACKAGE_JSON} must declare a kebab-case \"name\".`,\n { path: PACKAGE_JSON },\n );\n }\n\n const version = manifest['version'];\n if (typeof version !== 'string' || version.length === 0) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(id)} must declare a non-empty \"version\".`,\n { packageId: id, path: PACKAGE_JSON },\n );\n }\n\n const widgetsValue = manifest['widgets'];\n const widgets =\n widgetsValue === undefined\n ? {}\n : requireObject(\n widgetsValue,\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(id)} \"widgets\" must be an object`,\n id,\n PACKAGE_JSON,\n );\n\n const entries = Object.keys(widgets)\n .sort()\n .map((widgetId) => readEntry(widgets[widgetId], widgetId, id));\n\n return { id, version, widgets: entries };\n}\n\nfunction readEntry(value: unknown, widgetId: string, packageId: string): WidgetEntry {\n if (!ID_PATTERN.test(widgetId)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(packageId)} declares widget id ${JSON.stringify(widgetId)}; ids must be kebab-case.`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n\n const entry = requireObject(\n value,\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} entry must be an object`,\n packageId,\n PACKAGE_JSON,\n );\n\n const path = entry['path'];\n if (typeof path !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} must declare a string \"path\".`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n const problem = packagePathProblem(path);\n if (problem !== undefined) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} path ${JSON.stringify(path)} ${problem}.`,\n { packageId, path },\n );\n }\n if (!path.endsWith(JSON_EXTENSION)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} path ${JSON.stringify(path)} must point at a ${JSON_EXTENSION} description.`,\n { packageId, path },\n );\n }\n\n return {\n id: widgetId,\n path,\n displayName: optionalString(entry, 'displayName', widgetId, packageId),\n description: optionalString(entry, 'description', widgetId, packageId),\n };\n}\n\nasync function readDefinition(\n files: PackageFiles,\n packageId: string,\n entry: WidgetEntry,\n): Promise<WidgetDefinition> {\n let bytes: Uint8Array;\n try {\n bytes = await files.read(entry.path);\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(entry.id)} declares a missing definition at ${JSON.stringify(entry.path)}.`,\n { packageId, path: entry.path, cause },\n );\n }\n\n const record = requireObject(\n parseJson(bytes, 'widget/invalid-definition', entry.path, packageId, entry.path),\n 'widget/invalid-definition',\n `Widget definition ${JSON.stringify(entry.path)} must be a JSON object`,\n packageId,\n entry.path,\n );\n\n const properties = readProperties(record['properties'], packageId, entry.path);\n const ports = readPorts(record['ports'], packageId, entry.path);\n\n return {\n properties,\n ports,\n ...(entry.displayName === undefined ? {} : { displayName: entry.displayName }),\n ...(entry.description === undefined ? {} : { description: entry.description }),\n };\n}\n\nfunction readProperties(\n value: unknown,\n packageId: string,\n path: string,\n): Readonly<Record<string, PropertyDefinition>> {\n if (value === undefined) {\n return createRecord();\n }\n const record = requireObject(\n value,\n 'widget/invalid-definition',\n `\"properties\" in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const properties: Record<string, PropertyDefinition> = createRecord();\n for (const [key, raw] of Object.entries(record)) {\n if (isUnsafeRecordKey(key)) {\n continue;\n }\n const descriptor = requireObject(\n raw,\n 'widget/invalid-definition',\n `Property ${JSON.stringify(key)} in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n const type = descriptor['type'];\n if (typeof type !== 'string' || type.length === 0) {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Property ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare a non-empty string \"type\".`,\n { packageId, path },\n );\n }\n properties[key] = { ...descriptor, type };\n }\n return properties;\n}\n\nfunction readPorts(\n value: unknown,\n packageId: string,\n path: string,\n): Readonly<Record<string, PortDefinition>> {\n if (value === undefined) {\n return createRecord();\n }\n const record = requireObject(\n value,\n 'widget/invalid-definition',\n `\"ports\" in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const ports: Record<string, PortDefinition> = createRecord();\n for (const [key, raw] of Object.entries(record)) {\n if (isUnsafeRecordKey(key)) {\n continue;\n }\n const descriptor = requireObject(\n raw,\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const direction = descriptor['direction'];\n if (direction !== 'input' && direction !== 'output') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare \"direction\" as \"input\" or \"output\".`,\n { packageId, path },\n );\n }\n\n const typeName = descriptor['type'];\n if (typeof typeName !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare a string \"type\".`,\n { packageId, path },\n );\n }\n const type = parsePayloadType(typeName);\n if (type === undefined) {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} declares unknown payload type ${JSON.stringify(typeName)}.`,\n { packageId, path },\n );\n }\n\n const title = portText(descriptor, 'title', key, packageId, path);\n const description = portText(descriptor, 'description', key, packageId, path);\n // RFC 0017: `delivery` is optional and independent of `type`; an unparsable value is rejected\n // here instead of silently falling back to the payload type default.\n const declaredDelivery = descriptor['delivery'];\n const delivery =\n declaredDelivery === undefined ? undefined : parseDeliveryKind(declaredDelivery);\n if (declaredDelivery !== undefined && delivery === undefined) {\n throw new WidgetLoadError(\n 'schema/invalid-value',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare \"delivery\" as \"level\" or \"message\".`,\n { packageId, path },\n );\n }\n ports[key] = {\n direction,\n type,\n ...(delivery === undefined ? {} : { delivery }),\n ...(title === undefined ? {} : { title }),\n ...(description === undefined ? {} : { description }),\n };\n }\n return ports;\n}\n\nasync function readImplementation(\n files: PackageFiles,\n packageId: string,\n widgetId: string,\n path: string,\n): Promise<string> {\n try {\n return decode(await files.read(path));\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/no-implementation',\n `Widget ${JSON.stringify(widgetId)} in package ${JSON.stringify(packageId)} has no implementation at ${JSON.stringify(path)}.`,\n { packageId, path, cause },\n );\n }\n}\n\n/** Rejects absolute paths, drive letters, backslashes and escaping `..` segments. */\nfunction packagePathProblem(path: string): string | undefined {\n if (path.length === 0) {\n return 'must not be empty';\n }\n if (path.startsWith('/')) {\n return 'must be relative to the package root';\n }\n if (/^[A-Za-z]:/.test(path)) {\n return 'must not carry a drive letter';\n }\n if (path.includes('\\\\')) {\n return 'must use POSIX separators';\n }\n if (path.split('/').includes('..')) {\n return 'must stay inside the package';\n }\n return undefined;\n}\n\nfunction toImplementationPath(definitionPath: string): string {\n return definitionPath.slice(0, -JSON_EXTENSION.length) + IMPLEMENTATION_EXTENSION;\n}\n\n/** Reads an optional manifest field; failures always point at `package.json`, where the field lives. */\nfunction optionalString(\n record: Record<string, unknown>,\n key: 'displayName' | 'description',\n widgetId: string,\n packageId: string,\n): string | undefined {\n const value = record[key];\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} \"${key}\" in ${PACKAGE_JSON} must be a string.`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n return value;\n}\n\nfunction portText(\n record: Record<string, unknown>,\n key: 'title' | 'description',\n portId: string,\n packageId: string,\n path: string,\n): string | undefined {\n const value = record[key];\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(portId)} \"${key}\" in ${JSON.stringify(path)} must be a string.`,\n { packageId, path },\n );\n }\n return value;\n}\n\nfunction parseJson(\n bytes: Uint8Array,\n code: WidgetLoadErrorCode,\n what: string,\n packageId: string | undefined,\n path: string,\n): unknown {\n try {\n return JSON.parse(decode(bytes)) as unknown;\n } catch (cause) {\n throw new WidgetLoadError(code, `${what} is not valid JSON.`, {\n path,\n cause,\n ...(packageId === undefined ? {} : { packageId }),\n });\n }\n}\n\nfunction requireObject(\n value: unknown,\n code: WidgetLoadErrorCode,\n message: string,\n packageId: string | undefined,\n path: string,\n): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new WidgetLoadError(code, `${message}.`, {\n path,\n ...(packageId === undefined ? {} : { packageId }),\n });\n }\n return value as Record<string, unknown>;\n}\n\nfunction decode(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Record for keys taken from untrusted definition JSON: no inherited setter can intercept an\n * assignment, so a declared entry can never become an object prototype.\n */\nfunction createRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\n/** `__proto__` is never a stable widget key, and on any object it would shadow the prototype. */\nfunction isUnsafeRecordKey(key: string): boolean {\n return key === '__proto__';\n}\n\nasync function sha256Hex(text: string, packageId: string): Promise<string> {\n const subtle = globalThis.crypto?.subtle;\n if (subtle === undefined) {\n throw new WidgetLoadError(\n 'widget/load-failed',\n 'Computing the widget package content hash requires Web Crypto (globalThis.crypto.subtle).',\n { packageId, path: PACKAGE_JSON },\n );\n }\n const digest = await subtle.digest('SHA-256', new TextEncoder().encode(text));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n","import type { WidgetModule, WidgetProvider } from '../types';\n\n/** Provider over a fixed module table, used for builtin widgets and tests. */\nexport function createStaticWidgetProvider(\n modules: Readonly<Record<string, WidgetModule>>,\n): WidgetProvider {\n const index = new Map(Object.entries(modules));\n return {\n resolve(ref) {\n return Promise.resolve(index.get(ref));\n },\n };\n}\n","import { WidgetLoadError } from '../errors';\nimport { loadWidgetPackage, type PackageFiles } from './load';\nimport type { WidgetModule, WidgetProvider } from '../types';\n\nexport interface PackageWidgetProviderOptions {\n readonly files: PackageFiles | readonly PackageFiles[];\n}\n\n/**\n * Loads every package up front and indexes its widgets under `<packageId>:<widgetId>`.\n * Resolution never touches the file system again, and unknown references return `undefined`.\n *\n * @throws {WidgetLoadError}\n */\nexport async function createPackageWidgetProvider(\n options: PackageWidgetProviderOptions,\n): Promise<WidgetProvider> {\n const filesList: readonly PackageFiles[] = Array.isArray(options.files)\n ? options.files\n : [options.files as PackageFiles];\n\n const index = new Map<string, WidgetModule>();\n const packageIds = new Set<string>();\n\n for (const files of filesList) {\n const widgetPackage = await loadWidgetPackage(withPathCache(files));\n if (packageIds.has(widgetPackage.id)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package id ${JSON.stringify(widgetPackage.id)} is provided more than once.`,\n { packageId: widgetPackage.id, path: 'package.json' },\n );\n }\n packageIds.add(widgetPackage.id);\n for (const [widgetId, module] of Object.entries(widgetPackage.modules)) {\n index.set(`${widgetPackage.id}:${widgetId}`, module);\n }\n }\n\n return {\n resolve(ref) {\n return Promise.resolve(index.get(ref));\n },\n };\n}\n\n/** Reads each path at most once for the lifetime of the provider. */\nfunction withPathCache(files: PackageFiles): PackageFiles {\n const cache = new Map<string, Promise<Uint8Array>>();\n return {\n label: files.label,\n read(path) {\n const cached = cache.get(path);\n if (cached !== undefined) {\n return cached;\n }\n const pending = files.read(path);\n cache.set(path, pending);\n return pending;\n },\n };\n}\n","/** Failure classification of a `HostFs.read` rejection. */\nexport type HostFsErrorCode = 'FileNotFound' | 'NoPermissions' | 'NoFileSystem' | 'Unavailable';\n\n/**\n * Structured-clone payload for a `HostFsError` that crosses a thread boundary.\n *\n * The receiving side rebuilds the instance from `code`; `message` keeps the original wording when\n * it survives the transport and falls back to the default message for the code otherwise.\n */\nexport interface HostFsErrorPayload {\n readonly code: HostFsErrorCode;\n readonly uri: string;\n readonly message?: string;\n}\n\nexport interface HostFsErrorOptions {\n readonly cause?: unknown;\n}\n\nconst DEFAULT_MESSAGES: Record<HostFsErrorCode, string> = {\n FileNotFound: 'Host resource not found',\n NoPermissions: 'Host resource access denied',\n NoFileSystem: 'No host file system handles the URI scheme',\n Unavailable: 'Host file system is unavailable',\n};\n\nconst ERROR_CODES: readonly HostFsErrorCode[] = [\n 'FileNotFound',\n 'NoPermissions',\n 'NoFileSystem',\n 'Unavailable',\n];\n\nfunction isHostFsErrorCode(value: unknown): value is HostFsErrorCode {\n return typeof value === 'string' && (ERROR_CODES as readonly string[]).includes(value);\n}\n\n/** Rejection of `HostFs.read`: `code` classifies the failure, `uri` names the resource. */\nexport class HostFsError extends Error {\n readonly code: HostFsErrorCode;\n readonly uri: string;\n\n constructor(\n code: HostFsErrorCode,\n uri: string,\n message?: string,\n options: HostFsErrorOptions = {},\n ) {\n super(\n message ?? `${DEFAULT_MESSAGES[code]}: ${uri}`,\n options.cause === undefined ? undefined : { cause: options.cause },\n );\n this.name = 'HostFsError';\n this.code = code;\n this.uri = uri;\n }\n}\n\n/** Narrows an unknown rejection to a `HostFsError` created in this realm. */\nexport function isHostFsError(value: unknown): value is HostFsError {\n return value instanceof HostFsError;\n}\n\n/** Copies the fields a thread hop must carry; the instance itself does not survive a structured clone. */\nexport function toHostFsErrorPayload(error: HostFsError): HostFsErrorPayload {\n return { code: error.code, uri: error.uri, message: error.message };\n}\n\n/** Rebuilds a `HostFsError` from its payload, rejecting codes outside the contract. */\nexport function fromHostFsErrorPayload(payload: HostFsErrorPayload): HostFsError {\n const code: unknown = payload.code;\n if (!isHostFsErrorCode(code)) {\n throw new TypeError(`Unknown HostFsError code: ${String(code)}`);\n }\n return new HostFsError(code, payload.uri, payload.message);\n}\n","/**\n * Decodes a self-contained `data:` URI to its bytes.\n *\n * `data:` resources never reach `HostFs`: the bytes travel with the reference, so the host decodes\n * them locally. `;base64` payloads are decoded from base64; other payloads are percent-decoded,\n * while characters that need no escaping are encoded as UTF-8. The URI fragment is ignored.\n *\n * @throws TypeError when the URI has no payload separator or the payload is not decodable.\n */\nexport function decodeDataUri(uri: string): Uint8Array {\n const { base64, payload } = splitDataUri(uri);\n return base64 ? decodeBase64(payload) : decodePercentPayload(payload);\n}\n\n/**\n * Decodes a self-contained `data:` URI to its text payload.\n *\n * The decoded bytes are read as UTF-8, so a payload that carries binary or malformed UTF-8 is a\n * decode failure rather than replacement characters.\n *\n * @throws TypeError when the URI has no payload separator, the payload is not decodable, or the\n * bytes are not UTF-8.\n */\nexport function decodeDataUriText(uri: string): string {\n const bytes = decodeDataUri(uri);\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (cause) {\n throw new TypeError('Data URI payload is not valid UTF-8', { cause });\n }\n}\n\ninterface DataUriPayload {\n readonly base64: boolean;\n readonly payload: string;\n}\n\n/** Splits the URI into its `;base64` flag and payload. */\nfunction splitDataUri(uri: string): DataUriPayload {\n if (uri.slice(0, 5).toLowerCase() !== 'data:') {\n throw new TypeError('Not a data: URI');\n }\n const hash = uri.indexOf('#');\n const body = hash < 0 ? uri : uri.slice(0, hash);\n const comma = body.indexOf(',');\n if (comma < 0) {\n throw new TypeError('Data URI must separate its payload with a comma');\n }\n\n const metadata = body.slice('data:'.length, comma);\n return { base64: /;base64$/i.test(metadata), payload: body.slice(comma + 1) };\n}\n\nfunction decodeBase64(payload: string): Uint8Array {\n let binary: string;\n try {\n binary = atob(payload);\n } catch (cause) {\n throw new TypeError('Data URI payload is not valid base64', { cause });\n }\n\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\nfunction isHexDigit(value: string | undefined): value is string {\n return value !== undefined && /^[0-9A-Fa-f]$/.test(value);\n}\n\n/**\n * Percent-decodes a payload to bytes, so `%89PNG` keeps its binary value instead of being read as\n * (invalid) UTF-8. Literal characters are UTF-8 encoded.\n */\nfunction decodePercentPayload(payload: string): Uint8Array {\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n let literal = 0;\n let index = 0;\n\n while (index < payload.length) {\n if (payload[index] !== '%') {\n index += 1;\n continue;\n }\n const high = payload[index + 1];\n const low = payload[index + 2];\n if (!isHexDigit(high) || !isHexDigit(low)) {\n throw new TypeError('Data URI payload is not valid percent-encoding');\n }\n if (index > literal) chunks.push(encoder.encode(payload.slice(literal, index)));\n chunks.push(new Uint8Array([Number.parseInt(`${high}${low}`, 16)]));\n index += 3;\n literal = index;\n }\n\n if (literal < payload.length) chunks.push(encoder.encode(payload.slice(literal)));\n\n let total = 0;\n for (const chunk of chunks) total += chunk.length;\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n","interface UriParts {\n readonly scheme: string | undefined;\n readonly authority: string | undefined;\n readonly path: string;\n readonly query: string | undefined;\n readonly fragment: string | undefined;\n}\n\ninterface PathReference {\n readonly path: string;\n readonly query: string | undefined;\n readonly fragment: string | undefined;\n}\n\nconst ABSOLUTE_URI = /^[A-Za-z][A-Za-z0-9+.-]*:/;\n\n/** Whether `uri` carries a scheme, i.e. is absolute rather than a relative reference. */\nexport function isAbsoluteHostUri(uri: string): boolean {\n return ABSOLUTE_URI.test(uri);\n}\n\n/** Splits a reference into path, query and fragment without interpreting leading slashes. */\nfunction splitPath(value: string): PathReference {\n const hash = value.indexOf('#');\n const fragment = hash < 0 ? undefined : value.slice(hash + 1);\n const beforeFragment = hash < 0 ? value : value.slice(0, hash);\n const question = beforeFragment.indexOf('?');\n const query = question < 0 ? undefined : beforeFragment.slice(question + 1);\n const path = question < 0 ? beforeFragment : beforeFragment.slice(0, question);\n return { path, query, fragment };\n}\n\nfunction parseUri(value: string): UriParts {\n const schemeMatch = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(value);\n const scheme = schemeMatch?.[1];\n let rest = schemeMatch === null ? value : value.slice(schemeMatch[0].length);\n\n let authority: string | undefined;\n if (rest.startsWith('//')) {\n const tail = rest.slice(2);\n const end = tail.search(/[/?#]/);\n authority = end < 0 ? tail : tail.slice(0, end);\n rest = end < 0 ? '' : tail.slice(end);\n }\n\n const { path, query, fragment } = splitPath(rest);\n return { scheme, authority, path, query, fragment };\n}\n\nfunction removeLastSegment(output: string): string {\n const slash = output.lastIndexOf('/');\n return slash < 0 ? '' : output.slice(0, slash);\n}\n\n/** RFC 3986 §5.2.4: drops `.` and `..` segments without touching empty segments. */\nfunction removeDotSegments(path: string): string {\n let input = path;\n let output = '';\n while (input.length > 0) {\n if (input.startsWith('../')) {\n input = input.slice(3);\n } else if (input.startsWith('./')) {\n input = input.slice(2);\n } else if (input.startsWith('/./')) {\n input = `/${input.slice(3)}`;\n } else if (input === '/.') {\n input = '/';\n } else if (input.startsWith('/../')) {\n input = `/${input.slice(4)}`;\n output = removeLastSegment(output);\n } else if (input === '/..') {\n input = '/';\n output = removeLastSegment(output);\n } else if (input === '.' || input === '..') {\n input = '';\n } else {\n const segment = /^\\/?[^/]*/.exec(input)?.[0] ?? input;\n output += segment;\n input = input.slice(segment.length);\n }\n }\n return output;\n}\n\n/** RFC 3986 §5.3: merges a relative path with the base path. */\nfunction mergePath(base: UriParts, referencePath: string): string {\n if (referencePath === '') return base.path;\n if (base.authority !== undefined && base.path === '') return `/${referencePath}`;\n const slash = base.path.lastIndexOf('/');\n return slash < 0 ? referencePath : `${base.path.slice(0, slash + 1)}${referencePath}`;\n}\n\nfunction compose(\n scheme: string,\n authority: string | undefined,\n path: string,\n query: string | undefined,\n fragment: string | undefined,\n): string {\n let uri = `${scheme}:`;\n if (authority !== undefined) uri += `//${authority}`;\n uri += path;\n if (query !== undefined) uri += `?${query}`;\n if (fragment !== undefined) uri += `#${fragment}`;\n return uri;\n}\n\n/**\n * Resolves a document reference against the absolute URI of the document that contains it.\n *\n * - a reference with a scheme is an absolute URI and is returned unchanged;\n * - a reference starting with `/` replaces the path and keeps the base scheme and authority;\n * - any other reference is merged with the base directory and normalized.\n *\n * The result always keeps the scheme and authority of `baseUri`, so a `//host/path` reference\n * stays inside the base authority instead of replacing it. Hosts pass a base URI whose path is\n * not empty; a base with an authority and an empty path resolves relative references under that\n * authority.\n *\n * @throws TypeError when `baseUri` is not an absolute URI.\n */\nexport function resolveHostUri(baseUri: string, reference: string): string {\n const base = parseUri(baseUri);\n if (base.scheme === undefined) {\n throw new TypeError(`Host URI base must be absolute: ${baseUri}`);\n }\n if (isAbsoluteHostUri(reference)) return reference;\n\n const target = splitPath(reference);\n const replacesPath = reference.startsWith('/');\n const path = replacesPath\n ? removeDotSegments(target.path)\n : removeDotSegments(mergePath(base, target.path));\n const keepBaseQuery = !replacesPath && target.path === '' && target.query === undefined;\n const query = keepBaseQuery ? base.query : target.query;\n return compose(base.scheme, base.authority, path, query, target.fragment);\n}\n","import { defineRpcService } from '@mica-js/core/rpc';\nimport type { CanvasBindingTarget } from '@mica-js/core/canvas';\nimport type { SimulationPublish } from '@mica-js/simulator';\nimport type { WidgetDefinition } from '../../types';\nimport type { WidgetAudioMountInfo } from '../audio/protocol';\nimport type { WidgetInputEvent } from './types';\n\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 */\nexport const widgetFrameEvent = 'widget:frame';\nexport const widgetPublishEvent = 'widget:publish';\nexport const widgetErrorEvent = 'widget:error';\n/** A resource the guest could not hand to a widget; non-fatal, the instance keeps running. */\nexport const widgetAssetFailedEvent = 'widget:asset-failed';\n\n/** Guest methods the host reaches through `sandbox.call()`. */\nexport const widgetLoadMethod = 'load';\nexport const widgetMountMethod = 'mount';\nexport const widgetUnmountMethod = 'unmount';\nexport const widgetResizeMethod = 'resize';\nexport const widgetSetPropertiesMethod = 'set-properties';\n/**\n * Replaces the device endpoints one instance writes to and reads from (RFC 0018).\n *\n * The guest routes topic traffic itself when it holds a direct device channel, so it needs the same\n * binding map the host validates against. A guest without that channel ignores the call.\n */\nexport const widgetSetBindingsMethod = 'set-bindings';\nexport const widgetDeliverMethod = 'deliver';\nexport const widgetPointerMethod = '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 */\nexport const widgetResetRuntimeMethod = 'reset-runtime';\n/** Instance boundary that produced a widget error. */\nexport type WidgetErrorPhase = 'mount' | 'render' | 'deliver';\n\n/** Widget errors cross the sandbox boundary as plain data. */\nexport interface SerializedWidgetError {\n readonly name: string;\n readonly message: string;\n}\n\n/** One rendered frame, always transferred so the host owns the bitmap. */\nexport interface WidgetFrameMessage {\n readonly instanceId: string;\n readonly bitmap: ImageBitmap;\n readonly width: number;\n readonly height: number;\n readonly dpr: number;\n}\n\n/** Payload a widget published on an output port. */\nexport interface WidgetPublishMessage {\n readonly instanceId: string;\n readonly port: string;\n readonly payload: unknown;\n /** Simulation time supplied by the widget; `0` when it did not pass one. */\n readonly simTime: number;\n /**\n * The guest already handed this publish to the device guest over its direct channel, so the host\n * must not forward it a second time. Absent when the guest has no channel or no binding.\n */\n readonly direct?: boolean;\n}\n\n/** Asset read that failed inside the guest; reported once per instance and `src`. */\nexport interface WidgetAssetFailedMessage {\n readonly instanceId: string;\n readonly src: string;\n readonly error: SerializedWidgetError;\n}\n\n/** Failure contained to one instance; the guest keeps every other instance running. */\nexport interface WidgetErrorMessage {\n readonly instanceId: string;\n readonly phase: WidgetErrorPhase;\n readonly error: SerializedWidgetError;\n}\n\nexport interface WidgetLoadModule {\n readonly definition: WidgetDefinition;\n readonly code: string;\n}\n\nexport interface WidgetLoadPackage {\n readonly id: string;\n readonly modules: Readonly<Record<string, WidgetLoadModule>>;\n}\n\nexport interface WidgetLoadRequest {\n readonly packages: readonly WidgetLoadPackage[];\n}\n\nexport interface WidgetMountRequest {\n readonly instanceId: string;\n readonly widget: string;\n readonly width: number;\n readonly height: number;\n readonly dpr: number;\n readonly props?: Readonly<Record<string, unknown>>;\n /** Bytes the host prefetched for this instance, keyed by `WidgetAssetRef.src`. */\n readonly assets?: Readonly<Record<string, Uint8Array>>;\n /**\n * Audio availability at mount time. Read synchronously by the factory through\n * `api.audio.state`; `session` is the one-shot token the worklet accepts for this generation.\n */\n readonly audio?: WidgetAudioMountInfo;\n}\n\n/** Every guest method the host reaches through `sandbox.call()`, in one RPC service. */\nexport interface WidgetGuestService {\n [widgetLoadMethod](request: WidgetLoadRequest): Promise<void>;\n [widgetMountMethod](request: WidgetMountRequest): void;\n [widgetUnmountMethod](instanceId: string): void;\n [widgetResizeMethod](instanceId: string, width: number, height: number, dpr: number): void;\n [widgetSetPropertiesMethod](instanceId: string, props: Readonly<Record<string, unknown>>): void;\n [widgetSetBindingsMethod](\n instanceId: string,\n bindings: Readonly<Record<string, CanvasBindingTarget>>,\n ): void;\n [widgetDeliverMethod](instanceId: string, port: string, payload: unknown, simTime: number): void;\n [widgetPointerMethod](instanceId: string, event: WidgetInputEvent): void;\n [widgetResetRuntimeMethod](): void;\n}\n\n/** Host → guest control lane: events pushed into the runtime and forced teardown. */\nexport interface WidgetGuestControlService {\n dispatchEvent(type: string, payload: unknown): void;\n terminate(): void;\n}\n\n/** Guest → host control lane: the event bus plus capability reads. */\nexport interface WidgetHostControlService {\n event(type: string, payload: unknown, transfer?: readonly Transferable[]): void;\n}\n\n/** Host file system reads the guest may perform; bytes travel as a transferred buffer. */\nexport interface WidgetHostCapabilitiesService {\n read(uri: string): Promise<Uint8Array>;\n}\n\n/**\n * Wire names shared by the worker script and the host adapter. Both sides must agree on the exact\n * strings, so they are defined once and registered with `register` / `getProxy`.\n */\nexport const widgetGuestService = defineRpcService<WidgetGuestService>('guest');\nexport const widgetGuestControlService =\n defineRpcService<WidgetGuestControlService>('guest-control');\nexport const widgetHostControlService = defineRpcService<WidgetHostControlService>('host-control');\nexport const widgetHostCapabilitiesService =\n defineRpcService<WidgetHostCapabilitiesService>('host-capabilities');\n\n/** The one member of {@link widgetHostControlService} that carries a transfer list. */\nexport const widgetHostEventMethod = 'event';\n\n/**\n * The slice of the device simulation guest the widget guest reaches over the direct port (RFC 0018).\n *\n * The assembly layer hands one end of a `MessageChannel` to each guest, so a widget publish reaches\n * the device guest and a device publish reaches the widget guest without the host relaying them.\n * `deliver` and `onDidPublish` are the whole data plane; everything else (schematic, topics, clock)\n * stays on the host side.\n */\nexport interface WidgetDeviceTopicChannel {\n /** Queues one payload for a device endpoint; consumed by the device guest's next step. */\n deliver(target: CanvasBindingTarget, payload: unknown, simTime?: number): Promise<void>;\n /** Subscribes to device publishes; the guest fans them out to its bound instances. */\n onDidPublish(listener: (publish: SimulationPublish) => void): () => void;\n}\n\n/**\n * Wire name of the contract above. It is deliberately the same id the device guest registers\n * (`@mica-js/simulator`'s `deviceSimulationHostGuestService`): the direct port is a second channel to\n * that guest, not a second protocol. The widget guest only declares the members it calls.\n */\nexport const widgetDeviceTopicService = defineRpcService<WidgetDeviceTopicChannel>('guest');\n","/**\n * Typed RPC contracts of the widget audio path (RFC 0016).\n *\n * Three endpoints carry the whole path:\n *\n * - the guest runtime talks to the `AudioWorklet` over a `MessagePort` it receives from the host;\n * - the host talks to the same worklet over the `AudioWorkletNode` port;\n * - the host pushes availability and the direct port into the guest over the sandbox RPC endpoint.\n *\n * `createRpc` serializes every call, so PCM stays on the worker ↔ worklet port and never passes\n * through the render host.\n */\n\nimport { defineRpcService } from '@mica-js/core/rpc';\n\n/** Name the worklet registers its processor under. */\nexport const widgetAudioWorkletProcessor = 'mica-widget-audio';\n\n/** Per-instance ceiling on simultaneous tones. */\nexport const defaultMaxVoices = 8;\n/** Per-instance ceiling on open PCM streams. */\nexport const defaultMaxStreams = 4;\n\n/** Availability of the host audio path. */\nexport type WidgetAudioState = 'unavailable' | 'suspended' | 'running';\n\n/** Why a tone or stream stopped. */\nexport type WidgetAudioEndReason =\n 'finished' | 'stopped' | 'dropped' | 'error' | 'unavailable' | 'disposed';\n\n/** Sample layout of a PCM stream. */\nexport type WidgetAudioFormat = 's16' | 'f32';\n\n/** Waveforms the worklet synthesizes for `api.audio.tone()`. */\nexport type WidgetOscillatorType = 'sine' | 'square' | 'triangle' | 'sawtooth';\n\n/** Playback state of a PCM stream, as the guest sees it. */\nexport type WidgetAudioStreamState = 'buffering' | 'playing' | 'ended' | 'closed';\n\n/** Per-instance ceilings; a host may tighten them through its options. */\nexport interface WidgetAudioLimits {\n readonly maxVoices: number;\n readonly maxStreams: number;\n}\n\n/** One mount generation of one instance, opened by the host before the guest can use it. */\nexport interface WidgetAudioSessionOpen {\n /** One-shot token every guest call must carry. */\n readonly session: string;\n /** Guest runtime that owns the token; a port from another runtime is rejected. */\n readonly runtimeId: string;\n readonly instanceId: string;\n readonly maxVoices: number;\n readonly maxStreams: number;\n}\n\nexport interface WidgetAudioToneInit {\n /** Guest-assigned id; unique per session. */\n readonly voiceId: string;\n readonly type: WidgetOscillatorType;\n /** Hz, `(0, 24000]`. */\n readonly frequency: number;\n /** `0`–`1`. */\n readonly volume: number;\n}\n\nexport interface WidgetAudioToneSettings {\n readonly volume?: number;\n readonly frequency?: number;\n /** Smoothing window in milliseconds, `0`–`10000`. */\n readonly rampMs: number;\n}\n\nexport interface WidgetAudioStop {\n /** Fade-out in milliseconds, `0`–`10000`. */\n readonly fadeMs: number;\n}\n\nexport interface WidgetAudioStreamInit {\n /** Guest-assigned id; unique per session. */\n readonly streamId: string;\n /** Source rate in Hz, `8000`–`96000`. */\n readonly sampleRate: number;\n readonly channels: 1 | 2;\n readonly format: WidgetAudioFormat;\n readonly capacityFrames: number;\n readonly startFrames: number;\n readonly volume: number;\n}\n\n/** Answer of `createStream`: the worklet re-checks the per-session quota. */\nexport interface WidgetAudioStreamOpened {\n readonly accepted: boolean;\n}\n\n/** Credit report; `consumedFrames` is cumulative over the stream's lifetime. */\nexport interface WidgetAudioProgress {\n readonly streamId: string;\n readonly consumedFrames: number;\n readonly underruns: number;\n readonly state: WidgetAudioStreamState;\n}\n\n/** Terminal event of one tone or stream. */\nexport interface WidgetAudioEndedMessage {\n readonly target: 'tone' | 'stream';\n readonly id: string;\n readonly reason: WidgetAudioEndReason;\n}\n\n/** Diagnostic codes the audio path reports. */\nexport type WidgetAudioDiagnosticCode = 'widget/audio-failed' | 'widget/audio-limit';\n\n/** Quota or validation class the receiving side dedupes against. */\nexport type WidgetAudioDiagnosticCategory = 'voices' | 'streams' | 'capacity' | 'worklet';\n\nexport interface WidgetAudioDiagnostic {\n /** Session the diagnostic belongs to; the host maps it back to the instance. */\n readonly session: string;\n readonly code: WidgetAudioDiagnosticCode;\n readonly category: WidgetAudioDiagnosticCategory;\n readonly message: string;\n}\n\n/**\n * Guest → worklet.\n *\n * Every member names a session; the worklet checks that the session belongs to the runtime that\n * owns the calling port, so a guest cannot steer another instance.\n */\nexport interface WidgetAudioWorkletService {\n createTone(session: string, init: WidgetAudioToneInit): void;\n setTone(session: string, voiceId: string, settings: WidgetAudioToneSettings): void;\n stopTone(session: string, voiceId: string, options: WidgetAudioStop): void;\n createStream(session: string, init: WidgetAudioStreamInit): WidgetAudioStreamOpened;\n /** `samples` travels as a transferred buffer; `true` means the whole block was accepted. */\n writeStream(session: string, streamId: string, samples: Int16Array | Float32Array): boolean;\n /** Drops everything that has not played yet and keeps the stream open. */\n clearStream(session: string, streamId: string): void;\n /** Drains the buffer, then ends the stream with `finished`. */\n endStream(session: string, streamId: string): void;\n /** Discards the buffer and closes the stream immediately. */\n closeStream(session: string, streamId: string): void;\n onDidProgress(listener: (progress: WidgetAudioProgress) => void): () => void;\n onDidEnded(listener: (ended: WidgetAudioEndedMessage) => void): () => void;\n}\n\nexport const widgetAudioWorkletService =\n defineRpcService<WidgetAudioWorkletService>('audio-worklet');\n\n/** Host → worklet, over the `AudioWorkletNode` port. */\nexport interface WidgetAudioControlService {\n openSession(init: WidgetAudioSessionOpen): void;\n closeSession(session: string): void;\n setSessionVolume(session: string, volume: number): void;\n setMuted(muted: boolean): void;\n suspend(): void;\n resume(): void;\n /** `port` is the guest end of the direct PCM channel; it is always transferred. */\n attachGuestPort(runtimeId: string, port: MessagePort): void;\n detachGuestPort(runtimeId: string): void;\n onDidDiagnostic(listener: (diagnostic: WidgetAudioDiagnostic) => void): () => void;\n}\n\nexport const widgetAudioControlService =\n defineRpcService<WidgetAudioControlService>('audio-control');\n\n/** Host → guest: audio availability and the direct PCM port handoff. */\nexport interface WidgetAudioGuestService {\n attachPort(port: MessagePort): void;\n setState(state: WidgetAudioState): void;\n}\n\nexport const widgetAudioGuestService = defineRpcService<WidgetAudioGuestService>('audio-guest');\n\n/** Attached to `mount` so the factory can read `api.audio.state` synchronously. */\nexport interface WidgetAudioMountInfo {\n readonly state: WidgetAudioState;\n /** One-shot token this mount generation uses on the direct port. */\n readonly session?: string;\n}\n","import workletScript from '../../guest/audio/entry.ts?audio-worklet-code';\nimport { widgetAudioWorkletProcessor } from '../../guest/audio/protocol';\n\nlet objectUrl: string | undefined;\n\n/**\n * Blob URL of the packaged `AudioWorkletProcessor` script.\n *\n * The script is bundled and minified into this module while the package is built, so an\n * `AudioContext` can load it through `addModule()` without the package publishing a separate\n * `*.worklet.js` asset. The URL is created once per page and reused by every host.\n */\nexport function widgetAudioWorkletUrl(): string {\n objectUrl ??= URL.createObjectURL(new Blob([workletScript], { type: 'text/javascript' }));\n return objectUrl;\n}\n\n/**\n * Loads the packaged processor into `context` and creates its node.\n *\n * Pass it as `getAudioWorklet` wherever a `WidgetHost` or `CanvasEditor` asks for one; hosts that\n * provide no loader of their own use the same processor internally.\n */\nexport async function createWidgetAudioWorklet(context: AudioContext): Promise<AudioWorkletNode> {\n if (typeof context.audioWorklet?.addModule !== 'function') {\n throw new Error('The AudioContext does not support AudioWorklet.addModule().');\n }\n await context.audioWorklet.addModule(widgetAudioWorkletUrl());\n return new AudioWorkletNode(context, widgetAudioWorkletProcessor);\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint, RpcProxy } from '@mica-js/core/rpc';\nimport {\n defaultMaxStreams,\n defaultMaxVoices,\n widgetAudioControlService,\n widgetAudioWorkletProcessor,\n} from '../../guest/audio/protocol';\nimport type {\n WidgetAudioControlService,\n WidgetAudioDiagnostic,\n WidgetAudioDiagnosticCode,\n WidgetAudioLimits,\n WidgetAudioMountInfo,\n WidgetAudioState,\n} from '../../guest/audio/protocol';\nimport { widgetAudioWorkletUrl } from './worklet';\n\n/** Structural stand-ins for the Web Audio nodes the engine touches; tests inject fakes. */\nexport interface AudioNodeLike {\n connect(destination: AudioNodeLike): unknown;\n disconnect?(): void;\n}\n\nexport interface AudioContextLike {\n readonly sampleRate: number;\n /** `suspended` | `running` | `closed` for a real context. */\n readonly state: string;\n readonly destination: AudioNodeLike;\n readonly audioWorklet?: { addModule(url: string): Promise<void> };\n /**\n * Fired by a real context whenever the browser suspends or resumes it on its own (autoplay\n * policy, hidden page, a caller calling `suspend()` / `resume()`). Used as a fallback when the\n * context lacks `addEventListener`; fakes may leave it `null`.\n */\n onstatechange?: ((event?: unknown) => void) | null;\n /** Preferred over `onstatechange`: subscribing must not clobber the caller's own handler. */\n addEventListener?(type: 'statechange', listener: () => void): void;\n removeEventListener?(type: 'statechange', listener: () => void): void;\n}\n\nexport interface AudioWorkletNodeLike extends AudioNodeLike {\n readonly port: MessagePort;\n}\n\nexport interface MessageChannelLike {\n readonly port1: MessagePort;\n readonly port2: MessagePort;\n}\n\n/** Host-side sinks the engine reports into; the widget host owns the sandbox plumbing. */\nexport interface WidgetAudioNotifier {\n /** Hands the direct guest ↔ worklet port to the sandbox. */\n emitPort(port: MessagePort): void;\n emitState(state: WidgetAudioState): void;\n}\n\nexport interface WidgetAudioEngineOptions {\n readonly context: AudioContextLike;\n readonly destination?: AudioNodeLike;\n readonly limits?: Partial<WidgetAudioLimits>;\n readonly report: (code: WidgetAudioDiagnosticCode, instanceId: string, message: string) => void;\n readonly notify: WidgetAudioNotifier;\n /** Loads the audio worklet node; tests or applications may provide their own loader. */\n readonly loadWorklet?: () => Promise<AudioWorkletNodeLike>;\n readonly createChannel?: () => MessageChannelLike;\n readonly createWorkletNode?: (context: AudioContextLike, name: string) => AudioWorkletNodeLike;\n}\n\ninterface InstanceAudio {\n readonly instanceId: string;\n readonly session: string;\n}\n\n/**\n * Host half of the audio path (RFC 0016).\n *\n * Owns the one `AudioWorkletNode`, the session tokens, and the two RPC endpoints that reach the\n * worklet: host controls over the node port, and the direct guest channel it hands to the sandbox.\n * No audio node other than that worklet is created here: tones, mixing and volume all live inside\n * the worklet.\n */\nexport class WidgetAudioEngine {\n readonly #context: AudioContextLike;\n readonly #destination: AudioNodeLike;\n readonly #report: WidgetAudioEngineOptions['report'];\n readonly #notify: WidgetAudioNotifier;\n readonly #limits: WidgetAudioLimits;\n readonly #loadWorklet: (() => Promise<AudioWorkletNodeLike>) | undefined;\n readonly #createChannel: () => MessageChannelLike;\n readonly #createWorkletNode: (context: AudioContextLike, name: string) => AudioWorkletNodeLike;\n readonly #runtimeId = `r${Math.random().toString(36).slice(2, 10)}`;\n readonly #instances = new Map<string, InstanceAudio>();\n #worklet: AudioWorkletNodeLike | undefined;\n #endpoint: RpcEndpoint | undefined;\n #control: RpcProxy<WidgetAudioControlService> | undefined;\n #booting: Promise<boolean> | undefined;\n #available: boolean | undefined;\n #muted = false;\n #suspended = false;\n #sessionCounter = 0;\n #disposed = false;\n #lastState: WidgetAudioState | undefined;\n #detachStateListener: (() => void) | undefined;\n /** Context state moved without an engine call; guests get the same ordered notification. */\n readonly #onContextStateChange = (): void => {\n if (this.#disposed) return;\n this.#syncState();\n };\n\n constructor(options: WidgetAudioEngineOptions) {\n this.#context = options.context;\n this.#destination = options.destination ?? options.context.destination;\n this.#report = options.report;\n this.#notify = options.notify;\n this.#limits = {\n maxVoices: Math.max(1, Math.floor(options.limits?.maxVoices ?? defaultMaxVoices)),\n maxStreams: Math.max(1, Math.floor(options.limits?.maxStreams ?? defaultMaxStreams)),\n };\n this.#loadWorklet = options.loadWorklet;\n this.#createChannel =\n options.createChannel ??\n (() => {\n const channel = new MessageChannel();\n return { port1: channel.port1, port2: channel.port2 };\n });\n this.#createWorkletNode =\n options.createWorkletNode ??\n ((context, name) => {\n const ctor = (\n globalThis as {\n AudioWorkletNode?: new (\n context: unknown,\n name: string,\n options: unknown,\n ) => AudioWorkletNodeLike;\n }\n ).AudioWorkletNode;\n if (!ctor) throw new Error('AudioWorkletNode is not available');\n return new ctor(context, name, {\n numberOfInputs: 0,\n numberOfOutputs: 1,\n outputChannelCount: [2],\n });\n });\n }\n\n /**\n * Current availability.\n *\n * `unavailable` means \"no audio at all\": the host configured none, the browser lacks\n * `AudioWorklet`, or the worklet module failed to load.\n */\n get state(): WidgetAudioState {\n if (this.#disposed || this.#available === false) return 'unavailable';\n if (this.#available !== true || this.#suspended) return 'suspended';\n return this.#context.state === 'running' ? 'running' : 'suspended';\n }\n\n /** Limits in force, so a caller can mirror them in its own UI. */\n get limits(): WidgetAudioLimits {\n return this.#limits;\n }\n\n /**\n * Opens the mount generation of one instance.\n *\n * Resolves once the worklet registered the session token, so the `mount` request that carries it\n * can never arrive after the first guest call of that generation.\n */\n async open(instanceId: string): Promise<WidgetAudioMountInfo> {\n if (this.#disposed) return { state: 'unavailable' };\n const available = await this.#boot();\n if (!available) return { state: 'unavailable' };\n\n this.close(instanceId);\n this.#sessionCounter += 1;\n const session = `${this.#runtimeId}-${this.#sessionCounter}`;\n this.#instances.set(instanceId, { instanceId, session });\n try {\n await this.#control?.openSession({\n session,\n runtimeId: this.#runtimeId,\n instanceId,\n maxVoices: this.#limits.maxVoices,\n maxStreams: this.#limits.maxStreams,\n });\n } catch (error) {\n this.#report(\n 'widget/audio-failed',\n instanceId,\n `The audio worklet rejected the session: ${describe(error)}`,\n );\n }\n this.#syncState();\n return { state: this.state, session };\n }\n\n setMuted(muted: boolean): void {\n this.#muted = muted === true;\n this.#call((control) => control.setMuted(this.#muted));\n }\n\n setInstanceVolume(instanceId: string, volume: number): void {\n if (typeof volume !== 'number') {\n throw new TypeError('WidgetHost.audio.setInstanceVolume expects a number');\n }\n if (!Number.isFinite(volume) || volume < 0 || volume > 1) {\n throw new RangeError('WidgetHost.audio.setInstanceVolume expects a value in [0, 1]');\n }\n const instance = this.#instances.get(instanceId);\n if (!instance) return;\n this.#call((control) => control.setSessionVolume(instance.session, volume));\n }\n\n /** Freezes audio without touching the caller's `AudioContext`. */\n suspend(): void {\n if (this.#disposed || this.#suspended) return;\n this.#suspended = true;\n this.#call((control) => control.suspend());\n this.#syncState();\n }\n\n resume(): void {\n if (this.#disposed) return;\n this.#suspended = false;\n this.#call((control) => control.resume());\n this.#syncState();\n }\n\n /**\n * Closes the instance only when it still belongs to `session`.\n *\n * A mount attempt that lost its id may have opened its own audio generation after the host's\n * cleanup sweep; closing by id alone would tear down the replacement instead.\n */\n closeSession(instanceId: string, session: string): void {\n const instance = this.#instances.get(instanceId);\n if (!instance || instance.session !== session) return;\n this.close(instanceId);\n }\n\n /** Drops one instance: its session token is revoked and the worklet ends its voices and streams. */\n close(instanceId: string): void {\n const instance = this.#instances.get(instanceId);\n if (!instance) return;\n this.#instances.delete(instanceId);\n this.#call((control) => control.closeSession(instance.session));\n }\n\n /**\n * Drops every instance and hands the worklet a fresh guest channel.\n *\n * Called when the sandbox goes away: the old guest port died with it, and the next sandbox needs\n * a port of its own.\n */\n reset(): void {\n for (const instanceId of [...this.#instances.keys()]) {\n this.close(instanceId);\n }\n if (this.#available === true && this.#control !== undefined) {\n void this.#restartRuntime();\n }\n }\n\n dispose(): void {\n if (this.#disposed) return;\n for (const instanceId of [...this.#instances.keys()]) {\n this.close(instanceId);\n }\n // Sent before the flag flips: the worklet drops the runtime, its sessions and its guest port.\n this.#call((control) => control.detachGuestPort(this.#runtimeId));\n this.#disposed = true;\n this.#detachStateListener?.();\n this.#detachStateListener = undefined;\n this.#endpoint?.dispose();\n this.#endpoint = undefined;\n this.#control = undefined;\n const worklet = this.#worklet;\n this.#worklet = undefined;\n if (worklet !== undefined) {\n closePort(worklet.port);\n try {\n worklet.disconnect?.();\n } catch {\n // Already detached.\n }\n }\n }\n\n /** Boots the worklet once; a failure is permanent for the lifetime of the engine. */\n #boot(): Promise<boolean> {\n this.#booting ??= this.#start().catch((error: unknown) => {\n this.#available = false;\n // A load that fails after `dispose()` is not a widget problem and has no live host to hear it.\n if (!this.#disposed) {\n this.#report('widget/audio-failed', '', `Widget audio is unavailable: ${describe(error)}`);\n }\n return false;\n });\n return this.#booting;\n }\n\n async #start(): Promise<boolean> {\n if (\n this.#loadWorklet === undefined &&\n typeof this.#context.audioWorklet?.addModule !== 'function'\n ) {\n this.#available = false;\n return false;\n }\n\n this.#listenForContextState();\n const worklet = await (this.#loadWorklet?.() ?? this.#loadDefaultWorklet());\n if (this.#disposed) {\n // `dispose()` ran while the module was loading: release the node instead of wiring it up.\n closePort(worklet.port);\n try {\n worklet.disconnect?.();\n } catch {\n // Already detached.\n }\n return false;\n }\n this.#worklet = worklet;\n const endpoint = createRpc(worklet.port);\n this.#endpoint = endpoint;\n const control = endpoint.getProxy(widgetAudioControlService, {\n transfer: (member, args) => (member === 'attachGuestPort' ? [args[1] as MessagePort] : []),\n });\n this.#control = control;\n control.onDidDiagnostic((diagnostic) => this.#onDiagnostic(diagnostic));\n worklet.connect(this.#destination);\n await this.#attachRuntime();\n this.#available = true;\n return true;\n }\n\n /**\n * Mirrors the context's own `statechange` onto mounted guests.\n *\n * The caller owns the `AudioContext`, so its state can move without the engine asking: autoplay\n * policy keeping it suspended, the browser suspending a hidden page, or the caller calling\n * `resume()`. Guests read `api.audio.state` and `onStateChange`, so those moves must be forwarded.\n */\n #listenForContextState(): void {\n if (this.#detachStateListener) return;\n const context = this.#context;\n if (typeof context.addEventListener === 'function') {\n context.addEventListener('statechange', this.#onContextStateChange);\n this.#detachStateListener = () =>\n context.removeEventListener?.('statechange', this.#onContextStateChange);\n return;\n }\n if (!('onstatechange' in context)) return;\n // Contexts that only expose the handler property keep the caller's value for `dispose()`.\n const previous = context.onstatechange;\n context.onstatechange = this.#onContextStateChange;\n this.#detachStateListener = () => {\n if (context.onstatechange === this.#onContextStateChange) context.onstatechange = previous;\n };\n }\n\n /** Worklet → host diagnostics, attributed back to the instance that owns the session. */\n #onDiagnostic(diagnostic: WidgetAudioDiagnostic): void {\n const owner = [...this.#instances.values()].find(\n (entry) => entry.session === diagnostic.session,\n );\n // A revoked token means the message is late; the RFC drops it instead of raising diagnostics.\n if (!owner) return;\n this.#report(diagnostic.code, owner.instanceId, diagnostic.message);\n }\n\n async #loadDefaultWorklet(): Promise<AudioWorkletNodeLike> {\n await this.#context.audioWorklet?.addModule(widgetAudioWorkletUrl());\n return this.#createWorkletNode(this.#context, widgetAudioWorkletProcessor);\n }\n\n async #restartRuntime(): Promise<void> {\n const control = this.#control;\n if (control === undefined) return;\n try {\n await control.detachGuestPort(this.#runtimeId);\n } catch {\n // The worklet already forgot the runtime; a new channel follows anyway.\n }\n await this.#attachRuntime();\n }\n\n /** Transfers a fresh port to the worklet and hands the other end to the guest. */\n async #attachRuntime(): Promise<void> {\n const control = this.#control;\n if (control === undefined || this.#disposed) return;\n const channel = this.#createChannel();\n try {\n await control.attachGuestPort(this.#runtimeId, channel.port1);\n } catch (error) {\n closePort(channel.port1);\n closePort(channel.port2);\n this.#report(\n 'widget/audio-failed',\n '',\n `The audio worklet rejected the guest port: ${describe(error)}`,\n );\n return;\n }\n this.#notify.emitPort(channel.port2);\n }\n\n /** Fires one host → worklet call; a missing or closed worklet is not a widget failure. */\n #call(run: (control: RpcProxy<WidgetAudioControlService>) => Promise<unknown>): void {\n const control = this.#control;\n if (control === undefined || this.#disposed) return;\n try {\n void run(control).catch(() => undefined);\n } catch {\n // The endpoint is already closed.\n }\n }\n\n #syncState(): void {\n const next = this.state;\n if (next === this.#lastState) return;\n this.#lastState = next;\n this.#notify.emitState(next);\n }\n}\n\nfunction closePort(port: MessagePort): void {\n try {\n port.close();\n } catch {\n // Already closed.\n }\n}\n\nfunction describe(error: unknown): string {\n if (error instanceof Error && error.message) return error.message;\n return typeof error === 'string' ? error : String(error);\n}\n","import type { WidgetAudioState } from '../../guest/audio/protocol';\nimport type { WidgetAudioControls } from './types';\n\n/**\n * Controls of a host that was created without `audio`.\n *\n * The state is `unavailable` and every setter is a no-op, so callers never have to branch on\n * whether audio is configured.\n */\nexport const NO_AUDIO_CONTROLS: WidgetAudioControls = {\n state: 'unavailable' as WidgetAudioState,\n setMuted(): void {},\n setInstanceVolume(): void {},\n suspend(): void {},\n resume(): void {},\n};\n","import type { PropertyDefinition } from '../../types';\nimport type { WidgetAssetRef } from './types';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\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/**\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: unknown): unknown {\n if (Array.isArray(value)) {\n return Object.freeze(value.map((item) => cloneFrozen(item)));\n }\n if (isPlainObject(value)) {\n const entries: [string, unknown][] = [];\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\nfunction isAssetMode(value: unknown): value is WidgetAssetRef['mode'] {\n return value === 'file' || value === 'inline' || value === 'store';\n}\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 */\nexport function mergeProperties(\n properties: Readonly<Record<string, PropertyDefinition>> | undefined,\n props: Readonly<Record<string, unknown>> | undefined,\n): Readonly<Record<string, unknown>> {\n const merged = new Map<string, unknown>();\n\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 ?? {})) {\n merged.set(key, props?.[key]);\n }\n\n return Object.freeze(Object.fromEntries(merged));\n}\n\n/**\n * Collects image / binary property values (`{ src, mode }`) from nested objects and arrays.\n * Results are keyed by `src`, so one resource referenced twice is only read once.\n */\nexport function collectAssetRefs(\n value: unknown,\n found: Map<string, WidgetAssetRef> = new Map(),\n seen: Set<object> = new Set(),\n): Map<string, WidgetAssetRef> {\n if (typeof value !== 'object' || value === null) return found;\n if (seen.has(value)) return found;\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) collectAssetRefs(item, found, seen);\n return found;\n }\n if (!isPlainObject(value)) return found;\n\n const candidate = value as { src?: unknown; mode?: unknown };\n if (typeof candidate.src === 'string' && isAssetMode(candidate.mode)) {\n if (!found.has(candidate.src)) {\n found.set(candidate.src, { src: candidate.src, mode: candidate.mode });\n }\n }\n for (const key of Object.keys(value)) collectAssetRefs(value[key], found, seen);\n return found;\n}\n","import { parsePayloadType } from '@mica-js/core/canvas';\nimport type { CanvasBindingCatalog, CanvasPortDescriptor } from '@mica-js/core/canvas';\nimport type { SchematicDocument } from '@mica-js/core/schematic';\nimport type { DeviceTopic } from '@mica-js/simulator';\nimport type { WidgetDefinition } from '../types';\n\n/** What the binding validator needs to know about one widget definition. */\ntype CatalogWidgetDefinition = NonNullable<ReturnType<CanvasBindingCatalog['widgetDefinition']>>;\n\n/** `symbol` + `port` pair as one map key; neither part can contain a NUL. */\nfunction portKey(symbol: string, port: string): string {\n return `${symbol}\\u0000${port}`;\n}\n\n/**\n * Catalog the host assembles itself (RFC 0018).\n *\n * Widget ports and properties come from the definitions `widgetProvider.resolve` returned, the\n * device side from `deviceHost.getTopics()` and the schematic the runtime loaded. A host with an\n * explicit `WidgetHostOptions.catalog` skips this one entirely.\n */\nexport class HostBindingCatalog implements CanvasBindingCatalog {\n readonly #definitions = new Map<string, CatalogWidgetDefinition>();\n #schematics = new Set<string>();\n #symbols = new Set<string>();\n #ports = new Map<string, CanvasPortDescriptor>();\n\n /** Whether the provider answered for `ref`; until it does, that widget stays unchecked. */\n knows(ref: string): boolean {\n return this.#definitions.has(ref);\n }\n\n /** Records one definition, so the synchronous validation no longer needs the provider. */\n recordDefinition(ref: string, definition: WidgetDefinition): void {\n this.#definitions.set(ref, {\n ports: definition.ports,\n propertyKeys: Object.keys(definition.properties),\n });\n }\n\n /**\n * Replaces the device side after a schematic load.\n *\n * `schematics` holds every path that identifies the loaded schematic (the reference the document\n * wrote and the absolute URI it resolved to); `topics` are the endpoints the running devices\n * report. A symbol the runtime does not report an endpoint for still counts as present when the\n * schematic lists it.\n */\n setDeviceFacts(options: {\n readonly schematics: readonly (string | undefined)[];\n readonly schematic: SchematicDocument | undefined;\n readonly topics: readonly DeviceTopic[];\n }): void {\n this.#schematics = new Set(\n options.schematics.filter((path): path is string => path !== undefined && path !== ''),\n );\n this.#symbols = new Set(options.schematic?.sheet.symbols.map((symbol) => symbol.id) ?? []);\n this.#ports = new Map();\n for (const topic of options.topics) {\n this.#symbols.add(topic.symbol);\n const type = parsePayloadType(topic.type);\n if (type === undefined) continue;\n this.#ports.set(portKey(topic.symbol, topic.port), {\n direction: topic.direction,\n type,\n });\n }\n }\n\n widgetDefinition(ref: string): CatalogWidgetDefinition | undefined {\n return this.#definitions.get(ref);\n }\n\n hasSchematic(path: string): boolean {\n return this.#schematics.has(path);\n }\n\n hasSymbol(symbolId: string): boolean {\n return this.#symbols.has(symbolId);\n }\n\n symbolPort(symbolId: string, port: string): CanvasPortDescriptor | undefined {\n return this.#ports.get(portKey(symbolId, port));\n }\n}\n","import { Emitter } from '@mica-js/core/lifecycle';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type {\n Widget,\n WidgetBinding,\n WidgetInstance,\n WidgetLayer,\n WidgetLayerChange,\n WidgetLayers,\n} from './types';\n\nexport interface WidgetInit {\n readonly instanceId: string;\n readonly widget: string;\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n readonly rotation: number;\n readonly dpr: number;\n readonly properties: Readonly<Record<string, unknown>>;\n readonly bindings: Readonly<Record<string, WidgetBinding>>;\n}\n\nexport interface WidgetPatch {\n readonly x?: number;\n readonly y?: number;\n readonly width?: number;\n readonly height?: number;\n readonly rotation?: number;\n readonly dpr?: number;\n readonly properties?: Readonly<Record<string, unknown>>;\n readonly bindings?: Readonly<Record<string, WidgetBinding>>;\n}\n\n/** Mutable backing record; the read-only `Widget` / `WidgetLayer` views are snapshots of it. */\ninterface WidgetRecord {\n readonly instanceId: string;\n widget: string;\n x: number;\n y: number;\n width: number;\n height: number;\n rotation: number;\n dpr: number;\n properties: Readonly<Record<string, unknown>>;\n bindings: Readonly<Record<string, WidgetBinding>>;\n bitmap: ImageBitmap | undefined;\n sequence: number;\n}\n\n/**\n * Instance table owned by the host.\n *\n * The table is the single source of the two projections RFC 0018 defines: `listInstances()` reads a\n * bulk view without bitmaps, and the four `onDid*` events report one change each with the complete\n * state. The legacy `WidgetLayers` view stays for the canvas editor: records mutate in place, so a\n * caller holding a layer from `get()` sees later frames without re-reading the table.\n */\nexport class WidgetStore implements WidgetLayers {\n readonly #records = new Map<string, WidgetRecord>();\n readonly #changes = new Set<(change: WidgetLayerChange) => void>();\n readonly #added = new Emitter<Widget>();\n readonly #updated = new Emitter<Widget>();\n readonly #removed = new Emitter<string>();\n readonly #reordered = new Emitter<readonly string[]>();\n\n /**\n * The four RFC 0018 events. A listener that throws is logged instead of breaking the document\n * flow, and the subscription itself is an ordinary {@link Disposable}.\n */\n readonly onDidAddWidget: Event<Widget> = (listener, thisArgs, disposables) =>\n this.#added.event(\n (widget) => invoke(listener, widget, 'widget add listener', thisArgs),\n undefined,\n disposables,\n );\n\n readonly onDidChangeWidget: Event<Widget> = (listener, thisArgs, disposables) =>\n this.#updated.event(\n (widget) => invoke(listener, widget, 'widget change listener', thisArgs),\n undefined,\n disposables,\n );\n\n readonly onDidRemoveWidget: Event<string> = (listener, thisArgs, disposables) =>\n this.#removed.event(\n (instanceId) => invoke(listener, instanceId, 'widget remove listener', thisArgs),\n undefined,\n disposables,\n );\n\n readonly onDidReorderWidgets: Event<readonly string[]> = (listener, thisArgs, disposables) =>\n this.#reordered.event(\n (order) => invoke(listener, order, 'widget reorder listener', thisArgs),\n undefined,\n disposables,\n );\n\n list(): readonly WidgetLayer[] {\n return [...this.#records.values()];\n }\n\n get(instanceId: string): WidgetLayer | undefined {\n return this.#records.get(instanceId);\n }\n\n listInstances(): readonly WidgetInstance[] {\n return [...this.#records.values()].map(toInstance);\n }\n\n subscribe(listener: (change: WidgetLayerChange) => void): () => void {\n this.#changes.add(listener);\n return () => {\n this.#changes.delete(listener);\n };\n }\n\n add(init: WidgetInit): Widget {\n this.remove(init.instanceId);\n const record: WidgetRecord = {\n instanceId: init.instanceId,\n widget: init.widget,\n x: init.x,\n y: init.y,\n width: init.width,\n height: init.height,\n rotation: init.rotation,\n dpr: init.dpr,\n properties: init.properties,\n bindings: init.bindings,\n bitmap: undefined,\n sequence: 0,\n };\n this.#records.set(init.instanceId, record);\n this.#emitChange({ type: 'added', instanceId: init.instanceId });\n this.#emitAdd(record);\n return record;\n }\n\n /**\n * Applies the document-derived fields of one instance and reports the ones that changed.\n *\n * @returns whether anything changed.\n */\n update(instanceId: string, patch: WidgetPatch): boolean {\n const record = this.#records.get(instanceId);\n if (!record) return false;\n\n let changed = false;\n if (patch.x !== undefined && patch.x !== record.x) {\n record.x = patch.x;\n changed = true;\n }\n if (patch.y !== undefined && patch.y !== record.y) {\n record.y = patch.y;\n changed = true;\n }\n if (patch.width !== undefined && patch.width !== record.width) {\n record.width = patch.width;\n changed = true;\n }\n if (patch.height !== undefined && patch.height !== record.height) {\n record.height = patch.height;\n changed = true;\n }\n if (patch.rotation !== undefined && patch.rotation !== record.rotation) {\n record.rotation = patch.rotation;\n changed = true;\n }\n if (patch.dpr !== undefined && patch.dpr !== record.dpr) {\n record.dpr = patch.dpr;\n changed = true;\n }\n if (patch.properties !== undefined && !sameRecord(record.properties, patch.properties)) {\n record.properties = patch.properties;\n changed = true;\n }\n if (patch.bindings !== undefined && !sameRecord(record.bindings, patch.bindings)) {\n record.bindings = patch.bindings;\n changed = true;\n }\n if (changed) this.#emitUpdate(record);\n return changed;\n }\n\n /** Installs a frame, closing the one it replaces, and bumps the sequence. */\n setBitmap(instanceId: string, bitmap: ImageBitmap): void {\n const record = this.#records.get(instanceId);\n if (!record) {\n closeBitmap(bitmap);\n return;\n }\n const previous = record.bitmap;\n record.bitmap = bitmap;\n record.sequence += 1;\n closeBitmap(previous);\n this.#emitUpdate(record);\n }\n\n remove(instanceId: string): void {\n const record = this.#records.get(instanceId);\n if (!record) return;\n this.#records.delete(instanceId);\n closeBitmap(record.bitmap);\n record.bitmap = undefined;\n this.#emitChange({ type: 'removed', instanceId });\n this.#emitRemove(instanceId);\n }\n\n /**\n * Rewrites drawing order to `instanceIds` without touching a frame.\n *\n * Ids the table does not hold are skipped, and records the caller did not list keep their\n * relative order at the end: a mount in flight owns an instance before the document entry that\n * created it is reconciled.\n */\n reorder(instanceIds: readonly string[]): void {\n const ordered = new Map<string, WidgetRecord>();\n for (const instanceId of instanceIds) {\n const record = this.#records.get(instanceId);\n if (record !== undefined) ordered.set(instanceId, record);\n }\n for (const [instanceId, record] of this.#records) {\n if (!ordered.has(instanceId)) ordered.set(instanceId, record);\n }\n if (sameOrder([...this.#records.keys()], [...ordered.keys()])) return;\n\n this.#records.clear();\n for (const [instanceId, record] of ordered) {\n this.#records.set(instanceId, record);\n }\n this.#emitChange({ type: 'reordered' });\n this.#reordered.fire([...this.#records.keys()]);\n }\n\n clear(): void {\n for (const instanceId of [...this.#records.keys()]) {\n this.remove(instanceId);\n }\n }\n\n /**\n * Reports every instance as removed and then added again, in drawing order, without touching a\n * record: a subscriber rebuilds its composite from the same bitmaps.\n */\n invalidate(): void {\n const records = [...this.#records.values()];\n for (const record of records) {\n this.#emitChange({ type: 'removed', instanceId: record.instanceId });\n this.#emitRemove(record.instanceId);\n }\n for (const record of records) {\n this.#emitChange({ type: 'added', instanceId: record.instanceId });\n this.#emitAdd(record);\n }\n }\n\n #emitUpdate(record: WidgetRecord): void {\n this.#emitChange({ type: 'updated', instanceId: record.instanceId });\n this.#updated.fire(toWidget(record));\n }\n\n #emitAdd(record: WidgetRecord): void {\n this.#added.fire(toWidget(record));\n }\n\n #emitRemove(instanceId: string): void {\n this.#removed.fire(instanceId);\n }\n\n #emitChange(change: WidgetLayerChange): void {\n for (const listener of [...this.#changes]) {\n invoke(listener, change, 'layer listener');\n }\n }\n}\n\nfunction toWidget(record: WidgetRecord): Widget {\n return {\n instanceId: record.instanceId,\n widget: record.widget,\n x: record.x,\n y: record.y,\n width: record.width,\n height: record.height,\n rotation: record.rotation,\n dpr: record.dpr,\n properties: record.properties,\n bindings: record.bindings,\n bitmap: record.bitmap,\n sequence: record.sequence,\n };\n}\n\nfunction toInstance(record: WidgetRecord): WidgetInstance {\n return {\n instanceId: record.instanceId,\n widget: record.widget,\n x: record.x,\n y: record.y,\n width: record.width,\n height: record.height,\n rotation: record.rotation,\n dpr: record.dpr,\n properties: record.properties,\n bindings: record.bindings,\n sequence: record.sequence,\n };\n}\n\nfunction invoke<T>(\n listener: (payload: T) => unknown,\n payload: T,\n name: string,\n thisArgs?: unknown,\n): void {\n try {\n listener.call(thisArgs, payload);\n } catch (error) {\n console.error(`[@mica-js/widget] ${name} threw`, error);\n }\n}\n\n/** Closes a bitmap without letting a double close escape. */\nexport function closeBitmap(bitmap: ImageBitmap | undefined): void {\n if (!bitmap) return;\n try {\n bitmap.close();\n } catch {\n // Already closed by its previous owner.\n }\n}\n\n/**\n * Shallow comparison of two record maps.\n *\n * The document owns property/binding values, so a nested object only counts as changed when the\n * caller replaced the object itself; deep equality would swallow those edits. The key sets matter\n * as much as the values, because a missing property key falls back to the definition default.\n */\nexport function sameRecord(\n left: Readonly<Record<string, unknown>>,\n right: Readonly<Record<string, unknown>>,\n): boolean {\n if (left === right) return true;\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every((key) => Object.hasOwn(right, key) && Object.is(left[key], right[key]))\n );\n}\n\nfunction sameOrder(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((id, index) => id === right[index]);\n}\n","import {\n CANVAS_VERSION,\n applyCanvasCommand,\n assertCanvasBindings,\n parseCanvas,\n validateCanvasBindings,\n} from '@mica-js/core/canvas';\nimport type {\n CanvasBindingTarget,\n CanvasCommand,\n CanvasDocument,\n CanvasWidgetInstance,\n WidgetPlacement,\n} from '@mica-js/core/canvas';\nimport {\n widgetAssetFailedEvent,\n widgetDeliverMethod,\n widgetErrorEvent,\n widgetFrameEvent,\n widgetLoadMethod,\n widgetMountMethod,\n widgetPointerMethod,\n widgetPublishEvent,\n widgetResetRuntimeMethod,\n widgetResizeMethod,\n widgetSetBindingsMethod,\n widgetSetPropertiesMethod,\n widgetUnmountMethod,\n} from '../guest/widget/protocol';\nimport type {\n WidgetAssetFailedMessage,\n WidgetErrorMessage,\n WidgetFrameMessage,\n WidgetPublishMessage,\n} from '../guest/widget/protocol';\nimport type { WidgetAudioMountInfo, WidgetAudioState } from '../guest/audio/protocol';\nimport { WidgetAudioEngine } from './audio/engine';\nimport type {\n AudioContextLike,\n AudioNodeLike,\n AudioWorkletNodeLike,\n WidgetAudioEngineOptions,\n} from './audio/engine';\nimport type { WidgetAudioControls } from './audio/types';\nimport { NO_AUDIO_CONTROLS } from './audio/noop';\nimport { decodeDataUri, decodeDataUriText } from '../host-fs/data-uri';\nimport { HostFsError } from '../host-fs/errors';\nimport type { HostFs } from '../host-fs/types';\nimport { isAbsoluteHostUri, resolveHostUri } from '../host-fs/uri';\nimport { collectAssetRefs, mergeProperties } from '../guest/widget/props';\nimport type { WidgetAssetRef, WidgetInputEvent } from '../guest/widget/types';\nimport type { WidgetModule, WidgetProvider } from '../types';\nimport type { Disposable, Event } from '@mica-js/core/lifecycle';\nimport type { DeviceSimulationHost, SimulationPublish } from '@mica-js/simulator';\nimport { HostBindingCatalog } from './catalog';\nimport { WidgetStore, sameRecord } from './widgets';\nimport type {\n Widget,\n WidgetAssetProvider,\n WidgetDiagnostic,\n WidgetDiagnosticCode,\n WidgetHost,\n WidgetHostMode,\n WidgetHostOptions,\n WidgetInstance,\n WidgetLayers,\n WidgetPublish,\n WidgetSandbox,\n WidgetSandboxFactory,\n} from './types';\ninterface InstanceRecord {\n readonly widget: string;\n /** Identifies the mount attempt that reserved this id, so late callbacks cannot adopt it. */\n readonly token: symbol;\n /** Placement last applied to this instance, so a pass can tell a real edit from a rewrite. */\n placement: WidgetPlacement;\n props: Readonly<Record<string, unknown>>;\n /** Binding map last handed to the guest, so an unchanged document sends nothing. */\n bindings: Readonly<Record<string, CanvasBindingTarget>>;\n /** `src` of every asset the mounted props referenced; the guest only holds prefetched bytes. */\n assets: ReadonlySet<string>;\n /** Audio session this attempt opened, released even when a newer record takes the id. */\n audioSession?: string;\n}\n\n/** Host state before any document was loaded. */\nconst EMPTY_DOCUMENT: CanvasDocument = { version: CANVAS_VERSION, widgets: [] };\n\n/** One fixed step, in milliseconds; the host converts it to picoseconds for the simulator. */\nconst DEFAULT_STEP_MS = 25;\nconst PS_PER_MS = 1_000_000_000;\n\ninterface FrameClockOptions {\n readonly stepMs: number;\n readonly requestFrame: (callback: () => void) => () => void;\n}\n\nfunction defaultRequestFrame(callback: () => void, delayMs: number): () => void {\n const timer = setTimeout(callback, delayMs);\n return () => {\n clearTimeout(timer);\n };\n}\n\n/** Startup or shutdown failure; already reported, so call sites must not report it twice. */\nclass WidgetRuntimeError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'WidgetRuntimeError';\n }\n}\n\n/**\n * The instance was removed (or the host disposed) while its mount was in flight. Rejecting keeps\n * `mount()` honest instead of resolving for an instance that no longer has a layer.\n */\nclass WidgetMountCancelledError extends Error {\n constructor(instanceId: string) {\n super(`Mount of widget instance \"${instanceId}\" was cancelled before it finished`);\n this.name = 'WidgetMountCancelledError';\n }\n}\n\n/**\n * Creates the widget host.\n *\n * The document is the single source of truth: instances are mounted, resized, repropped and\n * reordered to match it. The sandbox starts lazily on the first instance and every concurrent mount\n * shares that one startup, so a host with no instances never pays for an iframe and a worker. After\n * a crash the next reconciliation starts a fresh sandbox instead of rebuilding instances\n * automatically.\n */\nexport function createWidgetHost(\n options: WidgetHostOptions,\n createSandbox: WidgetSandboxFactory,\n): WidgetHost {\n return new WidgetHostImpl(options, createSandbox);\n}\n\nclass WidgetHostImpl implements WidgetHost {\n readonly #provider: WidgetProvider;\n readonly #fs: HostFs | undefined;\n readonly #container: HTMLElement | undefined;\n readonly #onDiagnostic: ((diagnostic: WidgetDiagnostic) => void) | undefined;\n readonly #onPublish: ((publish: WidgetPublish) => void) | undefined;\n readonly #assets: WidgetAssetProvider | undefined;\n readonly #catalog: WidgetHostOptions['catalog'];\n /** Catalog assembled from the widget provider and the running simulation (RFC 0018). */\n readonly #autoCatalog = new HostBindingCatalog();\n readonly #deviceHost: DeviceSimulationHost;\n #mode: WidgetHostMode;\n readonly #frameOptions: FrameClockOptions;\n readonly #createSandbox: WidgetSandboxFactory;\n readonly #audio: WidgetAudioEngine | undefined;\n readonly #store = new WidgetStore();\n readonly #instances = new Map<string, InstanceRecord>();\n readonly #detachers: (() => void)[] = [];\n readonly #documentListeners = new Set<(document: CanvasDocument) => void>();\n /** Input events waiting for the next step start; only used while a frame clock runs. */\n readonly #pendingInputs: { readonly instanceId: string; readonly event: WidgetInputEvent }[] = [];\n\n /** `WidgetHost.audio`; a no-op control surface when no audio was configured. */\n readonly audio: WidgetAudioControls;\n /** Port the worklet handed over before a sandbox existed; flushed on the next attach. */\n #pendingAudioPort: MessagePort | undefined;\n /** Latest availability, replayed to a sandbox that was created after the change. */\n #lastAudioState: WidgetAudioState | undefined;\n\n #document: CanvasDocument = EMPTY_DOCUMENT;\n /** Instances whose binding diagnostics prevent guest mounting for the current snapshot. */\n #bindingSkipped = new Set<string>();\n /** URI the current snapshot was read from; `undefined` for the parsed-document entry. */\n #documentUri: string | undefined;\n /** Absolute URI of the schematic the runtime was told to load. */\n #schematicUri: string | undefined;\n #unsubscribeDevicePublish: Disposable | undefined;\n #cancelFrame: (() => void) | undefined;\n #paused = false;\n #advancing = false;\n /** Whether a document was loaded; only then does the clock have something to advance. */\n #loaded = false;\n /** Last simulation time reported by the device host, used as a publish timestamp fallback. */\n #simTime = 0;\n /**\n * Last payload the simulation published per endpoint.\n *\n * A level topic only publishes when it changes, so an instance that mounts afterwards is seeded\n * from here instead of waiting for a change that may never come.\n */\n readonly #lastPublished = new Map<string, SimulationPublish>();\n #reconcilePending = false;\n /** The next coordination pass has to reset the guest before it syncs instances. */\n #resetPending = false;\n /** The next coordination pass has to reset the device before it resets the guest. */\n #deviceResetPending = false;\n /** The next coordination pass has to re-read the document and reload the schematic. */\n #reloadPending = false;\n #reloadSchematicPending = false;\n #reconcilePass: Promise<void> | undefined;\n /** Identifies the drain that owns {@link #reconcilePass}; only that drain may release it. */\n #reconcileOwner = 0;\n /**\n * One end of the direct device channel, consumed by the first sandbox this host starts.\n *\n * It is transferred to the guest at startup, so it cannot be reused: a restart runs in fallback.\n */\n #devicePort: MessagePort | undefined;\n /** True while the running guest owns the direct device channel and routes topic traffic itself. */\n #directDevice = false;\n #sandbox: WidgetSandbox | undefined;\n #starting: Promise<WidgetSandbox> | undefined;\n #disposing: Promise<void> | undefined;\n #disposed = false;\n #dpr: number;\n\n constructor(options: WidgetHostOptions, createSandbox: WidgetSandboxFactory) {\n const provider = options.widgetProvider ?? options.provider;\n if (provider === undefined) {\n throw new TypeError('createWidgetHost requires a widgetProvider');\n }\n this.#provider = provider;\n this.#fs = options.fs;\n this.#container = options.container;\n this.#onDiagnostic = options.onDidReportDiagnostic ?? options.onDiagnostic;\n this.#onPublish = options.onDidPublish ?? options.onPublish;\n this.#assets = options.assets;\n this.#catalog = options.catalog;\n this.#deviceHost = options.deviceHost;\n this.#devicePort = options.devicePort;\n this.#mode = options.mode ?? 'simulation';\n const frame = options.frame;\n const stepMs =\n frame?.stepMs !== undefined && Number.isFinite(frame.stepMs) && frame.stepMs > 0\n ? frame.stepMs\n : DEFAULT_STEP_MS;\n this.#frameOptions = {\n // The public interval is milliseconds; the simulator remains expressed in picoseconds.\n stepMs,\n requestFrame: frame?.requestFrame ?? ((callback) => defaultRequestFrame(callback, stepMs)),\n };\n this.#createSandbox = createSandbox;\n this.#dpr = options.dpr ?? currentDevicePixelRatio();\n\n let audio: WidgetAudioEngine | undefined;\n if (options.audio !== undefined) {\n const getAudioWorklet = options.audio.getAudioWorklet;\n const context = options.audio.context;\n const audioOptions: WidgetAudioEngineOptions = {\n context: context as unknown as AudioContextLike,\n report: (code, instanceId, message) =>\n this.#report(code, message, this.#instanceIds(instanceId)),\n notify: {\n emitPort: (port) => this.#emitAudioPort(port),\n emitState: (state) => this.#emitAudioState(state),\n },\n };\n if (options.audio.destination !== undefined) {\n Object.assign(audioOptions, {\n destination: options.audio.destination as unknown as AudioNodeLike,\n });\n }\n if (getAudioWorklet !== undefined) {\n Object.assign(audioOptions, {\n loadWorklet: () => getAudioWorklet(context) as Promise<AudioWorkletNodeLike>,\n });\n }\n if (options.audio.limits !== undefined) {\n Object.assign(audioOptions, { limits: options.audio.limits });\n }\n audio = new WidgetAudioEngine(audioOptions);\n }\n this.#audio = audio;\n this.audio = this.#audio ?? NO_AUDIO_CONTROLS;\n this.#unsubscribeDevicePublish = this.#deviceHost.onDidPublish((publish) => {\n if (this.#mode === 'simulation') this.#onSimulationPublish(publish);\n });\n }\n\n getDocument(): CanvasDocument {\n return this.#document;\n }\n\n getMode(): WidgetHostMode {\n return this.#mode;\n }\n\n async setMode(mode: WidgetHostMode): Promise<void> {\n if (this.#disposed) throw new WidgetRuntimeError('Widget host is disposed');\n if (mode === this.#mode) return;\n\n const previous = this.#mode;\n this.#stopClock();\n this.#pendingInputs.length = 0;\n try {\n this.#clearWidgetInstances();\n this.#resetPending = true;\n this.#deviceResetPending = true;\n this.#reloadPending = false;\n this.#reloadSchematicPending = false;\n this.#mode = mode;\n await this.#scheduleReconcile();\n if (this.#mode === 'simulation' && this.#loaded && !this.#paused) this.#startClock();\n } catch (error) {\n this.#mode = previous;\n if (previous === 'simulation' && this.#loaded && !this.#paused) this.#startClock();\n throw error;\n }\n }\n\n getLayers(): WidgetLayers {\n return this.#store;\n }\n\n listInstances(): readonly WidgetInstance[] {\n return this.#store.listInstances();\n }\n\n onDidAddWidget: Event<Widget> = this.#store.onDidAddWidget;\n\n onDidChangeWidget: Event<Widget> = this.#store.onDidChangeWidget;\n\n onDidRemoveWidget: Event<string> = this.#store.onDidRemoveWidget;\n\n onDidReorderWidgets: Event<readonly string[]> = this.#store.onDidReorderWidgets;\n\n invalidate(): void {\n if (this.#disposed) return;\n this.#store.invalidate();\n }\n\n pause(): void {\n this.#paused = true;\n this.#stopClock();\n }\n\n resume(): void {\n if (this.#disposed) return;\n this.#paused = false;\n // The clock re-times from now: the time spent paused never becomes backlog.\n if (this.#loaded) this.#startClock();\n }\n\n async loadDocument(source: CanvasDocument | string): Promise<void> {\n const documentUri = typeof source === 'string' ? source : undefined;\n const input = documentUri === undefined ? source : await this.#readDocumentText(documentUri);\n const parsed = parseCanvas(input);\n // RFC 0018 steps 2–5: the schematic is loaded before instances mount, and a schematic that\n // cannot be read or parsed rejects the whole load instead of mounting half a canvas. Bindings\n // validate afterwards, because the catalog can only resolve symbols of the loaded schematic;\n // a rejected check still leaves the previous document and instances in place.\n const schematicUri = this.#resolveSchematicUri(parsed, documentUri);\n await this.#loadSchematic(schematicUri);\n // RFC 0018: the host assembles the binding catalog from what is now running, so the checks see\n // the endpoints of the schematic that was just loaded rather than the previous one.\n await this.#refreshCatalog(parsed, parsed.schematic, schematicUri);\n const bindingSkipped = this.#bindingSkipIds(parsed);\n this.#documentUri = documentUri;\n this.#schematicUri = schematicUri;\n this.#commit(parsed, bindingSkipped);\n const pass = this.#scheduleReconcile();\n this.#emitDocument(parsed);\n await pass;\n this.#loaded = true;\n if (this.#mode === 'simulation') this.#startClock();\n }\n\n /**\n * Reads a document URI: `data:` decodes locally, every other scheme goes through `fs`.\n *\n * Relative references never reach the reader; the caller supplies an absolute URI, which is also\n * what `HostFs.read` expects.\n */\n async #readDocumentText(uri: string): Promise<string> {\n if (!isAbsoluteHostUri(uri)) {\n throw new TypeError(`WidgetHost.loadDocument requires an absolute URI: ${uri}`);\n }\n if (uri.slice(0, 5).toLowerCase() === 'data:') {\n return decodeDataUriText(uri);\n }\n const fs = this.#fs;\n if (fs === undefined) {\n throw new HostFsError(\n 'NoFileSystem',\n uri,\n 'WidgetHost has no HostFs configured to read this document URI',\n );\n }\n return new TextDecoder().decode(await fs.read(uri));\n }\n\n /**\n * Resolves the document's `schematic` reference against the canvas URI.\n *\n * `undefined` clears the runtime. An absolute reference passes through; a relative one needs the\n * canvas URI as its base, so the parsed-document form can only carry absolute references.\n */\n #resolveSchematicUri(\n document: CanvasDocument,\n documentUri: string | undefined,\n ): string | undefined {\n const schematic = document.schematic;\n if (schematic === undefined || schematic === '') return undefined;\n if (documentUri === undefined) return schematic;\n return resolveHostUri(documentUri, schematic);\n }\n\n /** Loads (or clears) the schematic on the device host. */\n async #loadSchematic(uri: string | undefined): Promise<void> {\n await this.#deviceHost.loadSchematic(uri);\n }\n\n applyCommand(command: CanvasCommand): void {\n // Both steps throw before the snapshot is committed, so a rejected command changes nothing.\n const document = applyCanvasCommand(this.#document, command);\n const bindingSkipped = this.#bindingSkipIds(document);\n this.#commit(document, bindingSkipped);\n void this.#scheduleReconcile();\n this.#emitDocument(document);\n }\n\n onDocumentChange(listener: (document: CanvasDocument) => void): () => void {\n this.#documentListeners.add(listener);\n return () => {\n this.#documentListeners.delete(listener);\n };\n }\n\n reset(): Promise<void> {\n if (this.#disposed) {\n return Promise.reject(new WidgetRuntimeError('Widget host is disposed'));\n }\n return this.#resetRuntime({\n reloadDocument: this.#documentUri !== undefined,\n reloadSchematic: this.#schematicUri !== undefined,\n resetDevice: true,\n });\n }\n\n #clearWidgetInstances(): void {\n for (const instanceId of this.#instances.keys()) {\n this.#audio?.close(instanceId);\n }\n this.#instances.clear();\n this.#store.clear();\n }\n\n async #resetRuntime(options: {\n readonly reloadDocument: boolean;\n readonly reloadSchematic: boolean;\n readonly resetDevice: boolean;\n }): Promise<void> {\n this.#stopClock();\n this.#pendingInputs.length = 0;\n this.#clearWidgetInstances();\n this.#resetPending = true;\n this.#deviceResetPending = options.resetDevice;\n this.#reloadPending = options.reloadDocument;\n this.#reloadSchematicPending = options.reloadSchematic;\n await this.#scheduleReconcile();\n if (this.#mode === 'simulation' && this.#loaded && !this.#paused) this.#startClock();\n }\n\n deliver(instanceId: string, port: string, payload: unknown, simTime: number): void {\n if (!this.#requireInstance(instanceId)) return;\n this.#fire(\n 'widget/deliver-failed',\n widgetDeliverMethod,\n [instanceId, port, payload, simTime],\n instanceId,\n );\n }\n\n dispatch(instanceId: string, event: WidgetInputEvent): void {\n if (!this.#requireInstance(instanceId)) return;\n // RFC 0018: input arrives whenever it wants and is dispatched at the next step start.\n if (this.#loaded) {\n this.#pendingInputs.push({ instanceId, event });\n return;\n }\n this.#fire('widget/deliver-failed', widgetPointerMethod, [instanceId, event], instanceId);\n }\n\n resize(dpr: number): void {\n if (!Number.isFinite(dpr) || dpr <= 0 || dpr === this.#dpr) return;\n this.#dpr = dpr;\n\n for (const layer of this.#store.list()) {\n this.#store.update(layer.instanceId, { dpr });\n this.#fire(\n 'widget/render-failed',\n widgetResizeMethod,\n [layer.instanceId, layer.width, layer.height, dpr],\n layer.instanceId,\n );\n }\n }\n\n dispose(): Promise<void> {\n const pending = this.#disposing ?? this.#shutdown();\n this.#disposing = pending;\n return pending;\n }\n\n /**\n * Runs the binding checks both document entry points share.\n *\n * An explicit `catalog` option wins. Otherwise the host checks against the catalog it assembled\n * from the widget provider and the running simulation (RFC 0018).\n */\n #bindingSkipIds(document: CanvasDocument): ReadonlySet<string> {\n const explicit = this.#catalog;\n const catalog = explicit ?? this.#autoCatalog;\n // A reference the provider has not answered for yet stays unchecked until the next pass.\n const resolved =\n explicit !== undefined ||\n document.widgets.every((widget) => this.#autoCatalog.knows(widget.widget));\n const diagnostics = validateCanvasBindings(\n document,\n resolved ? { catalog } : { catalog, skipWidgets: true },\n );\n const bindingCodes = new Set([\n 'canvas/unknown-symbol',\n 'canvas/unknown-target-port',\n 'canvas/unknown-port',\n 'topic/type-mismatch',\n ]);\n const rejectsDocument = diagnostics.some((diagnostic) => {\n const pointer = diagnostic.pointer ?? '';\n return (\n !bindingCodes.has(diagnostic.code) || !/^\\/widgets\\/\\d+\\/bindings(?:\\/|$)/.test(pointer)\n );\n });\n if (rejectsDocument)\n assertCanvasBindings(document, resolved ? { catalog } : { catalog, skipWidgets: true });\n const skipped = new Set<string>();\n for (const diagnostic of diagnostics) {\n if (!bindingCodes.has(diagnostic.code)) continue;\n const match = /^\\/widgets\\/(\\d+)\\/bindings(?:\\/|$)/.exec(diagnostic.pointer ?? '');\n if (match === null) continue;\n const widget = document.widgets[Number(match[1])];\n if (widget !== undefined) {\n skipped.add(widget.id);\n this.#reportBindingDiagnostic(\n widget,\n diagnostic.code,\n diagnostic.message,\n diagnostic.pointer,\n );\n }\n }\n return skipped;\n }\n\n /**\n * Re-assembles the automatic catalog after the device host loaded a schematic (RFC 0018).\n *\n * The device side is read once the load resolved, so `getTopics()` and `getSchematic()` describe\n * the runtime the instances will talk to; the widget side resolves every reference the document\n * names before validation runs.\n */\n async #refreshCatalog(\n document: CanvasDocument,\n schematic: string | undefined,\n schematicUri: string | undefined,\n ): Promise<void> {\n // An explicit catalog is the caller's, so nothing has to be assembled.\n if (this.#catalog !== undefined) return;\n const deviceHost = this.#deviceHost;\n const [topics, loaded] = await Promise.all([deviceHost.getTopics(), deviceHost.getSchematic()]);\n this.#autoCatalog.setDeviceFacts({\n schematics: [schematic, schematicUri],\n schematic: loaded,\n topics,\n });\n await this.#resolveDefinitions(document);\n }\n\n /**\n * Resolves the widget definitions the document references, so validation itself stays synchronous.\n *\n * A rejection or an unknown reference is only recorded as \"not resolved\": the mount of every\n * instance using it reports the failure on its own.\n */\n async #resolveDefinitions(document: CanvasDocument): Promise<void> {\n const refs = new Set(document.widgets.map((widget) => widget.widget));\n await Promise.all(\n [...refs].map(async (ref) => {\n if (this.#autoCatalog.knows(ref)) return;\n try {\n const module = await this.#provider.resolve(ref);\n if (module !== undefined) this.#autoCatalog.recordDefinition(ref, module.definition);\n } catch {\n // Reported when an instance of this reference mounts.\n }\n }),\n );\n }\n\n /**\n * Makes `document` the new snapshot and drops the instances it no longer lists.\n *\n * Removal is synchronous on purpose: a mount still in flight for a removed id has to be cancelled\n * right away, while the coordination pass that would have removed it may be blocked on it.\n */\n #commit(document: CanvasDocument, bindingSkipped: ReadonlySet<string> = new Set()): void {\n this.#document = document;\n this.#bindingSkipped = new Set(bindingSkipped);\n const live = new Set(document.widgets.map((widget) => widget.id));\n for (const instanceId of [...this.#instances.keys()]) {\n if (!live.has(instanceId)) this.#unmount(instanceId);\n }\n }\n\n /**\n * Queues a coordination pass and returns the running queue.\n *\n * A pass reads {@link document} per instance, so everything committed while it waits is coalesced\n * into the next iteration; the promise settles only once the queue has caught up.\n *\n * The drain starts on a microtask instead of from here: {@link #syncInstances} notifies the layer\n * store synchronously from inside a guest await, and a subscriber that applies a command from that\n * notification would otherwise re-enter while the slot below is still empty and start a second,\n * concurrent drain.\n */\n #scheduleReconcile(): Promise<void> {\n this.#reconcilePending = true;\n this.#reconcilePass ??= Promise.resolve().then(() => this.#drainReconcile());\n return this.#reconcilePass;\n }\n\n async #drainReconcile(): Promise<void> {\n const owner = ++this.#reconcileOwner;\n try {\n while (this.#reconcilePending && !this.#disposed) {\n this.#reconcilePending = false;\n if (this.#reloadPending) {\n this.#reloadPending = false;\n await this.#reloadDocument();\n }\n if (this.#deviceResetPending) {\n this.#deviceResetPending = false;\n await this.#deviceHost.reset();\n this.#simTime = await this.#deviceHost.getSimTime();\n // The circuit is back at its initial state; the next step publishes every topic again.\n this.#lastPublished.clear();\n }\n if (this.#resetPending) {\n this.#resetPending = false;\n await this.#resetGuestRuntime();\n if (this.#reloadSchematicPending) {\n this.#reloadSchematicPending = false;\n await this.#reloadSchematic();\n }\n }\n await this.#syncInstances();\n }\n } finally {\n // A stale finish must never untrack a newer pass that is still mounting, so only the drain\n // that owns the slot releases it.\n if (this.#reconcileOwner === owner) {\n this.#reconcilePending = false;\n this.#reconcilePass = undefined;\n }\n }\n }\n\n /**\n * Re-reads the document behind the current URI, for `reset()`.\n *\n * A document that no longer parses is reported instead of rejecting: the reset still has to put\n * the instances back with the snapshot the host already holds.\n */\n async #reloadDocument(): Promise<void> {\n const uri = this.#documentUri;\n if (uri === undefined) return;\n try {\n const parsed = parseCanvas(await this.#readDocumentText(uri));\n const bindingSkipped = this.#bindingSkipIds(parsed);\n this.#schematicUri = this.#resolveSchematicUri(parsed, uri);\n this.#commit(parsed, bindingSkipped);\n this.#emitDocument(parsed);\n } catch (error) {\n this.#report(\n 'widget/runtime-failed',\n `The canvas document \"${uri}\" could not be reloaded: ${describeError(error)}`,\n );\n }\n }\n\n /** Re-executes the runtime half of `loadDocument`: the schematic goes back to time 0. */\n async #reloadSchematic(): Promise<void> {\n try {\n await this.#loadSchematic(this.#schematicUri);\n await this.#refreshCatalog(this.#document, this.#document.schematic, this.#schematicUri);\n } catch (error) {\n this.#report(\n 'widget/runtime-failed',\n `The schematic could not be reloaded: ${describeError(error)}`,\n );\n }\n }\n\n /** Mounts, resizes, sets properties and reorders instances to match the document. */\n async #syncInstances(): Promise<void> {\n for (const { id: instanceId } of this.#document.widgets) {\n if (this.#disposed) return;\n // A newer snapshot may have dropped this id while the previous instance was mounting.\n const widget = this.#document.widgets.find((entry) => entry.id === instanceId);\n if (widget === undefined) continue;\n if (this.#bindingSkipped.has(instanceId)) {\n if (this.#instances.has(instanceId)) this.#unmount(instanceId);\n continue;\n }\n await this.#syncInstance(widget);\n }\n this.#store.reorder(this.#document.widgets.map((widget) => widget.id));\n }\n\n async #syncInstance(widget: CanvasWidgetInstance): Promise<void> {\n const existing = this.#instances.get(widget.id);\n if (existing === undefined) {\n await this.#mount(widget);\n return;\n }\n if (existing.widget !== widget.widget) {\n // Nothing in the document retargets an instance in place, so replacing it is the only way to\n // keep one layer from mixing two widget definitions.\n this.#unmount(widget.id);\n await this.#mount(widget);\n return;\n }\n\n const placement = placementOf(widget);\n const props = widget.properties ?? {};\n // Geometry and properties are host-side state: record them before the guest call, so a\n // subscriber sees the document value even when the guest render fails.\n this.#store.update(widget.id, {\n ...placement,\n properties: props,\n bindings: widget.bindings ?? {},\n });\n\n // `x`, `y` and `rotation` only move the composite position, which the document already carries;\n // only a size change has to reach the guest.\n if (\n placement.width !== existing.placement.width ||\n placement.height !== existing.placement.height\n ) {\n this.#resizeGuest(widget.id, placement.width, placement.height);\n }\n existing.placement = placement;\n\n const bindings = widget.bindings ?? {};\n if (!sameBindings(existing.bindings, bindings)) {\n // A rebound port changes which endpoint the guest routes to, so a routing guest has to know.\n this.#setBindings(widget.id, bindings);\n }\n\n if (!sameRecord(existing.props, props)) {\n // Bytes are prefetched once, at mount: the guest cannot read a resource the host never sent,\n // so a property that names a new image re-mounts instead of reaching an empty asset map.\n if (this.#referencesUnprefetchedAsset(existing, props)) {\n this.#unmount(widget.id);\n await this.#mount(widget);\n return;\n }\n this.#setProperties(widget.id, props);\n }\n }\n\n #referencesUnprefetchedAsset(\n existing: InstanceRecord,\n props: Readonly<Record<string, unknown>>,\n ): boolean {\n if (this.#assets === undefined) return false;\n for (const src of collectAssetRefs(props).keys()) {\n if (!existing.assets.has(src)) return true;\n }\n return false;\n }\n\n /**\n * Mounts one document instance. Failures stay inside that instance: the mount attempt already\n * reported its own diagnostic, and the document is never rolled back for it.\n */\n async #mount(widget: CanvasWidgetInstance): Promise<void> {\n try {\n await this.#startInstance(widget);\n } catch {\n // Already reported, or a newer snapshot cancelled this mount; the next pass resumes from the\n // current document either way.\n }\n }\n\n async #startInstance(widget: CanvasWidgetInstance): Promise<void> {\n const { id: instanceId, widget: ref } = widget;\n\n if (this.#disposed) {\n this.#report('widget/runtime-failed', 'The widget host is disposed.', {\n instanceId,\n widget: ref,\n });\n throw new WidgetRuntimeError('Widget host is disposed');\n }\n if (this.#instances.has(instanceId)) {\n this.#report(\n 'widget/instance-exists',\n `Widget instance \"${instanceId}\" is already mounted.`,\n { instanceId, widget: ref },\n );\n return;\n }\n\n // Reserve the id before the first await: a concurrent mount of the same instance now loses\n // here instead of racing into the guest and tearing down the winner's record and layer.\n const record: InstanceRecord = {\n widget: ref,\n token: Symbol(instanceId),\n placement: placementOf(widget),\n props: widget.properties ?? {},\n bindings: widget.bindings ?? {},\n assets: new Set<string>(),\n };\n this.#instances.set(instanceId, record);\n this.#store.add({\n instanceId,\n widget: ref,\n ...record.placement,\n dpr: this.#dpr,\n properties: record.props,\n bindings: widget.bindings ?? {},\n });\n this.#store.reorder(this.#document.widgets.map((entry) => entry.id));\n\n let mounted = false;\n try {\n mounted = await this.#mountInstance(instanceId, ref, record);\n } finally {\n // A cancelled or failed attempt only drops its own reservation.\n if (!mounted) this.#forget(instanceId, record);\n }\n // The instance exists in the guest now, so the live level of every bound endpoint can be sent,\n // and a guest that routes on its own learns which endpoint each port talks to.\n if (mounted) {\n this.#setBindings(instanceId, record.bindings);\n this.#replayPublished(widget);\n }\n }\n\n /**\n * Runs one mount attempt; every await re-checks that this attempt still owns the id.\n *\n * @returns always `true`; a cancelled attempt throws instead of reporting success.\n */\n async #mountInstance(instanceId: string, ref: string, record: InstanceRecord): Promise<boolean> {\n let module: WidgetModule | undefined;\n try {\n module = await this.#provider.resolve(ref);\n } catch (error) {\n this.#report(\n 'widget/mount-failed',\n `Widget \"${ref}\" could not be resolved: ${describeError(error)}`,\n { instanceId, widget: ref },\n );\n throw error;\n }\n\n const resolved = module === undefined ? undefined : splitRef(ref);\n if (module === undefined || resolved === undefined) {\n this.#report(\n 'widget/unknown-widget',\n module === undefined\n ? `No widget is registered as \"${ref}\".`\n : `Widget reference \"${ref}\" must use the \"<package>:<widget>\" form.`,\n { instanceId, widget: ref },\n );\n return false;\n }\n this.#autoCatalog.recordDefinition(ref, module.definition);\n this.#requireOwnership(instanceId, record);\n\n const sandbox = await this.#ensureSandbox();\n this.#requireOwnership(instanceId, record);\n\n try {\n await sandbox.call(widgetLoadMethod, {\n packages: [\n {\n id: resolved.packageId,\n modules: {\n [resolved.widgetId]: { definition: module.definition, code: module.code },\n },\n },\n ],\n });\n this.#requireOwnership(instanceId, record);\n\n // The guest merges defaults again on its own, so a definition that changes between load and\n // mount still behaves the same on both sides of the boundary.\n const props = mergeProperties(module.definition?.properties, record.props);\n const assets = await this.#prefetchAssets(instanceId, ref, props);\n record.assets = new Set(collectAssetRefs(props).keys());\n this.#requireOwnership(instanceId, record);\n\n const layer = this.#store.get(instanceId);\n if (!layer) throw new WidgetMountCancelledError(instanceId);\n // The mount token goes out before the guest can open a stream with it.\n const audio: WidgetAudioMountInfo =\n this.#audio === undefined ? { state: 'unavailable' } : await this.#audio.open(instanceId);\n if (audio.session !== undefined) record.audioSession = audio.session;\n this.#requireOwnership(instanceId, record);\n await sandbox.call(widgetMountMethod, {\n instanceId,\n widget: ref,\n width: layer.width,\n height: layer.height,\n dpr: layer.dpr,\n props,\n ...(assets === undefined ? {} : { assets }),\n audio,\n });\n } catch (error) {\n if (error instanceof WidgetRuntimeError) throw error;\n if (error instanceof WidgetMountCancelledError) throw error;\n // Disposal is the caller's own doing, not a widget failure; report it as a cancellation.\n if (this.#disposed) throw new WidgetMountCancelledError(instanceId);\n if (this.#isTerminated()) {\n this.#failRuntime('The widget sandbox terminated during mount.');\n throw error;\n }\n this.#report(\n 'widget/mount-failed',\n `Widget \"${ref}\" failed to mount: ${describeError(error)}`,\n { instanceId, widget: ref },\n );\n throw error;\n }\n\n if (!this.#owns(instanceId, record)) {\n // The mount was cancelled while the guest was creating the instance. Release that session,\n // otherwise an unmounted id keeps a canvas, subscriptions and timers alive for good. A newer\n // record for the same id is skipped: the guest keys sessions by id, so a late release would\n // tear down the replacement's session instead of ours.\n if (!this.#instances.has(instanceId)) {\n await releaseGuestInstance(sandbox, instanceId);\n }\n throw new WidgetMountCancelledError(instanceId);\n }\n return true;\n }\n\n #unmount(instanceId: string): void {\n const instance = this.#instances.get(instanceId);\n if (!instance) {\n this.#report('widget/instance-not-found', `Widget instance \"${instanceId}\" is not mounted.`, {\n instanceId,\n });\n return;\n }\n\n this.#forget(instanceId, instance);\n this.#fire(undefined, widgetUnmountMethod, [instanceId], instanceId);\n }\n\n /** Repaints one instance at a new size; the store already carries the new geometry. */\n #resizeGuest(instanceId: string, width: number, height: number): void {\n if (!this.#requireInstance(instanceId)) return;\n const layer = this.#store.get(instanceId);\n if (!layer) return;\n this.#fire(\n 'widget/render-failed',\n widgetResizeMethod,\n [instanceId, width, height, layer.dpr],\n instanceId,\n );\n }\n\n #setProperties(instanceId: string, props: Readonly<Record<string, unknown>>): void {\n const instance = this.#requireInstance(instanceId);\n if (!instance) return;\n instance.props = props;\n this.#fire('widget/render-failed', widgetSetPropertiesMethod, [instanceId, props], instanceId);\n }\n\n /**\n * Hands one instance's binding map to the guest.\n *\n * Only a guest with the direct device channel needs it: that guest then routes publishes to the\n * device and device publishes back to the instance. A guest without one keeps the host as its only\n * router, so the call is skipped rather than sent into a runtime that ignores it.\n */\n #setBindings(instanceId: string, bindings: Readonly<Record<string, CanvasBindingTarget>>): void {\n const instance = this.#instances.get(instanceId);\n if (instance === undefined) return;\n instance.bindings = bindings;\n if (!this.#directDevice) return;\n this.#fire(\n 'widget/deliver-failed',\n widgetSetBindingsMethod,\n [instanceId, bindings],\n instanceId,\n );\n }\n\n #requireInstance(instanceId: string): InstanceRecord | undefined {\n const instance = this.#instances.get(instanceId);\n if (!instance) {\n this.#report('widget/instance-not-found', `Widget instance \"${instanceId}\" is not mounted.`, {\n instanceId,\n });\n }\n return instance;\n }\n\n /** True while `record` is still the live record for this id in an undisposed host. */\n #owns(instanceId: string, record: InstanceRecord): boolean {\n return !this.#disposed && this.#instances.get(instanceId) === record;\n }\n\n /** Aborts a mount attempt whose instance was removed or replaced while it awaited. */\n #requireOwnership(instanceId: string, record: InstanceRecord): void {\n if (!this.#owns(instanceId, record)) {\n throw new WidgetMountCancelledError(instanceId);\n }\n }\n\n /** Drops this attempt's reservation and layer; a newer record for the same id is left alone. */\n #forget(instanceId: string, record: InstanceRecord): void {\n const current = this.#instances.get(instanceId);\n if (current !== record) {\n // The id was already dropped or replaced. Release only this attempt's audio generation, so a\n // session opened after a reset sweep cannot outlive the instance it belonged to.\n if (record.audioSession !== undefined) {\n this.#audio?.closeSession(instanceId, record.audioSession);\n }\n return;\n }\n this.#instances.delete(instanceId);\n this.#store.remove(instanceId);\n // The worklet closes the streams of this generation even when the guest never hears about it.\n this.#audio?.close(instanceId);\n }\n\n /**\n * Asks the guest to release its sessions.\n *\n * The guest keeps its evaluated modules: a reset rebuilds instances, so module-level state is out\n * of scope by contract and the factories stay warm. A host without a sandbox has nothing to\n * reset: no instance ever mounted, so the following sync pass simply mounts into a fresh runtime.\n * Failures are reported, never thrown: the remount below resumes from whatever state the guest is\n * in.\n */\n async #resetGuestRuntime(): Promise<void> {\n if (!this.#sandbox && !this.#starting) return;\n try {\n const sandbox = await this.#ensureSandbox();\n if (this.#disposed) return;\n await sandbox.call(widgetResetRuntimeMethod);\n } catch (error) {\n if (this.#disposed || error instanceof WidgetRuntimeError) return;\n if (this.#isTerminated()) {\n this.#failRuntime('The widget sandbox terminated during reset.');\n return;\n }\n this.#report(\n 'widget/runtime-failed',\n `The widget runtime could not be reset: ${describeError(error)}`,\n );\n }\n }\n\n #ensureSandbox(): Promise<WidgetSandbox> {\n if (this.#disposed) {\n return Promise.reject(new WidgetRuntimeError('Widget host is disposed'));\n }\n\n const existing = this.#sandbox;\n if (existing) {\n if (existing.state === 'terminated') {\n return Promise.reject(this.#failRuntime('The widget sandbox terminated unexpectedly.'));\n }\n return Promise.resolve(existing);\n }\n\n if (!this.#starting) {\n // The device port travels with the guest's first ordinary message, so it is spent once the guest exists.\n const devicePort = this.#devicePort;\n this.#devicePort = undefined;\n const pending = this.#createSandbox({\n ...(this.#container === undefined ? {} : { container: this.#container }),\n ...(this.#fs === undefined ? {} : { fs: this.#fs }),\n ...(devicePort === undefined ? {} : { devicePort }),\n })\n .catch((error: unknown) => {\n throw this.#failRuntime(\n `The widget sandbox failed to start: ${describeError(error)}`,\n error,\n );\n })\n .then(async (sandbox: WidgetSandbox) => {\n if (this.#disposed) {\n await terminate(sandbox);\n throw new WidgetRuntimeError('Widget host is disposed');\n }\n this.#sandbox = sandbox;\n this.#directDevice = sandbox.directDevice === true;\n this.#attach(sandbox);\n return sandbox;\n });\n\n this.#starting = pending;\n const settle = (): void => {\n if (this.#starting === pending) this.#starting = undefined;\n };\n pending.then(settle, settle);\n }\n\n return this.#starting;\n }\n\n /**\n * Reads every asset reference found in the merged props.\n *\n * RFC 0018 step 4: widget property resources resolve against the canvas document URI, so a host\n * without a `WidgetAssetProvider` reads them through `fs` (a `data:` reference is decoded\n * locally). Failures are reported and skipped: a missing image must not stop the mount.\n */\n async #prefetchAssets(\n instanceId: string,\n ref: string,\n props: Readonly<Record<string, unknown>>,\n ): Promise<Record<string, Uint8Array> | undefined> {\n const source = this.#assets;\n const fs = this.#fs;\n const baseUri = this.#documentUri;\n let read: (assetRef: WidgetAssetRef) => Promise<Uint8Array>;\n if (source !== undefined) {\n read = (assetRef) => source.resolve(assetRef);\n } else if (fs !== undefined && baseUri !== undefined) {\n read = (assetRef) => readHostAsset(fs, baseUri, assetRef);\n } else {\n return undefined;\n }\n\n const refs = collectAssetRefs(props);\n const entries = await Promise.all(\n [...refs.values()].map(async (assetRef): Promise<[string, Uint8Array] | undefined> => {\n try {\n const bytes = await read(assetRef);\n if (!(bytes instanceof Uint8Array)) {\n throw new TypeError('WidgetAssetProvider.resolve() must resolve to a Uint8Array');\n }\n return [assetRef.src, bytes];\n } catch (error) {\n this.#report(\n 'widget/asset-failed',\n `Widget asset \"${assetRef.src}\" for \"${ref}\" could not be read: ${describeError(error)}`,\n { instanceId, widget: ref },\n );\n return undefined;\n }\n }),\n );\n\n return Object.fromEntries(\n entries.filter((entry): entry is [string, Uint8Array] => entry !== undefined),\n );\n }\n\n #attach(sandbox: WidgetSandbox): void {\n this.#detachers.push(\n sandbox.on(widgetFrameEvent, (payload) => this.#onFrame(payload)),\n sandbox.on(widgetPublishEvent, (payload) => this.#onPublishMessage(payload)),\n sandbox.on(widgetErrorEvent, (payload) => this.#onErrorMessage(payload)),\n sandbox.on(widgetAssetFailedEvent, (payload) => this.#onAssetFailedMessage(payload)),\n );\n // A worklet that booted before the sandbox existed handed its port over already.\n this.#flushAudioPort();\n this.#flushAudioState();\n }\n\n #emitAudioPort(port: MessagePort): void {\n this.#pendingAudioPort = port;\n this.#flushAudioPort();\n }\n\n /** Drops a port nobody received; the host owns it until it is transferred. */\n #releaseAudioPort(): void {\n const port = this.#pendingAudioPort;\n this.#pendingAudioPort = undefined;\n try {\n port?.close();\n } catch {\n // Already closed.\n }\n }\n\n /** Transfers the direct worker ↔ worklet port; skipped until a sandbox can receive it. */\n #flushAudioPort(): void {\n const port = this.#pendingAudioPort;\n const sandbox = this.#sandbox;\n if (port === undefined || sandbox === undefined) return;\n this.#pendingAudioPort = undefined;\n if (sandbox.audio === undefined) {\n // No host → guest audio lane: nobody can receive the port, so the host releases it.\n try {\n port.close();\n } catch {\n // Already closed.\n }\n return;\n }\n try {\n sandbox.audio.attachPort(port);\n } catch {\n // A terminated sandbox has no guest left to inform.\n }\n }\n\n #emitAudioState(state: WidgetAudioState): void {\n if (this.#lastAudioState === state) return;\n this.#lastAudioState = state;\n this.#flushAudioState();\n }\n\n /** Pushes the latest availability; a mounted instance already received it in its mount request. */\n #flushAudioState(): void {\n const state = this.#lastAudioState;\n const sandbox = this.#sandbox;\n if (state === undefined || sandbox === undefined) return;\n try {\n sandbox.audio?.setState(state);\n } catch {\n // A terminated sandbox has no guest left to inform.\n }\n }\n\n #detach(): void {\n for (const detach of this.#detachers.splice(0)) {\n try {\n detach();\n } catch {\n // The sandbox may already be gone.\n }\n }\n }\n\n #onFrame(payload: unknown): void {\n const frame = payload as Partial<WidgetFrameMessage> | null | undefined;\n if (!frame || typeof frame !== 'object' || typeof frame.instanceId !== 'string') return;\n if (!isBitmap(frame.bitmap)) return;\n this.#store.setBitmap(frame.instanceId, frame.bitmap);\n }\n\n #onPublishMessage(payload: unknown): void {\n const message = payload as Partial<WidgetPublishMessage> | null | undefined;\n if (!message || typeof message !== 'object') return;\n if (typeof message.instanceId !== 'string' || typeof message.port !== 'string') return;\n const publish: WidgetPublish = {\n instanceId: message.instanceId,\n port: message.port,\n payload: message.payload,\n // The device host is the one authority for time: the last value it reported is the best\n // stamp a widget publish can carry when the widget did not pass one.\n simTime:\n typeof message.simTime === 'number' && Number.isFinite(message.simTime)\n ? message.simTime\n : this.#simTime,\n };\n // Route before notifying: a device may answer synchronously, and the host listener should see\n // the publish once its effects are already in flight. A guest with the direct device channel has\n // already delivered it, so forwarding here would deliver the same payload twice.\n if (message.direct !== true) this.#forwardToDeviceHost(publish);\n this.#onPublish?.(publish);\n }\n\n /** Sends a widget publish to the endpoint its port is bound to; unbound ports stay host-local. */\n #forwardToDeviceHost(publish: WidgetPublish): void {\n const widget = this.#document.widgets.find((candidate) => candidate.id === publish.instanceId);\n const target = widget?.bindings?.[publish.port];\n if (target === undefined) return;\n\n void this.#deviceHost\n .deliver(target, publish.payload, publish.simTime)\n .catch((error: unknown) => {\n this.#report(\n 'widget/deliver-failed',\n `Publish from \"${publish.instanceId}\" could not reach ${target.symbol}.${target.port}: ${describeError(error)}`,\n { instanceId: publish.instanceId, widget: widget?.widget },\n );\n });\n }\n\n /** Fans a device publish out to every widget port bound to its endpoint. */\n #onSimulationPublish(publish: SimulationPublish): void {\n if (this.#disposed) return;\n const { target } = publish;\n this.#lastPublished.set(targetKey(target), publish);\n // The direct channel already handed this publish to the guest, which fans it out to the same\n // instances; the host only keeps the level cache that seeds mounts.\n if (this.#directDevice) return;\n for (const widget of this.#document.widgets) {\n const bindings = widget.bindings;\n if (bindings === undefined) continue;\n for (const port of Object.keys(bindings)) {\n const bound = bindings[port];\n if (bound === undefined || bound.symbol !== target.symbol || bound.port !== target.port) {\n continue;\n }\n // `deliver` reports unknown instances and guest failures on its own.\n this.deliver(widget.id, port, publish.payload, publish.simTime);\n }\n }\n }\n\n /**\n * Seeds one freshly mounted instance with the values its endpoints already carry.\n *\n * `deliver` only forwards what the simulation publishes, and a level topic publishes on change\n * only, so without this a widget mounted mid-run would wait for the next change to show anything.\n */\n #replayPublished(widget: CanvasWidgetInstance): void {\n for (const [port, target] of Object.entries(widget.bindings ?? {})) {\n const publish = this.#lastPublished.get(targetKey(target));\n if (publish === undefined) continue;\n this.deliver(widget.id, port, publish.payload, publish.simTime);\n }\n }\n\n #onAssetFailedMessage(payload: unknown): void {\n const message = payload as Partial<WidgetAssetFailedMessage> | null | undefined;\n if (!message || typeof message !== 'object') return;\n if (typeof message.instanceId !== 'string') return;\n\n const src = typeof message.src === 'string' ? message.src : 'unknown';\n const name = message.error?.name ?? 'Error';\n const text = message.error?.message ?? 'Unknown asset failure';\n this.#report(\n 'widget/asset-failed',\n `Widget \"${message.instanceId}\" could not read asset \"${src}\": ${name}: ${text}`,\n {\n instanceId: message.instanceId,\n widget: this.#instances.get(message.instanceId)?.widget,\n },\n );\n }\n\n #onErrorMessage(payload: unknown): void {\n const message = payload as Partial<WidgetErrorMessage> | null | undefined;\n if (!message || typeof message !== 'object') return;\n if (typeof message.instanceId !== 'string') return;\n\n // Mount failures travel back through the rejected `mount()` promise instead, so that one\n // failure produces exactly one diagnostic.\n if (message.phase !== 'render' && message.phase !== 'deliver') return;\n\n const code: WidgetDiagnosticCode =\n message.phase === 'render' ? 'widget/render-failed' : 'widget/deliver-failed';\n const name = message.error?.name ?? 'Error';\n const text = message.error?.message ?? 'Unknown widget failure';\n this.#report(\n code,\n `Widget \"${message.instanceId}\" failed during ${message.phase}: ${name}: ${text}`,\n {\n instanceId: message.instanceId,\n widget: this.#instances.get(message.instanceId)?.widget,\n },\n );\n }\n\n #fire(\n code: WidgetDiagnosticCode | undefined,\n method: string,\n args: readonly unknown[],\n instanceId: string,\n ): void {\n if (this.#disposed) return;\n if (!this.#sandbox && !this.#starting) return;\n\n void this.#ensureSandbox()\n .then((sandbox) => sandbox.call(method, ...args))\n .catch((error: unknown) => {\n if (this.#disposed || error instanceof WidgetRuntimeError) return;\n if (this.#isTerminated()) {\n this.#failRuntime('The widget sandbox terminated unexpectedly.');\n return;\n }\n if (code === undefined) return;\n this.#report(\n code,\n `Widget call \"${method}\" failed for \"${instanceId}\": ${describeError(error)}`,\n { instanceId, widget: this.#instances.get(instanceId)?.widget },\n );\n });\n }\n\n #isTerminated(): boolean {\n return this.#sandbox?.state === 'terminated';\n }\n\n /**\n * Starts the frame clock. RFC 0018 gives the host the clock, so a loaded document advances on its\n * own; a pause or a disposed host keeps it stopped.\n */\n #startClock(): void {\n if (this.#disposed || this.#paused || this.#mode !== 'simulation') return;\n this.#scheduleFrame();\n }\n\n #stopClock(): void {\n const cancel = this.#cancelFrame;\n this.#cancelFrame = undefined;\n cancel?.();\n }\n\n #scheduleFrame(): void {\n if (this.#cancelFrame !== undefined || this.#disposed) return;\n this.#cancelFrame = this.#frameOptions.requestFrame(() => {\n this.#cancelFrame = undefined;\n void this.#advanceFrame();\n });\n }\n\n /** Advances one fixed simulation step, then schedules the next 25 ms clock tick. */\n async #advanceFrame(): Promise<void> {\n if (this.#advancing || this.#disposed || this.#paused) return;\n this.#advancing = true;\n try {\n if (this.#disposed || this.#paused) return;\n // Inputs that arrived since the last step are dispatched at the step's start.\n this.#flushInputs();\n if (this.#mode === 'simulation') {\n const report = await this.#deviceHost.tick(this.#frameOptions.stepMs * PS_PER_MS);\n this.#simTime = report.simTime;\n }\n } catch (error) {\n this.#report('widget/runtime-failed', `A simulation step failed: ${describeError(error)}`);\n } finally {\n this.#advancing = false;\n if (!this.#disposed && !this.#paused && this.#mode === 'simulation') this.#scheduleFrame();\n }\n }\n\n /** Dispatches the queued input events at the start of a step. */\n #flushInputs(): void {\n for (const input of this.#pendingInputs.splice(0)) {\n if (!this.#instances.has(input.instanceId)) continue;\n this.#fire(\n 'widget/deliver-failed',\n widgetPointerMethod,\n [input.instanceId, input.event],\n input.instanceId,\n );\n }\n }\n\n /** Abandons the runtime: layers are cleared and the failure is reported once. */\n #failRuntime(message: string, cause?: unknown): WidgetRuntimeError {\n this.#sandbox = undefined;\n this.#starting = undefined;\n // The dead guest had the only device port; the next sandbox runs without one and the host\n // relays topic traffic again.\n this.#directDevice = false;\n this.#detach();\n this.#store.clear();\n this.#instances.clear();\n this.#pendingInputs.length = 0;\n // The dead sandbox took the guest port with it; the next one gets a fresh channel.\n this.#releaseAudioPort();\n this.#audio?.reset();\n if (!this.#disposed) this.#report('widget/runtime-failed', message);\n return new WidgetRuntimeError(message, cause === undefined ? undefined : { cause });\n }\n\n async #shutdown(): Promise<void> {\n this.#disposed = true;\n this.#stopClock();\n this.#detach();\n this.#unsubscribeDevicePublish?.dispose();\n this.#unsubscribeDevicePublish = undefined;\n this.#pendingInputs.length = 0;\n this.#store.clear();\n this.#instances.clear();\n this.#lastPublished.clear();\n this.#directDevice = false;\n // A port handed over but never transferred belongs to this host; release it with the rest.\n const devicePort = this.#devicePort;\n this.#devicePort = undefined;\n try {\n devicePort?.close();\n } catch {\n // Already closed with a guest.\n }\n this.#releaseAudioPort();\n this.#audio?.dispose();\n\n const pending = this.#starting;\n const sandbox = this.#sandbox;\n this.#starting = undefined;\n this.#sandbox = undefined;\n\n if (sandbox) {\n await terminate(sandbox);\n return;\n }\n if (pending) {\n const late = await pending.catch(() => undefined);\n if (late) await terminate(late);\n }\n }\n\n /** Diagnostic ids for one instance; audio failures without an instance report no ids. */\n #instanceIds(instanceId: string): { instanceId?: string; widget?: string } {\n if (instanceId === '') return {};\n const widget = this.#instances.get(instanceId)?.widget;\n return widget === undefined ? { instanceId } : { instanceId, widget };\n }\n\n #reportBindingDiagnostic(\n widget: CanvasWidgetInstance,\n code: string,\n message: string,\n pointer: string | undefined,\n ): void {\n this.#report('widget/binding-failed', message, {\n instanceId: widget.id,\n widget: widget.widget,\n bindingCode: code,\n pointer,\n });\n }\n\n #report(\n code: WidgetDiagnosticCode,\n message: string,\n ids: {\n instanceId?: string | undefined;\n widget?: string | undefined;\n bindingCode?: string | undefined;\n pointer?: string | undefined;\n } = {},\n ): void {\n const diagnostic: WidgetDiagnostic = {\n code,\n message,\n ...(ids.instanceId === undefined ? {} : { instanceId: ids.instanceId }),\n ...(ids.widget === undefined ? {} : { widget: ids.widget }),\n ...(ids.bindingCode === undefined ? {} : { bindingCode: ids.bindingCode }),\n ...(ids.pointer === undefined ? {} : { pointer: ids.pointer }),\n };\n try {\n this.#onDiagnostic?.(diagnostic);\n } catch (error) {\n console.error('[@mica-js/widget] diagnostic handler threw', error);\n }\n }\n\n #emitDocument(document: CanvasDocument): void {\n for (const listener of [...this.#documentListeners]) {\n try {\n listener(document);\n } catch (error) {\n console.error('[@mica-js/widget] document listener threw', error);\n }\n }\n }\n}\n\nfunction placementOf(widget: CanvasWidgetInstance): WidgetPlacement {\n return {\n x: widget.x,\n y: widget.y,\n width: widget.width,\n height: widget.height,\n rotation: widget.rotation,\n };\n}\n\nfunction splitRef(ref: string): { packageId: string; widgetId: string } | undefined {\n const separator = ref.indexOf(':');\n if (separator <= 0 || separator === ref.length - 1) return undefined;\n return { packageId: ref.slice(0, separator), widgetId: ref.slice(separator + 1) };\n}\n\n/** Map key of one binding endpoint; the separator cannot occur in a symbol id or a port name. */\nfunction targetKey(target: { readonly symbol: string; readonly port: string }): string {\n return `${target.symbol}\\u0000${target.port}`;\n}\n\n/** Compares two binding maps by endpoint; the document reparses objects it never changed. */\nfunction sameBindings(\n left: Readonly<Record<string, CanvasBindingTarget>>,\n right: Readonly<Record<string, CanvasBindingTarget>>,\n): boolean {\n if (left === right) return true;\n const ports = Object.keys(left);\n if (ports.length !== Object.keys(right).length) return false;\n return ports.every((port) => {\n const bound = right[port];\n return bound !== undefined && targetKey(left[port]!) === targetKey(bound);\n });\n}\n\nfunction currentDevicePixelRatio(): number {\n const ratio = (globalThis as { devicePixelRatio?: unknown }).devicePixelRatio;\n return typeof ratio === 'number' && Number.isFinite(ratio) && ratio > 0 ? ratio : 1;\n}\n\nfunction isBitmap(value: unknown): value is ImageBitmap {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as ImageBitmap).close === 'function'\n );\n}\n\nfunction describeError(error: unknown): string {\n if (error instanceof Error && error.message) return error.message;\n return typeof error === 'string' ? error : String(error);\n}\n\n/**\n * Reads one widget property resource (RFC 0018 step 4).\n *\n * `inline` references carry base64 and a `data:` reference carries its own bytes, so neither\n * reaches `fs`; every other reference resolves against the canvas document URI first.\n */\nfunction readHostAsset(fs: HostFs, baseUri: string, ref: WidgetAssetRef): Promise<Uint8Array> {\n if (ref.src.slice(0, 5).toLowerCase() === 'data:') {\n return Promise.resolve(decodeDataUri(ref.src));\n }\n if (ref.mode === 'inline') return Promise.resolve(decodeBase64Asset(ref.src));\n return fs.read(resolveHostUri(baseUri, ref.src));\n}\n\nfunction decodeBase64Asset(text: string): Uint8Array {\n let binary: string;\n try {\n binary = atob(text);\n } catch (cause) {\n throw new TypeError('Inline asset src is not valid base64', { cause });\n }\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n}\n\nasync function terminate(sandbox: WidgetSandbox): Promise<void> {\n try {\n await sandbox.terminate('widget host disposed');\n } catch {\n // Already terminated.\n }\n}\n\n/** Asks the guest to drop an instance the host has already given up on. */\nasync function releaseGuestInstance(sandbox: WidgetSandbox, instanceId: string): Promise<void> {\n try {\n await sandbox.call(widgetUnmountMethod, instanceId);\n } catch {\n // The guest never created the instance, or the sandbox is already gone.\n }\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport { loggerService } from '@mica-js/core/logging';\nimport { isHostFsError, toHostFsErrorPayload } from '../host-fs/errors';\nimport { widgetAudioGuestService } from '../guest/audio/protocol';\nimport {\n widgetGuestControlService,\n widgetGuestService,\n widgetHostCapabilitiesService,\n widgetHostControlService,\n} from '../guest/widget/protocol';\nimport type { SandboxWorker } from '@mica-js/sandbox';\nimport type { WidgetSandbox, WidgetSandboxHostOptions } from './types';\n\n/** Adapts a provider-created widget worker to WidgetHost's RPC-facing surface. */\nexport async function createWidgetSandboxFromWorker(\n worker: SandboxWorker,\n options: WidgetSandboxHostOptions,\n): Promise<WidgetSandbox> {\n const devicePort = options.devicePort;\n let port: MessagePort;\n let rpc: ReturnType<typeof createRpc> | undefined;\n let logRegistration: { dispose(): void } | undefined;\n try {\n await worker.ready;\n const channel = new MessageChannel();\n port = channel.port1;\n const endpoint = createRpc(port);\n rpc = endpoint;\n logRegistration = endpoint.register(loggerService, {\n write(record) {\n const method = console[record.level] ?? console.log;\n method.call(console, `[${record.scope}]`, record.message, ...record.data);\n },\n });\n const transfer = devicePort === undefined ? [channel.port2] : [channel.port2, devicePort];\n worker.postMessage(null, transfer);\n } catch (error) {\n logRegistration?.dispose();\n rpc?.dispose();\n await worker.terminate('widget sandbox failed to start').catch(() => undefined);\n throw error;\n }\n const endpoint = rpc;\n if (endpoint === undefined) {\n throw new Error('Widget RPC endpoint was not created.');\n }\n const listeners = new Map<string, Set<(payload: unknown) => void>>();\n const dispatch = (type: string, payload: unknown) => {\n for (const listener of [...(listeners.get(type) ?? [])]) listener(payload);\n };\n endpoint.register(\n widgetHostCapabilitiesService,\n {\n async read(uri: string) {\n if (!options.fs) throw new Error(`No HostFs configured for ${uri}`);\n try {\n return await options.fs.read(uri);\n } catch (error) {\n if (isHostFsError(error)) {\n const payload = toHostFsErrorPayload(error);\n throw Object.assign(new Error(JSON.stringify(payload)), { name: 'HostFsError' });\n }\n throw error;\n }\n },\n },\n {\n transfer: (member, value) =>\n member === 'read' && value instanceof Uint8Array ? [value.buffer] : [],\n },\n );\n endpoint.register(widgetHostControlService, { event: dispatch });\n const guest = endpoint.getProxy(widgetGuestService) as unknown as Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n >;\n const audio = endpoint.getProxy(widgetAudioGuestService, {\n transfer: (member, args) => (member === 'attachPort' ? [args[0] as MessagePort] : []),\n });\n return {\n get state() {\n return worker.state;\n },\n directDevice: devicePort !== undefined,\n call: (method, ...args) => guest[method]!(...args),\n on: (type, listener) => {\n let set = listeners.get(type);\n if (!set) listeners.set(type, (set = new Set()));\n set.add(listener);\n return () => set?.delete(listener);\n },\n emit: (type, payload, transfer) => {\n void endpoint\n .getProxy(widgetGuestControlService, { transfer: () => transfer ?? [] })\n .dispatchEvent(type, payload)\n .catch(() => undefined);\n },\n audio: {\n attachPort: (port) => {\n void audio.attachPort(port).catch(() => undefined);\n },\n setState: (state) => {\n void audio.setState(state).catch(() => undefined);\n },\n },\n terminate: async (reason) => {\n logRegistration?.dispose();\n endpoint.dispose();\n await worker.terminate(reason);\n },\n } satisfies WidgetSandbox;\n}\n","import { SandboxWorker } from '@mica-js/sandbox';\nimport type { SandboxWorkerOptions } from '@mica-js/sandbox';\nimport guestScript from '../guest/widget/entry.ts?sandbox-worker-code';\n\n/**\n * The widget guest worker script, bundled and minified into this module by\n * `@mica-js/sandbox/vite` while the package itself is built.\n *\n * It is a classic script: every dependency is inlined, so the sandbox can run it without a module\n * loader and the package publishes no separate `*.sandbox.js` file.\n */\nexport const widgetGuestScript: string = guestScript;\n\n/**\n * Creates the widget host guest worker.\n *\n * This is the guest `WidgetHost` talks to, and it is the same one `@mica-js/canvas-editor`'s\n * `SandboxHostProvider` starts by default. Hosts only start it; the RPC surface is wired by\n * `createWidgetSandboxFromWorker`.\n */\nexport function createWidgetHostGuestSandbox(options: SandboxWorkerOptions = {}): SandboxWorker {\n return new SandboxWorker(widgetGuestScript, { name: 'widget', ...options });\n}\n"],"mappings":";;;;;;;AAmBA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CACA;CACA;CAEA,YAAY,MAA2B,SAAiB,UAAkC,CAAC,GAAG;EAC5F,MAAM,SAAS,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;EACjF,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,YAAY,QAAQ;EACzB,KAAK,OAAO,QAAQ;CACtB;AACF;;;ACRA,IAAM,eAAe;AACrB,IAAM,iBAAiB;AACvB,IAAM,2BAA2B;;AAEjC,IAAM,aAAa;;;;;;;AAqBnB,eAAsB,kBAAkB,OAA6C;CACnF,MAAM,WAAW,MAAM,aAAa,KAAK;CACzC,MAAM,UAAwC,CAAC;CAC/C,MAAM,UAAyC,CAAC;CAEhD,KAAK,MAAM,SAAS,SAAS,SAAS;EACpC,MAAM,aAAa,MAAM,eAAe,OAAO,SAAS,IAAI,KAAK;EACjE,MAAM,qBAAqB,qBAAqB,MAAM,IAAI;EAC1D,MAAM,OAAO,MAAM,mBAAmB,OAAO,SAAS,IAAI,MAAM,IAAI,kBAAkB;EACtF,QAAQ,MAAM,MAAM;GAAE;GAAY;EAAK;EACvC,QAAQ,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC;CAC/B;CAGA,MAAM,cAAc,MAAM,UAAU,KAAK,UAAU,OAAO,GAAG,SAAS,EAAE;CACxE,OAAO;EAAE,IAAI,SAAS;EAAI,SAAS,SAAS;EAAS;EAAa;CAAQ;AAC5E;AAEA,eAAe,aAAa,OAA+C;CACzE,IAAI;CACJ,IAAI;EACF,QAAQ,MAAM,MAAM,KAAK,YAAY;CACvC,SAAS,OAAO;EACd,MAAM,IAAI,gBACR,4BACA,WAAW,KAAK,U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AC,YAAY,KAAA,CAAS;GAClD;EACF;EACA,WAAW,OAAO,WAAW;GAC3B,iBAAiB,QAAQ;GACzB,SAAS,QAAQ;GACjB,MAAM,OAAO,UAAU,MAAM;EAC/B;CACF;AACF;;;;;;;;;;ACpGA,IAAa,oBAA4BC;;;;;;;;AASzC,SAAgB,6BAA6B,UAAgC,CAAC,GAAkB;CAC9F,OAAO,IAAI,cAAc,mBAAmB;EAAE,MAAM;EAAU,GAAG;CAAQ,CAAC;AAC5E"}
1
+ {"version":3,"file":"index.js","names":["workletScript","closePort","guestScript"],"sources":["../src/errors.ts","../src/package/load.ts","../src/package/static-provider.ts","../src/package/package-provider.ts","../src/host-fs/errors.ts","../src/host-fs/data-uri.ts","../src/host-fs/uri.ts","../src/guest/widget/props.ts","../src/guest/widget/protocol.ts","../src/guest/audio/protocol.ts","../src/host/audio/worklet.ts","../src/host/audio/engine.ts","../src/host/audio/noop.ts","../src/runtime/errors.ts","../src/runtime/runtime.ts","../src/host/sandbox.ts","../src/host/guest.ts"],"sourcesContent":["export type WidgetLoadErrorCode =\n | 'widget/package-not-found'\n | 'widget/invalid-manifest'\n | 'widget/invalid-definition'\n | 'widget/no-implementation'\n | 'widget/not-self-contained'\n | 'widget/load-failed'\n /** A descriptor field carries a value outside its closed set (RFC 0017 `delivery`). */\n | 'schema/invalid-value';\n\nexport interface WidgetLoadErrorOptions {\n /** Package id, when the package was already identified. */\n readonly packageId?: string;\n /** Package-relative path the failure refers to. */\n readonly path?: string;\n readonly cause?: unknown;\n}\n\n/** Thrown when a widget reference resolves to a package that cannot be turned into a module. */\nexport class WidgetLoadError extends Error {\n readonly code: WidgetLoadErrorCode;\n readonly packageId: string | undefined;\n readonly path: string | undefined;\n\n constructor(code: WidgetLoadErrorCode, message: string, options: WidgetLoadErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'WidgetLoadError';\n this.code = code;\n this.packageId = options.packageId;\n this.path = options.path;\n }\n}\n","import { parseDeliveryKind, parsePayloadType } from '@mica-js/document/canvas';\nimport { WidgetLoadError, type WidgetLoadErrorCode } from '../errors';\nimport type { PortDefinition, PropertyDefinition, WidgetDefinition, WidgetModule } from '../types';\n\n/** Read-only view of the files that make up one package. */\nexport interface PackageFiles {\n /** Human-readable label used in diagnostics. */\n readonly label: string;\n /** Reads a package-relative POSIX path and resolves to its bytes. */\n read(path: string): Promise<Uint8Array>;\n}\n\nexport interface WidgetPackage {\n readonly id: string;\n readonly version: string;\n /**\n * SHA-256 (hex) over the `[widget id, source]` pairs in widget-id order, so distinct package\n * contents never collide and reordering the manifest does not change the hash.\n */\n readonly contentHash: string;\n readonly modules: Readonly<Record<string, WidgetModule>>;\n}\n\nconst PACKAGE_JSON = 'package.json';\nconst JSON_EXTENSION = '.json';\nconst IMPLEMENTATION_EXTENSION = '.js';\n/** Package and widget ids are stable kebab-case identifiers (see #1). */\nconst ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/;\n\ninterface WidgetEntry {\n readonly id: string;\n readonly path: string;\n readonly displayName: string | undefined;\n readonly description: string | undefined;\n}\n\ninterface PackageManifest {\n readonly id: string;\n readonly version: string;\n readonly widgets: readonly WidgetEntry[];\n}\n\n/**\n * Reads a package manifest, every declared widget definition and its paired implementation.\n * Only the three declared path kinds are read; the package is never enumerated.\n *\n * @throws {WidgetLoadError}\n */\nexport async function loadWidgetPackage(files: PackageFiles): Promise<WidgetPackage> {\n const manifest = await readManifest(files);\n const modules: Record<string, WidgetModule> = {};\n const sources: (readonly [string, string])[] = [];\n\n for (const entry of manifest.widgets) {\n const definition = await readDefinition(files, manifest.id, entry);\n const implementationPath = toImplementationPath(entry.path);\n const code = await readImplementation(files, manifest.id, entry.id, implementationPath);\n modules[entry.id] = { definition, code };\n sources.push([entry.id, code]);\n }\n\n // Ids travel with each source, so the digest separates adjacent widgets and empty files.\n const contentHash = await sha256Hex(JSON.stringify(sources), manifest.id);\n return { id: manifest.id, version: manifest.version, contentHash, modules };\n}\n\nasync function readManifest(files: PackageFiles): Promise<PackageManifest> {\n let bytes: Uint8Array;\n try {\n bytes = await files.read(PACKAGE_JSON);\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/package-not-found',\n `Package ${JSON.stringify(files.label)} has no readable ${PACKAGE_JSON}.`,\n { path: PACKAGE_JSON, cause },\n );\n }\n\n const manifest = requireObject(\n parseJson(bytes, 'widget/invalid-manifest', PACKAGE_JSON, undefined, PACKAGE_JSON),\n 'widget/invalid-manifest',\n `${PACKAGE_JSON} must be a JSON object`,\n undefined,\n PACKAGE_JSON,\n );\n\n const id = manifest['name'];\n if (typeof id !== 'string' || !ID_PATTERN.test(id)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `${PACKAGE_JSON} must declare a kebab-case \"name\".`,\n { path: PACKAGE_JSON },\n );\n }\n\n const version = manifest['version'];\n if (typeof version !== 'string' || version.length === 0) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(id)} must declare a non-empty \"version\".`,\n { packageId: id, path: PACKAGE_JSON },\n );\n }\n\n const widgetsValue = manifest['widgets'];\n const widgets =\n widgetsValue === undefined\n ? {}\n : requireObject(\n widgetsValue,\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(id)} \"widgets\" must be an object`,\n id,\n PACKAGE_JSON,\n );\n\n const entries = Object.keys(widgets)\n .sort()\n .map((widgetId) => readEntry(widgets[widgetId], widgetId, id));\n\n return { id, version, widgets: entries };\n}\n\nfunction readEntry(value: unknown, widgetId: string, packageId: string): WidgetEntry {\n if (!ID_PATTERN.test(widgetId)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package ${JSON.stringify(packageId)} declares widget id ${JSON.stringify(widgetId)}; ids must be kebab-case.`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n\n const entry = requireObject(\n value,\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} entry must be an object`,\n packageId,\n PACKAGE_JSON,\n );\n\n const path = entry['path'];\n if (typeof path !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} must declare a string \"path\".`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n const problem = packagePathProblem(path);\n if (problem !== undefined) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} path ${JSON.stringify(path)} ${problem}.`,\n { packageId, path },\n );\n }\n if (!path.endsWith(JSON_EXTENSION)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} path ${JSON.stringify(path)} must point at a ${JSON_EXTENSION} description.`,\n { packageId, path },\n );\n }\n\n return {\n id: widgetId,\n path,\n displayName: optionalString(entry, 'displayName', widgetId, packageId),\n description: optionalString(entry, 'description', widgetId, packageId),\n };\n}\n\nasync function readDefinition(\n files: PackageFiles,\n packageId: string,\n entry: WidgetEntry,\n): Promise<WidgetDefinition> {\n let bytes: Uint8Array;\n try {\n bytes = await files.read(entry.path);\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(entry.id)} declares a missing definition at ${JSON.stringify(entry.path)}.`,\n { packageId, path: entry.path, cause },\n );\n }\n\n const record = requireObject(\n parseJson(bytes, 'widget/invalid-definition', entry.path, packageId, entry.path),\n 'widget/invalid-definition',\n `Widget definition ${JSON.stringify(entry.path)} must be a JSON object`,\n packageId,\n entry.path,\n );\n\n const properties = readProperties(record['properties'], packageId, entry.path);\n const ports = readPorts(record['ports'], packageId, entry.path);\n\n return {\n properties,\n ports,\n ...(entry.displayName === undefined ? {} : { displayName: entry.displayName }),\n ...(entry.description === undefined ? {} : { description: entry.description }),\n };\n}\n\nfunction readProperties(\n value: unknown,\n packageId: string,\n path: string,\n): Readonly<Record<string, PropertyDefinition>> {\n if (value === undefined) {\n return createRecord();\n }\n const record = requireObject(\n value,\n 'widget/invalid-definition',\n `\"properties\" in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const properties: Record<string, PropertyDefinition> = createRecord();\n for (const [key, raw] of Object.entries(record)) {\n if (isUnsafeRecordKey(key)) {\n continue;\n }\n const descriptor = requireObject(\n raw,\n 'widget/invalid-definition',\n `Property ${JSON.stringify(key)} in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n const type = descriptor['type'];\n if (typeof type !== 'string' || type.length === 0) {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Property ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare a non-empty string \"type\".`,\n { packageId, path },\n );\n }\n properties[key] = { ...descriptor, type };\n }\n return properties;\n}\n\nfunction readPorts(\n value: unknown,\n packageId: string,\n path: string,\n): Readonly<Record<string, PortDefinition>> {\n if (value === undefined) {\n return createRecord();\n }\n const record = requireObject(\n value,\n 'widget/invalid-definition',\n `\"ports\" in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const ports: Record<string, PortDefinition> = createRecord();\n for (const [key, raw] of Object.entries(record)) {\n if (isUnsafeRecordKey(key)) {\n continue;\n }\n const descriptor = requireObject(\n raw,\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must be an object`,\n packageId,\n path,\n );\n\n const direction = descriptor['direction'];\n if (direction !== 'input' && direction !== 'output') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare \"direction\" as \"input\" or \"output\".`,\n { packageId, path },\n );\n }\n\n const typeName = descriptor['type'];\n if (typeof typeName !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare a string \"type\".`,\n { packageId, path },\n );\n }\n const type = parsePayloadType(typeName);\n if (type === undefined) {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} declares unknown payload type ${JSON.stringify(typeName)}.`,\n { packageId, path },\n );\n }\n\n const title = portText(descriptor, 'title', key, packageId, path);\n const description = portText(descriptor, 'description', key, packageId, path);\n // RFC 0017: `delivery` is optional and independent of `type`; an unparsable value is rejected\n // here instead of silently falling back to the payload type default.\n const declaredDelivery = descriptor['delivery'];\n const delivery =\n declaredDelivery === undefined ? undefined : parseDeliveryKind(declaredDelivery);\n if (declaredDelivery !== undefined && delivery === undefined) {\n throw new WidgetLoadError(\n 'schema/invalid-value',\n `Port ${JSON.stringify(key)} in ${JSON.stringify(path)} must declare \"delivery\" as \"level\" or \"message\".`,\n { packageId, path },\n );\n }\n ports[key] = {\n direction,\n type,\n ...(delivery === undefined ? {} : { delivery }),\n ...(title === undefined ? {} : { title }),\n ...(description === undefined ? {} : { description }),\n };\n }\n return ports;\n}\n\nasync function readImplementation(\n files: PackageFiles,\n packageId: string,\n widgetId: string,\n path: string,\n): Promise<string> {\n try {\n return decode(await files.read(path));\n } catch (cause) {\n throw new WidgetLoadError(\n 'widget/no-implementation',\n `Widget ${JSON.stringify(widgetId)} in package ${JSON.stringify(packageId)} has no implementation at ${JSON.stringify(path)}.`,\n { packageId, path, cause },\n );\n }\n}\n\n/** Rejects absolute paths, drive letters, backslashes and escaping `..` segments. */\nfunction packagePathProblem(path: string): string | undefined {\n if (path.length === 0) {\n return 'must not be empty';\n }\n if (path.startsWith('/')) {\n return 'must be relative to the package root';\n }\n if (/^[A-Za-z]:/.test(path)) {\n return 'must not carry a drive letter';\n }\n if (path.includes('\\\\')) {\n return 'must use POSIX separators';\n }\n if (path.split('/').includes('..')) {\n return 'must stay inside the package';\n }\n return undefined;\n}\n\nfunction toImplementationPath(definitionPath: string): string {\n return definitionPath.slice(0, -JSON_EXTENSION.length) + IMPLEMENTATION_EXTENSION;\n}\n\n/** Reads an optional manifest field; failures always point at `package.json`, where the field lives. */\nfunction optionalString(\n record: Record<string, unknown>,\n key: 'displayName' | 'description',\n widgetId: string,\n packageId: string,\n): string | undefined {\n const value = record[key];\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Widget ${JSON.stringify(widgetId)} \"${key}\" in ${PACKAGE_JSON} must be a string.`,\n { packageId, path: PACKAGE_JSON },\n );\n }\n return value;\n}\n\nfunction portText(\n record: Record<string, unknown>,\n key: 'title' | 'description',\n portId: string,\n packageId: string,\n path: string,\n): string | undefined {\n const value = record[key];\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== 'string') {\n throw new WidgetLoadError(\n 'widget/invalid-definition',\n `Port ${JSON.stringify(portId)} \"${key}\" in ${JSON.stringify(path)} must be a string.`,\n { packageId, path },\n );\n }\n return value;\n}\n\nfunction parseJson(\n bytes: Uint8Array,\n code: WidgetLoadErrorCode,\n what: string,\n packageId: string | undefined,\n path: string,\n): unknown {\n try {\n return JSON.parse(decode(bytes)) as unknown;\n } catch (cause) {\n throw new WidgetLoadError(code, `${what} is not valid JSON.`, {\n path,\n cause,\n ...(packageId === undefined ? {} : { packageId }),\n });\n }\n}\n\nfunction requireObject(\n value: unknown,\n code: WidgetLoadErrorCode,\n message: string,\n packageId: string | undefined,\n path: string,\n): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new WidgetLoadError(code, `${message}.`, {\n path,\n ...(packageId === undefined ? {} : { packageId }),\n });\n }\n return value as Record<string, unknown>;\n}\n\nfunction decode(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Record for keys taken from untrusted definition JSON: no inherited setter can intercept an\n * assignment, so a declared entry can never become an object prototype.\n */\nfunction createRecord<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\n/** `__proto__` is never a stable widget key, and on any object it would shadow the prototype. */\nfunction isUnsafeRecordKey(key: string): boolean {\n return key === '__proto__';\n}\n\nasync function sha256Hex(text: string, packageId: string): Promise<string> {\n const subtle = globalThis.crypto?.subtle;\n if (subtle === undefined) {\n throw new WidgetLoadError(\n 'widget/load-failed',\n 'Computing the widget package content hash requires Web Crypto (globalThis.crypto.subtle).',\n { packageId, path: PACKAGE_JSON },\n );\n }\n const digest = await subtle.digest('SHA-256', new TextEncoder().encode(text));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n","import type { WidgetModule, WidgetProvider } from '../types';\n\n/** Provider over a fixed module table, used for builtin widgets and tests. */\nexport function createStaticWidgetProvider(\n modules: Readonly<Record<string, WidgetModule>>,\n): WidgetProvider {\n const index = new Map(Object.entries(modules));\n return {\n resolve(ref) {\n return Promise.resolve(index.get(ref));\n },\n };\n}\n","import { WidgetLoadError } from '../errors';\nimport { loadWidgetPackage, type PackageFiles } from './load';\nimport type { WidgetModule, WidgetProvider } from '../types';\n\nexport interface PackageWidgetProviderOptions {\n readonly files: PackageFiles | readonly PackageFiles[];\n}\n\n/**\n * Loads every package up front and indexes its widgets under `<packageId>:<widgetId>`.\n * Resolution never touches the file system again, and unknown references return `undefined`.\n *\n * @throws {WidgetLoadError}\n */\nexport async function createPackageWidgetProvider(\n options: PackageWidgetProviderOptions,\n): Promise<WidgetProvider> {\n const filesList: readonly PackageFiles[] = Array.isArray(options.files)\n ? options.files\n : [options.files as PackageFiles];\n\n const index = new Map<string, WidgetModule>();\n const packageIds = new Set<string>();\n\n for (const files of filesList) {\n const widgetPackage = await loadWidgetPackage(withPathCache(files));\n if (packageIds.has(widgetPackage.id)) {\n throw new WidgetLoadError(\n 'widget/invalid-manifest',\n `Package id ${JSON.stringify(widgetPackage.id)} is provided more than once.`,\n { packageId: widgetPackage.id, path: 'package.json' },\n );\n }\n packageIds.add(widgetPackage.id);\n for (const [widgetId, module] of Object.entries(widgetPackage.modules)) {\n index.set(`${widgetPackage.id}:${widgetId}`, module);\n }\n }\n\n return {\n resolve(ref) {\n return Promise.resolve(index.get(ref));\n },\n };\n}\n\n/** Reads each path at most once for the lifetime of the provider. */\nfunction withPathCache(files: PackageFiles): PackageFiles {\n const cache = new Map<string, Promise<Uint8Array>>();\n return {\n label: files.label,\n read(path) {\n const cached = cache.get(path);\n if (cached !== undefined) {\n return cached;\n }\n const pending = files.read(path);\n cache.set(path, pending);\n return pending;\n },\n };\n}\n","/** Failure classification of a `HostFs.read` rejection. */\nexport type HostFsErrorCode = 'FileNotFound' | 'NoPermissions' | 'NoFileSystem' | 'Unavailable';\n\n/**\n * Structured-clone payload for a `HostFsError` that crosses a thread boundary.\n *\n * The receiving side rebuilds the instance from `code`; `message` keeps the original wording when\n * it survives the transport and falls back to the default message for the code otherwise.\n */\nexport interface HostFsErrorPayload {\n readonly code: HostFsErrorCode;\n readonly uri: string;\n readonly message?: string;\n}\n\nexport interface HostFsErrorOptions {\n readonly cause?: unknown;\n}\n\nconst DEFAULT_MESSAGES: Record<HostFsErrorCode, string> = {\n FileNotFound: 'Host resource not found',\n NoPermissions: 'Host resource access denied',\n NoFileSystem: 'No host file system handles the URI scheme',\n Unavailable: 'Host file system is unavailable',\n};\n\nconst ERROR_CODES: readonly HostFsErrorCode[] = [\n 'FileNotFound',\n 'NoPermissions',\n 'NoFileSystem',\n 'Unavailable',\n];\n\nfunction isHostFsErrorCode(value: unknown): value is HostFsErrorCode {\n return typeof value === 'string' && (ERROR_CODES as readonly string[]).includes(value);\n}\n\n/** Rejection of `HostFs.read`: `code` classifies the failure, `uri` names the resource. */\nexport class HostFsError extends Error {\n readonly code: HostFsErrorCode;\n readonly uri: string;\n\n constructor(\n code: HostFsErrorCode,\n uri: string,\n message?: string,\n options: HostFsErrorOptions = {},\n ) {\n super(\n message ?? `${DEFAULT_MESSAGES[code]}: ${uri}`,\n options.cause === undefined ? undefined : { cause: options.cause },\n );\n this.name = 'HostFsError';\n this.code = code;\n this.uri = uri;\n }\n}\n\n/** Narrows an unknown rejection to a `HostFsError` created in this realm. */\nexport function isHostFsError(value: unknown): value is HostFsError {\n return value instanceof HostFsError;\n}\n\n/** Copies the fields a thread hop must carry; the instance itself does not survive a structured clone. */\nexport function toHostFsErrorPayload(error: HostFsError): HostFsErrorPayload {\n return { code: error.code, uri: error.uri, message: error.message };\n}\n\n/** Rebuilds a `HostFsError` from its payload, rejecting codes outside the contract. */\nexport function fromHostFsErrorPayload(payload: HostFsErrorPayload): HostFsError {\n const code: unknown = payload.code;\n if (!isHostFsErrorCode(code)) {\n throw new TypeError(`Unknown HostFsError code: ${String(code)}`);\n }\n return new HostFsError(code, payload.uri, payload.message);\n}\n","/**\n * Decodes a self-contained `data:` URI to its bytes.\n *\n * `data:` resources never reach `HostFs`: the bytes travel with the reference, so the host decodes\n * them locally. `;base64` payloads are decoded from base64; other payloads are percent-decoded,\n * while characters that need no escaping are encoded as UTF-8. The URI fragment is ignored.\n *\n * @throws TypeError when the URI has no payload separator or the payload is not decodable.\n */\nexport function decodeDataUri(uri: string): Uint8Array {\n const { base64, payload } = splitDataUri(uri);\n return base64 ? decodeBase64(payload) : decodePercentPayload(payload);\n}\n\n/**\n * Decodes a self-contained `data:` URI to its text payload.\n *\n * The decoded bytes are read as UTF-8, so a payload that carries binary or malformed UTF-8 is a\n * decode failure rather than replacement characters.\n *\n * @throws TypeError when the URI has no payload separator, the payload is not decodable, or the\n * bytes are not UTF-8.\n */\nexport function decodeDataUriText(uri: string): string {\n const bytes = decodeDataUri(uri);\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch (cause) {\n throw new TypeError('Data URI payload is not valid UTF-8', { cause });\n }\n}\n\ninterface DataUriPayload {\n readonly base64: boolean;\n readonly payload: string;\n}\n\n/** Splits the URI into its `;base64` flag and payload. */\nfunction splitDataUri(uri: string): DataUriPayload {\n if (uri.slice(0, 5).toLowerCase() !== 'data:') {\n throw new TypeError('Not a data: URI');\n }\n const hash = uri.indexOf('#');\n const body = hash < 0 ? uri : uri.slice(0, hash);\n const comma = body.indexOf(',');\n if (comma < 0) {\n throw new TypeError('Data URI must separate its payload with a comma');\n }\n\n const metadata = body.slice('data:'.length, comma);\n return { base64: /;base64$/i.test(metadata), payload: body.slice(comma + 1) };\n}\n\nfunction decodeBase64(payload: string): Uint8Array {\n let binary: string;\n try {\n binary = atob(payload);\n } catch (cause) {\n throw new TypeError('Data URI payload is not valid base64', { cause });\n }\n\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\nfunction isHexDigit(value: string | undefined): value is string {\n return value !== undefined && /^[0-9A-Fa-f]$/.test(value);\n}\n\n/**\n * Percent-decodes a payload to bytes, so `%89PNG` keeps its binary value instead of being read as\n * (invalid) UTF-8. Literal characters are UTF-8 encoded.\n */\nfunction decodePercentPayload(payload: string): Uint8Array {\n const encoder = new TextEncoder();\n const chunks: Uint8Array[] = [];\n let literal = 0;\n let index = 0;\n\n while (index < payload.length) {\n if (payload[index] !== '%') {\n index += 1;\n continue;\n }\n const high = payload[index + 1];\n const low = payload[index + 2];\n if (!isHexDigit(high) || !isHexDigit(low)) {\n throw new TypeError('Data URI payload is not valid percent-encoding');\n }\n if (index > literal) chunks.push(encoder.encode(payload.slice(literal, index)));\n chunks.push(new Uint8Array([Number.parseInt(`${high}${low}`, 16)]));\n index += 3;\n literal = index;\n }\n\n if (literal < payload.length) chunks.push(encoder.encode(payload.slice(literal)));\n\n let total = 0;\n for (const chunk of chunks) total += chunk.length;\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n","interface UriParts {\n readonly scheme: string | undefined;\n readonly authority: string | undefined;\n readonly path: string;\n readonly query: string | undefined;\n readonly fragment: string | undefined;\n}\n\ninterface PathReference {\n readonly path: string;\n readonly query: string | undefined;\n readonly fragment: string | undefined;\n}\n\nconst ABSOLUTE_URI = /^[A-Za-z][A-Za-z0-9+.-]*:/;\n\n/** Whether `uri` carries a scheme, i.e. is absolute rather than a relative reference. */\nexport function isAbsoluteHostUri(uri: string): boolean {\n return ABSOLUTE_URI.test(uri);\n}\n\n/** Splits a reference into path, query and fragment without interpreting leading slashes. */\nfunction splitPath(value: string): PathReference {\n const hash = value.indexOf('#');\n const fragment = hash < 0 ? undefined : value.slice(hash + 1);\n const beforeFragment = hash < 0 ? value : value.slice(0, hash);\n const question = beforeFragment.indexOf('?');\n const query = question < 0 ? undefined : beforeFragment.slice(question + 1);\n const path = question < 0 ? beforeFragment : beforeFragment.slice(0, question);\n return { path, query, fragment };\n}\n\nfunction parseUri(value: string): UriParts {\n const schemeMatch = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(value);\n const scheme = schemeMatch?.[1];\n let rest = schemeMatch === null ? value : value.slice(schemeMatch[0].length);\n\n let authority: string | undefined;\n if (rest.startsWith('//')) {\n const tail = rest.slice(2);\n const end = tail.search(/[/?#]/);\n authority = end < 0 ? tail : tail.slice(0, end);\n rest = end < 0 ? '' : tail.slice(end);\n }\n\n const { path, query, fragment } = splitPath(rest);\n return { scheme, authority, path, query, fragment };\n}\n\nfunction removeLastSegment(output: string): string {\n const slash = output.lastIndexOf('/');\n return slash < 0 ? '' : output.slice(0, slash);\n}\n\n/** RFC 3986 §5.2.4: drops `.` and `..` segments without touching empty segments. */\nfunction removeDotSegments(path: string): string {\n let input = path;\n let output = '';\n while (input.length > 0) {\n if (input.startsWith('../')) {\n input = input.slice(3);\n } else if (input.startsWith('./')) {\n input = input.slice(2);\n } else if (input.startsWith('/./')) {\n input = `/${input.slice(3)}`;\n } else if (input === '/.') {\n input = '/';\n } else if (input.startsWith('/../')) {\n input = `/${input.slice(4)}`;\n output = removeLastSegment(output);\n } else if (input === '/..') {\n input = '/';\n output = removeLastSegment(output);\n } else if (input === '.' || input === '..') {\n input = '';\n } else {\n const segment = /^\\/?[^/]*/.exec(input)?.[0] ?? input;\n output += segment;\n input = input.slice(segment.length);\n }\n }\n return output;\n}\n\n/** RFC 3986 §5.3: merges a relative path with the base path. */\nfunction mergePath(base: UriParts, referencePath: string): string {\n if (referencePath === '') return base.path;\n if (base.authority !== undefined && base.path === '') return `/${referencePath}`;\n const slash = base.path.lastIndexOf('/');\n return slash < 0 ? referencePath : `${base.path.slice(0, slash + 1)}${referencePath}`;\n}\n\nfunction compose(\n scheme: string,\n authority: string | undefined,\n path: string,\n query: string | undefined,\n fragment: string | undefined,\n): string {\n let uri = `${scheme}:`;\n if (authority !== undefined) uri += `//${authority}`;\n uri += path;\n if (query !== undefined) uri += `?${query}`;\n if (fragment !== undefined) uri += `#${fragment}`;\n return uri;\n}\n\n/**\n * Resolves a document reference against the absolute URI of the document that contains it.\n *\n * - a reference with a scheme is an absolute URI and is returned unchanged;\n * - a reference starting with `/` replaces the path and keeps the base scheme and authority;\n * - any other reference is merged with the base directory and normalized.\n *\n * The result always keeps the scheme and authority of `baseUri`, so a `//host/path` reference\n * stays inside the base authority instead of replacing it. Hosts pass a base URI whose path is\n * not empty; a base with an authority and an empty path resolves relative references under that\n * authority.\n *\n * @throws TypeError when `baseUri` is not an absolute URI.\n */\nexport function resolveHostUri(baseUri: string, reference: string): string {\n const base = parseUri(baseUri);\n if (base.scheme === undefined) {\n throw new TypeError(`Host URI base must be absolute: ${baseUri}`);\n }\n if (isAbsoluteHostUri(reference)) return reference;\n\n const target = splitPath(reference);\n const replacesPath = reference.startsWith('/');\n const path = replacesPath\n ? removeDotSegments(target.path)\n : removeDotSegments(mergePath(base, target.path));\n const keepBaseQuery = !replacesPath && target.path === '' && target.query === undefined;\n const query = keepBaseQuery ? base.query : target.query;\n return compose(base.scheme, base.authority, path, query, target.fragment);\n}\n","import type { PropertyDefinition } from '../../types';\nimport type { WidgetAssetRef } from './types';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\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/**\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: unknown): unknown {\n if (Array.isArray(value)) {\n return Object.freeze(value.map((item) => cloneFrozen(item)));\n }\n if (isPlainObject(value)) {\n const entries: [string, unknown][] = [];\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\nfunction isAssetMode(value: unknown): value is WidgetAssetRef['mode'] {\n return value === 'file' || value === 'inline' || value === 'store';\n}\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 */\nexport function mergeProperties(\n properties: Readonly<Record<string, PropertyDefinition>> | undefined,\n props: Readonly<Record<string, unknown>> | undefined,\n): Readonly<Record<string, unknown>> {\n const merged = new Map<string, unknown>();\n\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 ?? {})) {\n merged.set(key, props?.[key]);\n }\n\n return Object.freeze(Object.fromEntries(merged));\n}\n\n/**\n * Collects image / binary property values (`{ src, mode }`) from nested objects and arrays.\n * Results are keyed by `src`, so one resource referenced twice is only read once.\n */\nexport function collectAssetRefs(\n value: unknown,\n found: Map<string, WidgetAssetRef> = new Map(),\n seen: Set<object> = new Set(),\n): Map<string, WidgetAssetRef> {\n if (typeof value !== 'object' || value === null) return found;\n if (seen.has(value)) return found;\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) collectAssetRefs(item, found, seen);\n return found;\n }\n if (!isPlainObject(value)) return found;\n\n const candidate = value as { src?: unknown; mode?: unknown };\n if (typeof candidate.src === 'string' && isAssetMode(candidate.mode)) {\n if (!found.has(candidate.src)) {\n found.set(candidate.src, { src: candidate.src, mode: candidate.mode });\n }\n }\n for (const key of Object.keys(value)) collectAssetRefs(value[key], found, seen);\n return found;\n}\n","import { defineRpcService } from '@mica-js/core/rpc';\nimport type { TimePs } from '@mica-js/core';\nimport type { CanvasBindingTarget } from '@mica-js/document/canvas';\nimport type { WidgetDefinition } from '../../types';\nimport type { WidgetAudioMountInfo } from '../audio/protocol';\nimport type { WidgetInputEvent } from './types';\n\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 */\nexport const widgetFrameEvent = 'widget:frame';\nexport const widgetPublishEvent = 'widget:publish';\nexport const widgetErrorEvent = 'widget:error';\n/** A resource the guest could not hand to a widget; non-fatal, the instance keeps running. */\nexport const widgetAssetFailedEvent = 'widget:asset-failed';\n\n/** Guest methods the host reaches through `sandbox.call()`. */\nexport const widgetLoadMethod = 'load';\nexport const widgetMountMethod = 'mount';\nexport const widgetUnmountMethod = 'unmount';\nexport const widgetResizeMethod = 'resize';\nexport const widgetSetPropertiesMethod = 'set-properties';\n/** Replaces the prefetched bytes of one mounted instance without remounting it. */\nexport const widgetSetAssetsMethod = 'set-assets';\n/**\n * Replaces the device endpoints one instance writes to and reads from (RFC 0018).\n *\n * The guest routes topic traffic itself when it holds a direct device channel, so it needs the same\n * binding map the host validates against. A guest without that channel ignores the call.\n */\nexport const widgetSetBindingsMethod = 'set-bindings';\nexport const widgetDeliverMethod = 'deliver';\nexport const widgetPointerMethod = 'pointer';\n/**\n * Configures explicit stepping and connects the direct simulation-runtime port before mounting.\n * Without explicit stepping the standalone guest retains automatic repaint scheduling.\n */\nexport const widgetConfigureMethod = 'configure';\n/**\n * Advances the guest to a caller-supplied time.\n *\n * The editor owns the clock: it delivers the same step to widgets and devices, so the guest must\n * not schedule time-bound work on its own.\n */\nexport const widgetStepMethod = 'step';\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 */\nexport const widgetResetRuntimeMethod = 'reset-runtime';\n/** Instance boundary that produced a widget error. */\nexport type WidgetErrorPhase = 'mount' | 'render' | 'deliver';\n\n/** Widget errors cross the sandbox boundary as plain data. */\nexport interface SerializedWidgetError {\n readonly name: string;\n readonly message: string;\n}\n\n/** One rendered frame, always transferred so the host owns the bitmap. */\nexport interface WidgetFrameMessage {\n readonly instanceId: string;\n readonly bitmap: ImageBitmap;\n readonly width: number;\n readonly height: number;\n readonly dpr: number;\n /**\n * Mount generation echoed from {@link WidgetMountRequest.generation}. The editor runtime\n * rejects a frame whose generation no longer owns the instance; standalone guests may omit it.\n */\n readonly generation?: number;\n}\n\n/** Payload a widget published on an output port. */\nexport interface WidgetPublishMessage {\n readonly instanceId: string;\n readonly port: string;\n readonly payload: unknown;\n /** Simulation time supplied by the widget; `0` when it did not pass one. */\n readonly simTime: number;\n /**\n * The guest already handed this publish to the device guest over its direct channel, so the host\n * must not forward it a second time. Absent when the guest has no channel or no binding.\n */\n readonly direct?: boolean;\n}\n\n/** Asset read that failed inside the guest; reported once per instance and `src`. */\nexport interface WidgetAssetFailedMessage {\n readonly instanceId: string;\n readonly src: string;\n readonly error: SerializedWidgetError;\n}\n\n/** Failure contained to one instance; the guest keeps every other instance running. */\nexport interface WidgetErrorMessage {\n readonly instanceId: string;\n readonly phase: WidgetErrorPhase;\n readonly error: SerializedWidgetError;\n}\n\nexport interface WidgetLoadModule {\n readonly definition: WidgetDefinition;\n readonly code: string;\n}\n\nexport interface WidgetLoadPackage {\n readonly id: string;\n readonly modules: Readonly<Record<string, WidgetLoadModule>>;\n}\n\nexport interface WidgetLoadRequest {\n readonly packages: readonly WidgetLoadPackage[];\n}\n\nexport interface WidgetMountRequest {\n readonly instanceId: string;\n readonly widget: string;\n readonly width: number;\n readonly height: number;\n readonly dpr: number;\n readonly props?: Readonly<Record<string, unknown>>;\n /** Bytes the host prefetched for this instance, keyed by `WidgetAssetRef.src`. */\n readonly assets?: Readonly<Record<string, Uint8Array>>;\n /**\n * Audio availability at mount time. Read synchronously by the factory through\n * `api.audio.state`; `session` is the one-shot token the worklet accepts for this generation.\n */\n readonly audio?: WidgetAudioMountInfo;\n /**\n * Mount generation assigned by the editor runtime. Frames echo it, so a frame produced by a\n * replaced instance can never be adopted by its successor.\n */\n readonly generation?: number;\n}\n\n/** Service the guest reaches over the transferred direct port. */\nexport type WidgetDirectTopicService = 'simulation-runtime';\n\n/** One-time guest configuration applied before the first mount. */\nexport interface IWidgetGuestRuntimeConfig {\n /**\n * Removes the guest's automatic repaint scheduling: an `invalidate()` only marks the instance\n * dirty, and the next {@link IWidgetGuestStep} paints it.\n */\n readonly explicitStepping?: boolean;\n /** Contract behind the direct port; defaults to `simulation-runtime` at first use. */\n readonly directTopicService?: WidgetDirectTopicService;\n}\n\n/** Caller-supplied time of one widget step. */\nexport interface IWidgetGuestStep {\n /** Simulation time after the step, in picoseconds. */\n readonly simTime: TimePs;\n /** Length of the step, in picoseconds. */\n readonly dt: TimePs;\n /** Editor mode; widgets keep running in both, the caller decides what advances. */\n readonly mode: 'edit' | 'simulation';\n}\n\n/** Every guest method the host reaches through `sandbox.call()`, in one RPC service. */\nexport interface WidgetGuestService {\n [widgetLoadMethod](request: WidgetLoadRequest): Promise<void>;\n /** Rejects when the factory or the first paint fails, so a candidate instance is not adopted. */\n [widgetMountMethod](request: WidgetMountRequest): Promise<void>;\n [widgetUnmountMethod](instanceId: string): void;\n [widgetResizeMethod](instanceId: string, width: number, height: number, dpr: number): void;\n [widgetSetPropertiesMethod](instanceId: string, props: Readonly<Record<string, unknown>>): void;\n [widgetSetAssetsMethod](instanceId: string, assets: Readonly<Record<string, Uint8Array>>): void;\n [widgetSetBindingsMethod](\n instanceId: string,\n bindings: Readonly<Record<string, CanvasBindingTarget>>,\n ): void;\n [widgetDeliverMethod](instanceId: string, port: string, payload: unknown, simTime: number): void;\n [widgetPointerMethod](instanceId: string, event: WidgetInputEvent): void;\n [widgetConfigureMethod](config: IWidgetGuestRuntimeConfig): boolean;\n /**\n * Resolves after queued direct input and deferred repaints are applied, and after every direct\n * widget → simulation delivery started by this step has settled.\n */\n [widgetStepMethod](step: IWidgetGuestStep): Promise<void>;\n [widgetResetRuntimeMethod](): void;\n}\n\n/** Host → guest control lane: events pushed into the runtime and forced teardown. */\nexport interface WidgetGuestControlService {\n dispatchEvent(type: string, payload: unknown): void;\n terminate(): void;\n}\n\n/** Guest → host control lane: the event bus plus capability reads. */\nexport interface WidgetHostControlService {\n event(type: string, payload: unknown, transfer?: readonly Transferable[]): void;\n}\n\n/** Host file system reads the guest may perform; bytes travel as a transferred buffer. */\nexport interface WidgetHostCapabilitiesService {\n read(uri: string): Promise<Uint8Array>;\n}\n\n/**\n * Wire names shared by the worker script and the host adapter. Both sides must agree on the exact\n * strings, so they are defined once and registered with `register` / `getProxy`.\n */\nexport const widgetGuestService = defineRpcService<WidgetGuestService>('guest');\nexport const widgetGuestControlService =\n defineRpcService<WidgetGuestControlService>('guest-control');\nexport const widgetHostControlService = defineRpcService<WidgetHostControlService>('host-control');\nexport const widgetHostCapabilitiesService =\n defineRpcService<WidgetHostCapabilitiesService>('host-capabilities');\n\n/** The one member of {@link widgetHostControlService} that carries a transfer list. */\nexport const widgetHostEventMethod = 'event';\n\n/** One publish the editor simulation runtime sends over the direct port. */\nexport interface IWidgetSimulationPublish {\n readonly target: CanvasBindingTarget;\n readonly payload: unknown;\n /** Simulation time the publish belongs to, in picoseconds. */\n readonly simTime: TimePs;\n}\n\n/**\n * The slice of the editor simulation runtime the guest reaches over the direct port.\n *\n * The editor registers this service on the device worker (or an in-process simulation) under the\n * `simulation-runtime` id and transfers the other end of the port to this guest. The contract is\n * declared locally on purpose: the widget package must not depend on the simulator implementation\n * to state the wire shape. `deliver` takes the same `{ target, payload, simTime }` message that\n * `onDidPublish` reports.\n */\nexport interface IWidgetSimulationRuntimeChannel {\n /** Queues one message for a device endpoint; consumed by the simulation's next step. */\n deliver(message: IWidgetSimulationPublish): Promise<void>;\n /** Subscribes to simulation publishes; the guest fans them out to its bound instances. */\n onDidPublish(listener: (publish: IWidgetSimulationPublish) => void): () => void;\n}\n\n/** Wire name of {@link IWidgetSimulationRuntimeChannel}. */\nexport const widgetSimulationRuntimeService =\n defineRpcService<IWidgetSimulationRuntimeChannel>('simulation-runtime');\n","/**\n * Typed RPC contracts of the widget audio path (RFC 0016).\n *\n * Three endpoints carry the whole path:\n *\n * - the guest runtime talks to the `AudioWorklet` over a `MessagePort` it receives from the host;\n * - the host talks to the same worklet over the `AudioWorkletNode` port;\n * - the host pushes availability and the direct port into the guest over the sandbox RPC endpoint.\n *\n * `createRpc` serializes every call, so PCM stays on the worker ↔ worklet port and never passes\n * through the render host.\n */\n\nimport { defineRpcService } from '@mica-js/core/rpc';\n\n/** Name the worklet registers its processor under. */\nexport const widgetAudioWorkletProcessor = 'mica-widget-audio';\n\n/** Per-instance ceiling on simultaneous tones. */\nexport const defaultMaxVoices = 8;\n/** Per-instance ceiling on open PCM streams. */\nexport const defaultMaxStreams = 4;\n\n/** Availability of the host audio path. */\nexport type WidgetAudioState = 'unavailable' | 'suspended' | 'running';\n\n/** Why a tone or stream stopped. */\nexport type WidgetAudioEndReason =\n 'finished' | 'stopped' | 'dropped' | 'error' | 'unavailable' | 'disposed';\n\n/** Sample layout of a PCM stream. */\nexport type WidgetAudioFormat = 's16' | 'f32';\n\n/** Waveforms the worklet synthesizes for `api.audio.tone()`. */\nexport type WidgetOscillatorType = 'sine' | 'square' | 'triangle' | 'sawtooth';\n\n/** Playback state of a PCM stream, as the guest sees it. */\nexport type WidgetAudioStreamState = 'buffering' | 'playing' | 'ended' | 'closed';\n\n/** Per-instance ceilings; a host may tighten them through its options. */\nexport interface WidgetAudioLimits {\n readonly maxVoices: number;\n readonly maxStreams: number;\n}\n\n/** One mount generation of one instance, opened by the host before the guest can use it. */\nexport interface WidgetAudioSessionOpen {\n /** One-shot token every guest call must carry. */\n readonly session: string;\n /** Guest runtime that owns the token; a port from another runtime is rejected. */\n readonly runtimeId: string;\n readonly instanceId: string;\n readonly maxVoices: number;\n readonly maxStreams: number;\n}\n\nexport interface WidgetAudioToneInit {\n /** Guest-assigned id; unique per session. */\n readonly voiceId: string;\n readonly type: WidgetOscillatorType;\n /** Hz, `(0, 24000]`. */\n readonly frequency: number;\n /** `0`–`1`. */\n readonly volume: number;\n}\n\nexport interface WidgetAudioToneSettings {\n readonly volume?: number;\n readonly frequency?: number;\n /** Smoothing window in milliseconds, `0`–`10000`. */\n readonly rampMs: number;\n}\n\nexport interface WidgetAudioStop {\n /** Fade-out in milliseconds, `0`–`10000`. */\n readonly fadeMs: number;\n}\n\nexport interface WidgetAudioStreamInit {\n /** Guest-assigned id; unique per session. */\n readonly streamId: string;\n /** Source rate in Hz, `8000`–`96000`. */\n readonly sampleRate: number;\n readonly channels: 1 | 2;\n readonly format: WidgetAudioFormat;\n readonly capacityFrames: number;\n readonly startFrames: number;\n readonly volume: number;\n}\n\n/** Answer of `createStream`: the worklet re-checks the per-session quota. */\nexport interface WidgetAudioStreamOpened {\n readonly accepted: boolean;\n}\n\n/** Credit report; `consumedFrames` is cumulative over the stream's lifetime. */\nexport interface WidgetAudioProgress {\n readonly streamId: string;\n readonly consumedFrames: number;\n readonly underruns: number;\n readonly state: WidgetAudioStreamState;\n}\n\n/** Terminal event of one tone or stream. */\nexport interface WidgetAudioEndedMessage {\n readonly target: 'tone' | 'stream';\n readonly id: string;\n readonly reason: WidgetAudioEndReason;\n}\n\n/** Diagnostic codes the audio path reports. */\nexport type WidgetAudioDiagnosticCode = 'widget/audio-failed' | 'widget/audio-limit';\n\n/** Quota or validation class the receiving side dedupes against. */\nexport type WidgetAudioDiagnosticCategory = 'voices' | 'streams' | 'capacity' | 'worklet';\n\nexport interface WidgetAudioDiagnostic {\n /** Session the diagnostic belongs to; the host maps it back to the instance. */\n readonly session: string;\n readonly code: WidgetAudioDiagnosticCode;\n readonly category: WidgetAudioDiagnosticCategory;\n readonly message: string;\n}\n\n/**\n * Guest → worklet.\n *\n * Every member names a session; the worklet checks that the session belongs to the runtime that\n * owns the calling port, so a guest cannot steer another instance.\n */\nexport interface WidgetAudioWorkletService {\n createTone(session: string, init: WidgetAudioToneInit): void;\n setTone(session: string, voiceId: string, settings: WidgetAudioToneSettings): void;\n stopTone(session: string, voiceId: string, options: WidgetAudioStop): void;\n createStream(session: string, init: WidgetAudioStreamInit): WidgetAudioStreamOpened;\n /** `samples` travels as a transferred buffer; `true` means the whole block was accepted. */\n writeStream(session: string, streamId: string, samples: Int16Array | Float32Array): boolean;\n /** Drops everything that has not played yet and keeps the stream open. */\n clearStream(session: string, streamId: string): void;\n /** Drains the buffer, then ends the stream with `finished`. */\n endStream(session: string, streamId: string): void;\n /** Discards the buffer and closes the stream immediately. */\n closeStream(session: string, streamId: string): void;\n onDidProgress(listener: (progress: WidgetAudioProgress) => void): () => void;\n onDidEnded(listener: (ended: WidgetAudioEndedMessage) => void): () => void;\n}\n\nexport const widgetAudioWorkletService =\n defineRpcService<WidgetAudioWorkletService>('audio-worklet');\n\n/** Host → worklet, over the `AudioWorkletNode` port. */\nexport interface WidgetAudioControlService {\n openSession(init: WidgetAudioSessionOpen): void;\n closeSession(session: string): void;\n setSessionVolume(session: string, volume: number): void;\n setMuted(muted: boolean): void;\n suspend(): void;\n resume(): void;\n /** `port` is the guest end of the direct PCM channel; it is always transferred. */\n attachGuestPort(runtimeId: string, port: MessagePort): void;\n detachGuestPort(runtimeId: string): void;\n onDidDiagnostic(listener: (diagnostic: WidgetAudioDiagnostic) => void): () => void;\n}\n\nexport const widgetAudioControlService =\n defineRpcService<WidgetAudioControlService>('audio-control');\n\n/** Host → guest: audio availability and the direct PCM port handoff. */\nexport interface WidgetAudioGuestService {\n attachPort(port: MessagePort): void;\n setState(state: WidgetAudioState): void;\n}\n\nexport const widgetAudioGuestService = defineRpcService<WidgetAudioGuestService>('audio-guest');\n\n/** Attached to `mount` so the factory can read `api.audio.state` synchronously. */\nexport interface WidgetAudioMountInfo {\n readonly state: WidgetAudioState;\n /** One-shot token this mount generation uses on the direct port. */\n readonly session?: string;\n}\n","import workletScript from '../../guest/audio/entry.ts?audio-worklet-code';\nimport { widgetAudioWorkletProcessor } from '../../guest/audio/protocol';\n\nlet objectUrl: string | undefined;\n\n/**\n * Blob URL of the packaged `AudioWorkletProcessor` script.\n *\n * The script is bundled and minified into this module while the package is built, so an\n * `AudioContext` can load it through `addModule()` without the package publishing a separate\n * `*.worklet.js` asset. The URL is created once per page and reused by every host.\n */\nexport function widgetAudioWorkletUrl(): string {\n objectUrl ??= URL.createObjectURL(new Blob([workletScript], { type: 'text/javascript' }));\n return objectUrl;\n}\n\n/**\n * Loads the packaged processor into `context` and creates its node.\n *\n * Pass it as `WidgetAudioOptions.getAudioWorklet`; runtimes that provide no loader of their\n * own use the same processor internally.\n */\nexport async function createWidgetAudioWorklet(context: AudioContext): Promise<AudioWorkletNode> {\n if (typeof context.audioWorklet?.addModule !== 'function') {\n throw new Error('The AudioContext does not support AudioWorklet.addModule().');\n }\n await context.audioWorklet.addModule(widgetAudioWorkletUrl());\n return new AudioWorkletNode(context, widgetAudioWorkletProcessor);\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint, RpcProxy } from '@mica-js/core/rpc';\nimport {\n defaultMaxStreams,\n defaultMaxVoices,\n widgetAudioControlService,\n widgetAudioWorkletProcessor,\n} from '../../guest/audio/protocol';\nimport type {\n WidgetAudioControlService,\n WidgetAudioDiagnostic,\n WidgetAudioDiagnosticCode,\n WidgetAudioLimits,\n WidgetAudioMountInfo,\n WidgetAudioState,\n} from '../../guest/audio/protocol';\nimport { widgetAudioWorkletUrl } from './worklet';\n\n/** Structural stand-ins for the Web Audio nodes the engine touches; tests inject fakes. */\nexport interface AudioNodeLike {\n connect(destination: AudioNodeLike): unknown;\n disconnect?(): void;\n}\n\nexport interface AudioContextLike {\n readonly sampleRate: number;\n /** `suspended` | `running` | `closed` for a real context. */\n readonly state: string;\n readonly destination: AudioNodeLike;\n readonly audioWorklet?: { addModule(url: string): Promise<void> };\n /**\n * Fired by a real context whenever the browser suspends or resumes it on its own (autoplay\n * policy, hidden page, a caller calling `suspend()` / `resume()`). Used as a fallback when the\n * context lacks `addEventListener`; fakes may leave it `null`.\n */\n onstatechange?: ((event?: unknown) => void) | null;\n /** Preferred over `onstatechange`: subscribing must not clobber the caller's own handler. */\n addEventListener?(type: 'statechange', listener: () => void): void;\n removeEventListener?(type: 'statechange', listener: () => void): void;\n}\n\nexport interface AudioWorkletNodeLike extends AudioNodeLike {\n readonly port: MessagePort;\n}\n\nexport interface MessageChannelLike {\n readonly port1: MessagePort;\n readonly port2: MessagePort;\n}\n\n/** Host-side sinks the engine reports into; the widget host owns the sandbox plumbing. */\nexport interface WidgetAudioNotifier {\n /** Hands the direct guest ↔ worklet port to the sandbox. */\n emitPort(port: MessagePort): void;\n emitState(state: WidgetAudioState): void;\n}\n\nexport interface WidgetAudioEngineOptions {\n readonly context: AudioContextLike;\n readonly destination?: AudioNodeLike;\n readonly limits?: Partial<WidgetAudioLimits>;\n readonly report: (code: WidgetAudioDiagnosticCode, instanceId: string, message: string) => void;\n readonly notify: WidgetAudioNotifier;\n /** Loads the audio worklet node; tests or applications may provide their own loader. */\n readonly loadWorklet?: () => Promise<AudioWorkletNodeLike>;\n readonly createChannel?: () => MessageChannelLike;\n readonly createWorkletNode?: (context: AudioContextLike, name: string) => AudioWorkletNodeLike;\n}\n\ninterface InstanceAudio {\n readonly instanceId: string;\n readonly session: string;\n}\n\n/**\n * Host half of the audio path (RFC 0016).\n *\n * Owns the one `AudioWorkletNode`, the session tokens, and the two RPC endpoints that reach the\n * worklet: host controls over the node port, and the direct guest channel it hands to the sandbox.\n * No audio node other than that worklet is created here: tones, mixing and volume all live inside\n * the worklet.\n */\nexport class WidgetAudioEngine {\n readonly #context: AudioContextLike;\n readonly #destination: AudioNodeLike;\n readonly #report: WidgetAudioEngineOptions['report'];\n readonly #notify: WidgetAudioNotifier;\n readonly #limits: WidgetAudioLimits;\n readonly #loadWorklet: (() => Promise<AudioWorkletNodeLike>) | undefined;\n readonly #createChannel: () => MessageChannelLike;\n readonly #createWorkletNode: (context: AudioContextLike, name: string) => AudioWorkletNodeLike;\n readonly #runtimeId = `r${Math.random().toString(36).slice(2, 10)}`;\n readonly #instances = new Map<string, InstanceAudio>();\n #worklet: AudioWorkletNodeLike | undefined;\n #endpoint: RpcEndpoint | undefined;\n #control: RpcProxy<WidgetAudioControlService> | undefined;\n #booting: Promise<boolean> | undefined;\n #available: boolean | undefined;\n #muted = false;\n #suspended = false;\n #sessionCounter = 0;\n #disposed = false;\n #lastState: WidgetAudioState | undefined;\n #detachStateListener: (() => void) | undefined;\n /** Context state moved without an engine call; guests get the same ordered notification. */\n readonly #onContextStateChange = (): void => {\n if (this.#disposed) return;\n this.#syncState();\n };\n\n constructor(options: WidgetAudioEngineOptions) {\n this.#context = options.context;\n this.#destination = options.destination ?? options.context.destination;\n this.#report = options.report;\n this.#notify = options.notify;\n this.#limits = {\n maxVoices: Math.max(1, Math.floor(options.limits?.maxVoices ?? defaultMaxVoices)),\n maxStreams: Math.max(1, Math.floor(options.limits?.maxStreams ?? defaultMaxStreams)),\n };\n this.#loadWorklet = options.loadWorklet;\n this.#createChannel =\n options.createChannel ??\n (() => {\n const channel = new MessageChannel();\n return { port1: channel.port1, port2: channel.port2 };\n });\n this.#createWorkletNode =\n options.createWorkletNode ??\n ((context, name) => {\n const ctor = (\n globalThis as {\n AudioWorkletNode?: new (\n context: unknown,\n name: string,\n options: unknown,\n ) => AudioWorkletNodeLike;\n }\n ).AudioWorkletNode;\n if (!ctor) throw new Error('AudioWorkletNode is not available');\n return new ctor(context, name, {\n numberOfInputs: 0,\n numberOfOutputs: 1,\n outputChannelCount: [2],\n });\n });\n }\n\n /**\n * Current availability.\n *\n * `unavailable` means \"no audio at all\": the host configured none, the browser lacks\n * `AudioWorklet`, or the worklet module failed to load.\n */\n get state(): WidgetAudioState {\n if (this.#disposed || this.#available === false) return 'unavailable';\n if (this.#available !== true || this.#suspended) return 'suspended';\n return this.#context.state === 'running' ? 'running' : 'suspended';\n }\n\n /** Limits in force, so a caller can mirror them in its own UI. */\n get limits(): WidgetAudioLimits {\n return this.#limits;\n }\n\n /**\n * Opens the mount generation of one instance.\n *\n * Resolves once the worklet registered the session token, so the `mount` request that carries it\n * can never arrive after the first guest call of that generation.\n */\n async open(instanceId: string): Promise<WidgetAudioMountInfo> {\n if (this.#disposed) return { state: 'unavailable' };\n const available = await this.#boot();\n if (!available) return { state: 'unavailable' };\n\n this.close(instanceId);\n this.#sessionCounter += 1;\n const session = `${this.#runtimeId}-${this.#sessionCounter}`;\n this.#instances.set(instanceId, { instanceId, session });\n try {\n await this.#control?.openSession({\n session,\n runtimeId: this.#runtimeId,\n instanceId,\n maxVoices: this.#limits.maxVoices,\n maxStreams: this.#limits.maxStreams,\n });\n } catch (error) {\n this.#report(\n 'widget/audio-failed',\n instanceId,\n `The audio worklet rejected the session: ${describe(error)}`,\n );\n }\n this.#syncState();\n return { state: this.state, session };\n }\n\n setMuted(muted: boolean): void {\n this.#muted = muted === true;\n this.#call((control) => control.setMuted(this.#muted));\n }\n\n setInstanceVolume(instanceId: string, volume: number): void {\n if (typeof volume !== 'number') {\n throw new TypeError('WidgetAudioControls.setInstanceVolume expects a number');\n }\n if (!Number.isFinite(volume) || volume < 0 || volume > 1) {\n throw new RangeError('WidgetAudioControls.setInstanceVolume expects a value in [0, 1]');\n }\n const instance = this.#instances.get(instanceId);\n if (!instance) return;\n this.#call((control) => control.setSessionVolume(instance.session, volume));\n }\n\n /** Freezes audio without touching the caller's `AudioContext`. */\n suspend(): void {\n if (this.#disposed || this.#suspended) return;\n this.#suspended = true;\n this.#call((control) => control.suspend());\n this.#syncState();\n }\n\n resume(): void {\n if (this.#disposed) return;\n this.#suspended = false;\n this.#call((control) => control.resume());\n this.#syncState();\n }\n\n /**\n * Closes the instance only when it still belongs to `session`.\n *\n * A mount attempt that lost its id may have opened its own audio generation after the host's\n * cleanup sweep; closing by id alone would tear down the replacement instead.\n */\n closeSession(instanceId: string, session: string): void {\n const instance = this.#instances.get(instanceId);\n if (!instance || instance.session !== session) return;\n this.close(instanceId);\n }\n\n /** Drops one instance: its session token is revoked and the worklet ends its voices and streams. */\n close(instanceId: string): void {\n const instance = this.#instances.get(instanceId);\n if (!instance) return;\n this.#instances.delete(instanceId);\n this.#call((control) => control.closeSession(instance.session));\n }\n\n /**\n * Drops every instance and hands the worklet a fresh guest channel.\n *\n * Called when the sandbox goes away: the old guest port died with it, and the next sandbox needs\n * a port of its own.\n */\n reset(): void {\n for (const instanceId of [...this.#instances.keys()]) {\n this.close(instanceId);\n }\n if (this.#available === true && this.#control !== undefined) {\n void this.#restartRuntime();\n }\n }\n\n dispose(): void {\n if (this.#disposed) return;\n for (const instanceId of [...this.#instances.keys()]) {\n this.close(instanceId);\n }\n // Sent before the flag flips: the worklet drops the runtime, its sessions and its guest port.\n this.#call((control) => control.detachGuestPort(this.#runtimeId));\n this.#disposed = true;\n this.#detachStateListener?.();\n this.#detachStateListener = undefined;\n this.#endpoint?.dispose();\n this.#endpoint = undefined;\n this.#control = undefined;\n const worklet = this.#worklet;\n this.#worklet = undefined;\n if (worklet !== undefined) {\n closePort(worklet.port);\n try {\n worklet.disconnect?.();\n } catch {\n // Already detached.\n }\n }\n }\n\n /** Boots the worklet once; a failure is permanent for the lifetime of the engine. */\n #boot(): Promise<boolean> {\n this.#booting ??= this.#start().catch((error: unknown) => {\n this.#available = false;\n // A load that fails after `dispose()` is not a widget problem and has no live host to hear it.\n if (!this.#disposed) {\n this.#report('widget/audio-failed', '', `Widget audio is unavailable: ${describe(error)}`);\n }\n return false;\n });\n return this.#booting;\n }\n\n async #start(): Promise<boolean> {\n if (\n this.#loadWorklet === undefined &&\n typeof this.#context.audioWorklet?.addModule !== 'function'\n ) {\n this.#available = false;\n return false;\n }\n\n this.#listenForContextState();\n const worklet = await (this.#loadWorklet?.() ?? this.#loadDefaultWorklet());\n if (this.#disposed) {\n // `dispose()` ran while the module was loading: release the node instead of wiring it up.\n closePort(worklet.port);\n try {\n worklet.disconnect?.();\n } catch {\n // Already detached.\n }\n return false;\n }\n this.#worklet = worklet;\n const endpoint = createRpc(worklet.port);\n this.#endpoint = endpoint;\n const control = endpoint.getProxy(widgetAudioControlService, {\n transfer: (member, args) => (member === 'attachGuestPort' ? [args[1] as MessagePort] : []),\n });\n this.#control = control;\n control.onDidDiagnostic((diagnostic) => this.#onDiagnostic(diagnostic));\n worklet.connect(this.#destination);\n await this.#attachRuntime();\n this.#available = true;\n return true;\n }\n\n /**\n * Mirrors the context's own `statechange` onto mounted guests.\n *\n * The caller owns the `AudioContext`, so its state can move without the engine asking: autoplay\n * policy keeping it suspended, the browser suspending a hidden page, or the caller calling\n * `resume()`. Guests read `api.audio.state` and `onStateChange`, so those moves must be forwarded.\n */\n #listenForContextState(): void {\n if (this.#detachStateListener) return;\n const context = this.#context;\n if (typeof context.addEventListener === 'function') {\n context.addEventListener('statechange', this.#onContextStateChange);\n this.#detachStateListener = () =>\n context.removeEventListener?.('statechange', this.#onContextStateChange);\n return;\n }\n if (!('onstatechange' in context)) return;\n // Contexts that only expose the handler property keep the caller's value for `dispose()`.\n const previous = context.onstatechange;\n context.onstatechange = this.#onContextStateChange;\n this.#detachStateListener = () => {\n if (context.onstatechange === this.#onContextStateChange) context.onstatechange = previous;\n };\n }\n\n /** Worklet → host diagnostics, attributed back to the instance that owns the session. */\n #onDiagnostic(diagnostic: WidgetAudioDiagnostic): void {\n const owner = [...this.#instances.values()].find(\n (entry) => entry.session === diagnostic.session,\n );\n // A revoked token means the message is late; the RFC drops it instead of raising diagnostics.\n if (!owner) return;\n this.#report(diagnostic.code, owner.instanceId, diagnostic.message);\n }\n\n async #loadDefaultWorklet(): Promise<AudioWorkletNodeLike> {\n await this.#context.audioWorklet?.addModule(widgetAudioWorkletUrl());\n return this.#createWorkletNode(this.#context, widgetAudioWorkletProcessor);\n }\n\n async #restartRuntime(): Promise<void> {\n const control = this.#control;\n if (control === undefined) return;\n try {\n await control.detachGuestPort(this.#runtimeId);\n } catch {\n // The worklet already forgot the runtime; a new channel follows anyway.\n }\n await this.#attachRuntime();\n }\n\n /** Transfers a fresh port to the worklet and hands the other end to the guest. */\n async #attachRuntime(): Promise<void> {\n const control = this.#control;\n if (control === undefined || this.#disposed) return;\n const channel = this.#createChannel();\n try {\n await control.attachGuestPort(this.#runtimeId, channel.port1);\n } catch (error) {\n closePort(channel.port1);\n closePort(channel.port2);\n this.#report(\n 'widget/audio-failed',\n '',\n `The audio worklet rejected the guest port: ${describe(error)}`,\n );\n return;\n }\n this.#notify.emitPort(channel.port2);\n }\n\n /** Fires one host → worklet call; a missing or closed worklet is not a widget failure. */\n #call(run: (control: RpcProxy<WidgetAudioControlService>) => Promise<unknown>): void {\n const control = this.#control;\n if (control === undefined || this.#disposed) return;\n try {\n void run(control).catch(() => undefined);\n } catch {\n // The endpoint is already closed.\n }\n }\n\n #syncState(): void {\n const next = this.state;\n if (next === this.#lastState) return;\n this.#lastState = next;\n this.#notify.emitState(next);\n }\n}\n\nfunction closePort(port: MessagePort): void {\n try {\n port.close();\n } catch {\n // Already closed.\n }\n}\n\nfunction describe(error: unknown): string {\n if (error instanceof Error && error.message) return error.message;\n return typeof error === 'string' ? error : String(error);\n}\n","import type { WidgetAudioState } from '../../guest/audio/protocol';\nimport type { WidgetAudioControls } from './types';\n\n/**\n * Controls of a host that was created without `audio`.\n *\n * The state is `unavailable` and every setter is a no-op, so callers never have to branch on\n * whether audio is configured.\n */\nexport const NO_AUDIO_CONTROLS: WidgetAudioControls = {\n state: 'unavailable' as WidgetAudioState,\n setMuted(): void {},\n setInstanceVolume(): void {},\n suspend(): void {},\n resume(): void {},\n};\n","/** Rejections the widget runtime produces before or around the guest boundary. */\nexport type WidgetRuntimeErrorCode =\n | 'widget/disposed'\n | 'widget/instance-exists'\n | 'widget/unknown-instance'\n | 'widget/unknown-port'\n | 'widget/invalid-instance'\n | 'widget/invalid-update'\n | 'widget/invalid-payload'\n | 'widget/invalid-direction'\n | 'widget/invalid-time'\n | 'widget/invalid-step'\n | 'widget/sandbox-failed';\n\n/**\n * Typed rejection of one runtime call.\n *\n * Widget boundary failures (render, input, publish) become diagnostics instead; errors with this\n * type mean the caller asked for something the runtime cannot do.\n */\nexport class WidgetRuntimeError extends Error {\n readonly code: WidgetRuntimeErrorCode;\n\n constructor(code: WidgetRuntimeErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'WidgetRuntimeError';\n this.code = code;\n }\n}\n","import { timePs } from '@mica-js/core';\nimport type { TimePs } from '@mica-js/core';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { CanvasBindingTarget, PayloadType } from '@mica-js/document/canvas';\nimport type { WidgetAudioMountInfo } from '../guest/audio/protocol';\nimport { mergeProperties } from '../guest/widget/props';\nimport {\n widgetAssetFailedEvent,\n widgetConfigureMethod,\n widgetDeliverMethod,\n widgetErrorEvent,\n widgetFrameEvent,\n widgetLoadMethod,\n widgetMountMethod,\n widgetPointerMethod,\n widgetPublishEvent,\n widgetResizeMethod,\n widgetSetAssetsMethod,\n widgetSetBindingsMethod,\n widgetSetPropertiesMethod,\n widgetStepMethod,\n widgetUnmountMethod,\n} from '../guest/widget/protocol';\nimport type {\n WidgetAssetFailedMessage,\n WidgetErrorMessage,\n WidgetFrameMessage,\n WidgetPublishMessage,\n} from '../guest/widget/protocol';\nimport type { WidgetInputEvent } from '../guest/widget/types';\nimport { WidgetAudioEngine } from '../host/audio/engine';\nimport type {\n AudioContextLike,\n AudioNodeLike,\n AudioWorkletNodeLike,\n WidgetAudioEngineOptions,\n} from '../host/audio/engine';\nimport { NO_AUDIO_CONTROLS } from '../host/audio/noop';\nimport type { WidgetAudioControls, WidgetAudioOptions } from '../host/audio/types';\nimport type { WidgetSandbox } from '../host/types';\nimport type { WidgetModule } from '../types';\nimport { WidgetRuntimeError } from './errors';\nimport type {\n IPreparedWidgetInstance,\n IWidgetFrame,\n IWidgetFrameContext,\n IWidgetInstanceUpdate,\n IWidgetMessage,\n IWidgetRuntime,\n IWidgetRuntimeDiagnostic,\n IWidgetRuntimeDiagnosticCode,\n IWidgetRuntimeDiagnosticPhase,\n IWidgetRuntimeOptions,\n} from './types';\n\ninterface IRuntimeInstance {\n readonly instanceId: string;\n readonly widget: string;\n readonly module: WidgetModule;\n readonly generation: number;\n width: number;\n height: number;\n dpr: number;\n bitmap: ImageBitmap | undefined;\n sequence: number;\n mounted: boolean;\n audioSession: string | undefined;\n}\n\n/** One deliver or pointer call accepted by `deliver` / `dispatch`, waiting for the next step. */\ninterface IPendingCall {\n readonly instanceId: string;\n readonly method: string;\n readonly args: readonly unknown[];\n}\n\n/**\n * Creates the widget runtime over an existing sandbox.\n *\n * The runtime owns the sandbox: `dispose()` terminates it, so the caller must not keep using it\n * afterwards. The runtime never reads documents or files, resolves widget modules, drives a clock\n * or talks to a device runtime; those stay with the editor that calls it.\n */\nexport function createWidgetRuntime(\n sandbox: WidgetSandbox,\n options: IWidgetRuntimeOptions = {},\n): IWidgetRuntime {\n return new WidgetRuntimeImpl(sandbox, options);\n}\n\nclass WidgetRuntimeImpl implements IWidgetRuntime {\n readonly #sandbox: WidgetSandbox;\n readonly #engine: WidgetAudioEngine | undefined;\n readonly #instances = new Map<string, IRuntimeInstance>();\n readonly #pending: IPendingCall[] = [];\n readonly #published = new Emitter<IWidgetMessage>();\n readonly #rendered = new Emitter<IWidgetFrame>();\n readonly #diagnostics = new Emitter<IWidgetRuntimeDiagnostic>();\n readonly #unsubscribers: (() => void)[] = [];\n\n readonly onDidPublish: Event<IWidgetMessage> = this.#published.event;\n readonly onDidRender: Event<IWidgetFrame> = this.#rendered.event;\n readonly onDidDiagnostic: Event<IWidgetRuntimeDiagnostic> = this.#diagnostics.event;\n readonly audio: WidgetAudioControls;\n\n /** Serializes mount, update, unmount, setBindings and step; a failure never poisons the chain. */\n #tail: Promise<void> = Promise.resolve();\n #configured: Promise<boolean> | undefined;\n #simTime: TimePs = timePs(0);\n #generation = 0;\n #disposed = false;\n #disposal: Promise<void> | undefined;\n\n constructor(sandbox: WidgetSandbox, options: IWidgetRuntimeOptions) {\n this.#sandbox = sandbox;\n\n const audioOptions: WidgetAudioOptions | undefined = options.audio;\n if (audioOptions === undefined) {\n this.audio = NO_AUDIO_CONTROLS;\n } else {\n const context = audioOptions.context;\n const getAudioWorklet = audioOptions.getAudioWorklet;\n const engineOptions: WidgetAudioEngineOptions = {\n context: context as unknown as AudioContextLike,\n ...(audioOptions.destination === undefined\n ? {}\n : { destination: audioOptions.destination as unknown as AudioNodeLike }),\n ...(getAudioWorklet === undefined\n ? {}\n : {\n loadWorklet: () => getAudioWorklet(context) as Promise<AudioWorkletNodeLike>,\n }),\n ...(audioOptions.limits === undefined ? {} : { limits: audioOptions.limits }),\n report: (code, instanceId, message) =>\n this.#report(code, 'audio', message, instanceId === '' ? {} : { instanceId }),\n notify: {\n emitPort: (port) => {\n const lane = sandbox.audio;\n if (lane === undefined) {\n closePort(port);\n return;\n }\n try {\n lane.attachPort(port);\n } catch {\n closePort(port);\n }\n },\n emitState: (state) => {\n try {\n sandbox.audio?.setState(state);\n } catch {\n // The sandbox is already gone; its guest state no longer matters.\n }\n },\n },\n };\n const engine = new WidgetAudioEngine(engineOptions);\n this.#engine = engine;\n this.audio = engine;\n }\n\n this.#unsubscribers.push(\n sandbox.on(widgetFrameEvent, (payload) => this.#onFrame(payload)),\n sandbox.on(widgetPublishEvent, (payload) => this.#onPublish(payload)),\n sandbox.on(widgetErrorEvent, (payload) => this.#onError(payload)),\n sandbox.on(widgetAssetFailedEvent, (payload) => this.#onAssetFailed(payload)),\n );\n }\n\n mount(instance: IPreparedWidgetInstance): Promise<void> {\n return this.#run(async () => {\n const prepared = normalizePrepared(instance);\n this.#assertActive();\n if (this.#instances.has(prepared.instanceId)) {\n throw new WidgetRuntimeError(\n 'widget/instance-exists',\n `Widget instance \"${prepared.instanceId}\" is already mounted.`,\n );\n }\n const ref = splitRef(prepared.widget);\n if (ref === undefined) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `Widget reference \"${prepared.widget}\" must use the \"<package>:<widget>\" form.`,\n );\n }\n\n await this.#configure();\n this.#assertActive();\n\n const record: IRuntimeInstance = {\n instanceId: prepared.instanceId,\n widget: prepared.widget,\n module: prepared.module,\n generation: ++this.#generation,\n width: prepared.width,\n height: prepared.height,\n dpr: prepared.dpr,\n bitmap: undefined,\n sequence: 0,\n mounted: false,\n audioSession: undefined,\n };\n this.#instances.set(record.instanceId, record);\n\n try {\n await this.#sandbox.call(widgetLoadMethod, {\n packages: [\n {\n id: ref.packageId,\n modules: {\n [ref.widgetId]: {\n definition: prepared.module.definition,\n code: prepared.module.code,\n },\n },\n },\n ],\n });\n this.#assertOwnership(record);\n\n const audio = await this.#openAudio(record);\n this.#assertOwnership(record);\n\n const properties = mergeProperties(\n prepared.module.definition.properties,\n prepared.properties,\n );\n await this.#sandbox.call(widgetMountMethod, {\n instanceId: record.instanceId,\n widget: record.widget,\n width: record.width,\n height: record.height,\n dpr: record.dpr,\n props: properties,\n ...(prepared.assets === undefined ? {} : { assets: prepared.assets }),\n generation: record.generation,\n audio,\n });\n this.#assertOwnership(record);\n record.mounted = true;\n } catch (error) {\n this.#forget(record);\n await this.#releaseGuest(record.instanceId);\n if (record.audioSession !== undefined) {\n this.#engine?.closeSession(record.instanceId, record.audioSession);\n }\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n `Mount of widget instance \"${prepared.instanceId}\" was cancelled before it finished.`,\n );\n }\n if (this.#sandbox.state === 'terminated') {\n this.#report(\n 'widget/runtime-failed',\n 'runtime',\n 'The widget sandbox terminated during mount.',\n );\n throw new WidgetRuntimeError(\n 'widget/sandbox-failed',\n 'The widget sandbox terminated during mount.',\n { cause: error },\n );\n }\n this.#report(\n 'widget/mount-failed',\n 'mount',\n `Widget \"${prepared.widget}\" failed to mount: ${describeError(error)}`,\n { instanceId: prepared.instanceId, widget: prepared.widget },\n );\n throw error instanceof WidgetRuntimeError\n ? error\n : new WidgetRuntimeError(\n 'widget/sandbox-failed',\n `Widget \"${prepared.widget}\" failed to mount: ${describeError(error)}`,\n { cause: error },\n );\n }\n });\n }\n\n update(instanceId: string, update: IWidgetInstanceUpdate): Promise<void> {\n return this.#run(async () => {\n requireId(instanceId);\n this.#assertActive();\n const record = this.#requireMounted(instanceId);\n\n if (update.width !== undefined || update.height !== undefined || update.dpr !== undefined) {\n const width =\n update.width === undefined ? record.width : requireSize(update.width, 'width');\n const height =\n update.height === undefined ? record.height : requireSize(update.height, 'height');\n const dpr = update.dpr === undefined ? record.dpr : requireDpr(update.dpr);\n await this.#call(\n widgetResizeMethod,\n [instanceId, width, height, dpr],\n record,\n 'widget/update-failed',\n 'update',\n );\n record.width = width;\n record.height = height;\n record.dpr = dpr;\n }\n\n if (update.properties !== undefined) {\n const properties = mergeProperties(record.module.definition.properties, update.properties);\n await this.#call(\n widgetSetPropertiesMethod,\n [instanceId, properties],\n record,\n 'widget/update-failed',\n 'update',\n );\n }\n\n if (update.assets !== undefined) {\n await this.#call(\n widgetSetAssetsMethod,\n [instanceId, update.assets],\n record,\n 'widget/update-failed',\n 'update',\n );\n }\n });\n }\n\n unmount(instanceId: string): Promise<void> {\n return this.#run(async () => {\n requireId(instanceId);\n // Disposal already cleared every instance and terminated the sandbox.\n if (this.#disposed) return;\n const record = this.#instances.get(instanceId);\n if (record === undefined) return;\n\n this.#instances.delete(instanceId);\n this.#closeRecord(record);\n for (let index = this.#pending.length - 1; index >= 0; index -= 1) {\n if (this.#pending[index]?.instanceId === instanceId) this.#pending.splice(index, 1);\n }\n if (record.audioSession !== undefined) {\n this.#engine?.closeSession(instanceId, record.audioSession);\n }\n try {\n await this.#sandbox.call(widgetUnmountMethod, instanceId);\n } catch (error) {\n this.#report(\n 'widget/unmount-failed',\n 'unmount',\n `Widget instance \"${instanceId}\" could not be released: ${describeError(error)}`,\n { instanceId, widget: record.widget },\n );\n }\n });\n }\n\n deliver(message: IWidgetMessage): Promise<void> {\n try {\n if (this.#disposed) {\n throw new WidgetRuntimeError('widget/disposed', 'The widget runtime is disposed.');\n }\n const record = this.#requireMounted(message.instanceId);\n const port = record.module.definition.ports[message.port];\n if (port === undefined) {\n throw new WidgetRuntimeError(\n 'widget/unknown-port',\n `Widget instance \"${message.instanceId}\" has no port ${JSON.stringify(message.port)}.`,\n );\n }\n if (port.direction !== 'input') {\n throw new WidgetRuntimeError(\n 'widget/invalid-direction',\n `Port \"${message.port}\" of \"${message.instanceId}\" is an output.`,\n );\n }\n if (!payloadMatches(port.type, message.payload)) {\n throw new WidgetRuntimeError(\n 'widget/invalid-payload',\n `Payload for \"${message.instanceId}.${message.port}\" does not match ${port.type}.`,\n );\n }\n const simTime = requireTime(message.simTime, 'simTime');\n this.#pending.push({\n instanceId: message.instanceId,\n method: widgetDeliverMethod,\n args: [message.instanceId, message.port, message.payload, simTime],\n });\n return Promise.resolve();\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n dispatch(instanceId: string, event: WidgetInputEvent): Promise<void> {\n try {\n if (this.#disposed) {\n throw new WidgetRuntimeError('widget/disposed', 'The widget runtime is disposed.');\n }\n this.#requireMounted(instanceId);\n if (\n typeof event !== 'object' ||\n event === null ||\n typeof event.type !== 'string' ||\n event.type === ''\n ) {\n throw new WidgetRuntimeError(\n 'widget/invalid-payload',\n 'A widget input event needs a nonempty type.',\n );\n }\n this.#pending.push({\n instanceId,\n method: widgetPointerMethod,\n args: [instanceId, event],\n });\n return Promise.resolve();\n } catch (error) {\n return Promise.reject(error);\n }\n }\n\n step(context: IWidgetFrameContext): Promise<void> {\n return this.#run(async () => {\n this.#assertActive();\n const simTime = requireTime(context.simTime, 'simTime');\n const dt = requireTime(context.dt, 'dt');\n if (context.mode !== 'edit' && context.mode !== 'simulation') {\n throw new WidgetRuntimeError(\n 'widget/invalid-step',\n `Unknown widget step mode: ${String(context.mode)}.`,\n );\n }\n\n await this.#configure();\n this.#assertActive();\n\n for (const call of this.#pending.splice(0)) {\n const record = this.#instances.get(call.instanceId);\n if (record === undefined || !record.mounted) {\n this.#report(\n 'widget/deliver-failed',\n 'deliver',\n `Queued ${call.method} for \"${call.instanceId}\" was dropped: the instance is not mounted.`,\n { instanceId: call.instanceId },\n );\n continue;\n }\n try {\n await this.#sandbox.call(call.method, ...call.args);\n } catch (error) {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n 'Widget step was cancelled by runtime disposal.',\n );\n }\n this.#report(\n 'widget/deliver-failed',\n 'deliver',\n `Widget call \"${call.method}\" failed for \"${call.instanceId}\": ${describeError(error)}`,\n { instanceId: call.instanceId, widget: record.widget },\n );\n }\n }\n\n this.#simTime = simTime;\n try {\n await this.#sandbox.call(widgetStepMethod, { simTime, dt, mode: context.mode });\n } catch (error) {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n 'Widget step was cancelled by runtime disposal.',\n );\n }\n this.#report('widget/step-failed', 'step', `Widget step failed: ${describeError(error)}`);\n throw new WidgetRuntimeError(\n 'widget/sandbox-failed',\n `Widget step failed: ${describeError(error)}`,\n { cause: error },\n );\n }\n });\n }\n\n setBindings(\n instanceId: string,\n bindings: Readonly<Record<string, CanvasBindingTarget>>,\n ): Promise<void> {\n return this.#run(async () => {\n const normalized = normalizeBindings(bindings);\n requireId(instanceId);\n this.#assertActive();\n const record = this.#requireMounted(instanceId);\n await this.#call(\n widgetSetBindingsMethod,\n [instanceId, normalized],\n record,\n 'widget/update-failed',\n 'update',\n );\n });\n }\n\n dispose(): Promise<void> {\n if (this.#disposal !== undefined) return this.#disposal;\n this.#disposed = true;\n this.#pending.length = 0;\n // Terminating now is what cancels a mount that is still waiting for the guest: its pending\n // calls reject, the operation cleans up its own record, and the queued shutdown then runs.\n const terminating = terminateSandbox(this.#sandbox);\n this.#disposal = this.#run(async () => {\n const records = [...this.#instances.values()];\n this.#instances.clear();\n for (const record of records) this.#closeRecord(record);\n for (const unsubscribe of this.#unsubscribers.splice(0)) {\n try {\n unsubscribe();\n } catch {\n // The sandbox may already be gone.\n }\n }\n this.#engine?.dispose();\n await terminating;\n this.#published.dispose();\n this.#rendered.dispose();\n this.#diagnostics.dispose();\n });\n return this.#disposal;\n }\n\n /** Runs one operation after the previous one, whether it resolved or rejected. */\n #run<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.#tail.then(operation, operation);\n this.#tail = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n #assertActive(): void {\n if (this.#disposed) {\n throw new WidgetRuntimeError('widget/disposed', 'The widget runtime is disposed.');\n }\n if (this.#sandbox.state === 'terminated') {\n throw new WidgetRuntimeError('widget/sandbox-failed', 'The widget sandbox is terminated.');\n }\n }\n\n #assertOwnership(record: IRuntimeInstance): void {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n `Mount of widget instance \"${record.instanceId}\" was cancelled before it finished.`,\n );\n }\n if (this.#instances.get(record.instanceId) !== record) {\n throw new WidgetRuntimeError(\n 'widget/unknown-instance',\n `Widget instance \"${record.instanceId}\" was replaced during mount.`,\n );\n }\n }\n\n #requireMounted(instanceId: string): IRuntimeInstance {\n const record = this.#instances.get(instanceId);\n if (record === undefined || !record.mounted) {\n throw new WidgetRuntimeError(\n 'widget/unknown-instance',\n `Widget instance \"${instanceId}\" is not mounted.`,\n );\n }\n return record;\n }\n\n #configure(): Promise<boolean> {\n const existing = this.#configured;\n if (existing !== undefined) return existing;\n\n const pending = this.#sandbox\n .call(widgetConfigureMethod, {\n explicitStepping: true,\n directTopicService: 'simulation-runtime',\n })\n .then((result) => result === true)\n .catch((error: unknown) => {\n this.#configured = undefined;\n const message = `Widget guest configuration failed: ${describeError(error)}`;\n this.#report('widget/runtime-failed', 'runtime', message);\n throw new WidgetRuntimeError('widget/sandbox-failed', message, { cause: error });\n });\n this.#configured = pending;\n return pending;\n }\n\n async #openAudio(record: IRuntimeInstance): Promise<WidgetAudioMountInfo> {\n const engine = this.#engine;\n if (engine === undefined) return { state: 'unavailable' };\n const info = await engine.open(record.instanceId);\n if (info.session !== undefined) record.audioSession = info.session;\n return info;\n }\n\n async #call(\n method: string,\n args: readonly unknown[],\n record: IRuntimeInstance,\n code: IWidgetRuntimeDiagnosticCode,\n phase: IWidgetRuntimeDiagnosticPhase,\n ): Promise<void> {\n try {\n await this.#sandbox.call(method, ...args);\n } catch (error) {\n if (this.#disposed) {\n throw new WidgetRuntimeError(\n 'widget/disposed',\n `Widget call \"${method}\" was cancelled by runtime disposal.`,\n );\n }\n this.#report(\n code,\n phase,\n `Widget call \"${method}\" failed for \"${record.instanceId}\": ${describeError(error)}`,\n { instanceId: record.instanceId, widget: record.widget },\n );\n throw new WidgetRuntimeError(\n 'widget/sandbox-failed',\n `Widget call \"${method}\" failed for \"${record.instanceId}\": ${describeError(error)}`,\n { cause: error },\n );\n }\n }\n\n #forget(record: IRuntimeInstance): void {\n if (this.#instances.get(record.instanceId) === record) {\n this.#instances.delete(record.instanceId);\n }\n this.#closeRecord(record);\n }\n\n #closeRecord(record: IRuntimeInstance): void {\n const bitmap = record.bitmap;\n record.bitmap = undefined;\n closeBitmap(bitmap);\n }\n\n async #releaseGuest(instanceId: string): Promise<void> {\n try {\n await this.#sandbox.call(widgetUnmountMethod, instanceId);\n } catch {\n // The guest never created the instance, or the sandbox is already gone.\n }\n }\n\n #onFrame(payload: unknown): void {\n const message = payload as Partial<WidgetFrameMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n const { instanceId, bitmap } = message;\n if (typeof instanceId !== 'string' || !isBitmap(bitmap)) return;\n if (this.#disposed) {\n closeBitmap(bitmap);\n return;\n }\n\n const record = this.#instances.get(instanceId);\n if (\n record === undefined ||\n (message.generation !== undefined && message.generation !== record.generation)\n ) {\n // A frame of an unmounted instance, or of the instance that used to own this id.\n closeBitmap(bitmap);\n return;\n }\n\n const width = frameNumber(message.width, record.width);\n const height = frameNumber(message.height, record.height);\n const dpr = frameNumber(message.dpr, record.dpr);\n const previous = record.bitmap;\n record.bitmap = bitmap;\n record.width = width;\n record.height = height;\n record.dpr = dpr;\n record.sequence += 1;\n closeBitmap(previous);\n\n this.#fire(this.#rendered, 'render', {\n instanceId,\n width,\n height,\n dpr,\n bitmap,\n sequence: record.sequence,\n });\n }\n\n #onPublish(payload: unknown): void {\n const message = payload as Partial<WidgetPublishMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n const { instanceId, port } = message;\n if (typeof instanceId !== 'string' || typeof port !== 'string') return;\n if (this.#disposed) return;\n\n const record = this.#instances.get(instanceId);\n if (record === undefined) {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Publish from unknown widget instance \"${instanceId}\" was dropped.`,\n { instanceId, port },\n );\n return;\n }\n const definitionPort = record.module.definition.ports[port];\n if (definitionPort === undefined) {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Widget \"${instanceId}\" published on unknown port \"${port}\".`,\n { instanceId, widget: record.widget, port },\n );\n return;\n }\n if (definitionPort.direction !== 'output') {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Widget \"${instanceId}\" published on input port \"${port}\".`,\n { instanceId, widget: record.widget, port },\n );\n return;\n }\n if (!payloadMatches(definitionPort.type, message.payload)) {\n this.#report(\n 'widget/publish-rejected',\n 'publish',\n `Publish on \"${instanceId}.${port}\" does not match ${definitionPort.type}.`,\n { instanceId, widget: record.widget, port },\n );\n return;\n }\n\n this.#fire(this.#published, 'publish', {\n instanceId,\n port,\n payload: message.payload,\n simTime: publishTime(message.simTime, this.#simTime),\n ...(message.direct === true ? { direct: true as const } : {}),\n });\n }\n\n #onError(payload: unknown): void {\n const message = payload as Partial<WidgetErrorMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n if (typeof message.instanceId !== 'string') return;\n // A mount failure travels back through the rejected `mount()` call instead.\n if (message.phase !== 'render' && message.phase !== 'deliver') return;\n\n const record = this.#instances.get(message.instanceId);\n const code: IWidgetRuntimeDiagnosticCode =\n message.phase === 'render' ? 'widget/render-failed' : 'widget/deliver-failed';\n const name = message.error?.name ?? 'Error';\n const text = message.error?.message ?? 'Unknown widget failure';\n this.#report(\n code,\n message.phase,\n `Widget \"${message.instanceId}\" failed during ${message.phase}: ${name}: ${text}`,\n {\n instanceId: message.instanceId,\n ...(record === undefined ? {} : { widget: record.widget }),\n },\n );\n }\n\n #onAssetFailed(payload: unknown): void {\n const message = payload as Partial<WidgetAssetFailedMessage> | null | undefined;\n if (message === null || typeof message !== 'object') return;\n if (typeof message.instanceId !== 'string') return;\n\n const src = typeof message.src === 'string' ? message.src : 'unknown';\n const name = message.error?.name ?? 'Error';\n const text = message.error?.message ?? 'Unknown asset failure';\n const record = this.#instances.get(message.instanceId);\n this.#report(\n 'widget/asset-failed',\n 'asset',\n `Widget \"${message.instanceId}\" could not read asset \"${src}\": ${name}: ${text}`,\n {\n instanceId: message.instanceId,\n ...(record === undefined ? {} : { widget: record.widget }),\n },\n );\n }\n\n #report(\n code: IWidgetRuntimeDiagnosticCode,\n phase: IWidgetRuntimeDiagnosticPhase,\n message: string,\n ids: {\n readonly instanceId?: string;\n readonly widget?: string;\n readonly port?: string;\n } = {},\n ): void {\n if (this.#disposed) return;\n const diagnostic: IWidgetRuntimeDiagnostic = {\n code,\n message,\n phase,\n ...(ids.instanceId === undefined ? {} : { instanceId: ids.instanceId }),\n ...(ids.widget === undefined ? {} : { widget: ids.widget }),\n ...(ids.port === undefined ? {} : { port: ids.port }),\n };\n this.#fire(this.#diagnostics, 'diagnostic', diagnostic);\n }\n\n /** Observer exceptions never break the instance flow a diagnostic or frame reports. */\n #fire<T>(emitter: Emitter<T>, label: string, value: T): void {\n try {\n emitter.fire(value);\n } catch (error) {\n console.error(`[@mica-js/widget] ${label} listener threw`, error);\n }\n }\n}\n\nfunction normalizePrepared(instance: IPreparedWidgetInstance): IPreparedWidgetInstance {\n if (typeof instance !== 'object' || instance === null) {\n throw new WidgetRuntimeError('widget/invalid-instance', 'A prepared widget is required.');\n }\n requireId(instance.instanceId);\n if (typeof instance.widget !== 'string' || !instance.widget.includes(':')) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n 'A prepared widget needs a \"<package>:<widget>\" reference.',\n );\n }\n const module = instance.module;\n if (\n typeof module !== 'object' ||\n module === null ||\n typeof module.code !== 'string' ||\n typeof module.definition !== 'object' ||\n module.definition === null ||\n typeof module.definition.ports !== 'object' ||\n module.definition.ports === null\n ) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `Widget \"${instance.widget}\" has no complete module.`,\n );\n }\n return {\n instanceId: instance.instanceId,\n widget: instance.widget,\n module,\n width: requireSize(instance.width, 'width'),\n height: requireSize(instance.height, 'height'),\n dpr: requireDpr(instance.dpr),\n ...(instance.properties === undefined ? {} : { properties: instance.properties }),\n ...(instance.assets === undefined ? {} : { assets: instance.assets }),\n };\n}\n\nfunction requireId(value: unknown): string {\n if (typeof value !== 'string' || value === '') {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n 'A widget instance id must be a nonempty string.',\n );\n }\n return value;\n}\n\nfunction requireSize(value: unknown, name: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `${name}=${String(value)} must be a finite nonnegative number.`,\n );\n }\n return value;\n}\n\nfunction requireDpr(value: unknown): number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n throw new WidgetRuntimeError(\n 'widget/invalid-instance',\n `dpr=${String(value)} must be a finite positive number.`,\n );\n }\n return value;\n}\n\nfunction requireTime(value: unknown, name: string): TimePs {\n try {\n return timePs(value as number);\n } catch (error) {\n throw new WidgetRuntimeError(\n 'widget/invalid-time',\n `${name} must be a valid time in picoseconds: ${describeError(error)}`,\n { cause: error },\n );\n }\n}\n\nfunction publishTime(value: unknown, fallback: TimePs): TimePs {\n if (typeof value !== 'number') return fallback;\n try {\n return timePs(value);\n } catch {\n return fallback;\n }\n}\n\nfunction frameNumber(value: unknown, fallback: number): number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback;\n}\n\nfunction normalizeBindings(\n value: Readonly<Record<string, CanvasBindingTarget>>,\n): Readonly<Record<string, CanvasBindingTarget>> {\n if (typeof value !== 'object' || value === null) {\n throw new WidgetRuntimeError('widget/invalid-update', 'Bindings must be an object.');\n }\n const bindings: Record<string, CanvasBindingTarget> = {};\n for (const [port, target] of Object.entries(value)) {\n if (\n typeof target !== 'object' ||\n target === null ||\n typeof target.symbol !== 'string' ||\n target.symbol === '' ||\n typeof target.port !== 'string' ||\n target.port === ''\n ) {\n throw new WidgetRuntimeError(\n 'widget/invalid-update',\n `Binding \"${port}\" needs a nonempty symbol and port.`,\n );\n }\n bindings[port] = { symbol: target.symbol, port: target.port };\n }\n return Object.freeze(bindings);\n}\n\nfunction splitRef(ref: string): { packageId: string; widgetId: string } | undefined {\n const separator = ref.indexOf(':');\n if (separator <= 0 || separator === ref.length - 1) return undefined;\n return { packageId: ref.slice(0, separator), widgetId: ref.slice(separator + 1) };\n}\n\nfunction isBitmap(value: unknown): value is ImageBitmap {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as ImageBitmap).close === 'function'\n );\n}\n\nfunction isVec2d(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) return false;\n const point = value as { readonly x?: unknown; readonly y?: unknown };\n return typeof point.x === 'number' && typeof point.y === 'number';\n}\n\n/** Mirrors the shared value model: a payload must match the declared port type exactly. */\nfunction payloadMatches(type: PayloadType, payload: unknown): boolean {\n switch (type) {\n case 'boolean':\n return typeof payload === 'boolean';\n case 'number':\n return typeof payload === 'number';\n case 'string':\n return typeof payload === 'string';\n case 'bytes':\n case 'bytes<rgb565>':\n case 'bytes<segments>':\n return payload instanceof Uint8Array;\n case 'vec2d':\n return isVec2d(payload);\n case 'vec3d':\n return isVec2d(payload) && typeof (payload as { readonly z?: unknown }).z === 'number';\n }\n}\n\nfunction closeBitmap(bitmap: ImageBitmap | undefined): void {\n if (bitmap === undefined) return;\n try {\n bitmap.close();\n } catch {\n // Already detached.\n }\n}\n\nfunction closePort(port: MessagePort): void {\n try {\n port.close();\n } catch {\n // Already closed.\n }\n}\n\nfunction describeError(error: unknown): string {\n if (error instanceof Error && error.message) return error.message;\n return typeof error === 'string' ? error : String(error);\n}\n\nasync function terminateSandbox(sandbox: WidgetSandbox): Promise<void> {\n try {\n await sandbox.terminate('widget runtime disposed');\n } catch {\n // Already terminated.\n }\n}\n","import { createRpc } from '@mica-js/core/rpc';\nimport { loggerService } from '@mica-js/core/logging';\nimport { isHostFsError, toHostFsErrorPayload } from '../host-fs/errors';\nimport { widgetAudioGuestService } from '../guest/audio/protocol';\nimport {\n widgetGuestControlService,\n widgetGuestService,\n widgetHostCapabilitiesService,\n widgetHostControlService,\n} from '../guest/widget/protocol';\nimport type { SandboxWorker } from '@mica-js/sandbox';\nimport type { WidgetSandbox, WidgetSandboxHostOptions } from './types';\n\n/** Adapts a provider-created widget worker to the runtime's RPC-facing surface. */\nexport async function createWidgetSandboxFromWorker(\n worker: SandboxWorker,\n options: WidgetSandboxHostOptions,\n): Promise<WidgetSandbox> {\n const devicePort = options.devicePort;\n let port: MessagePort;\n let rpc: ReturnType<typeof createRpc> | undefined;\n let logRegistration: { dispose(): void } | undefined;\n try {\n await worker.ready;\n const channel = new MessageChannel();\n port = channel.port1;\n const endpoint = createRpc(port);\n rpc = endpoint;\n logRegistration = endpoint.register(loggerService, {\n write(record) {\n const method = console[record.level] ?? console.log;\n method.call(console, `[${record.scope}]`, record.message, ...record.data);\n },\n });\n const transfer = devicePort === undefined ? [channel.port2] : [channel.port2, devicePort];\n worker.postMessage(null, transfer);\n } catch (error) {\n logRegistration?.dispose();\n rpc?.dispose();\n await worker.terminate('widget sandbox failed to start').catch(() => undefined);\n throw error;\n }\n const endpoint = rpc;\n if (endpoint === undefined) {\n throw new Error('Widget RPC endpoint was not created.');\n }\n const listeners = new Map<string, Set<(payload: unknown) => void>>();\n const dispatch = (type: string, payload: unknown) => {\n for (const listener of [...(listeners.get(type) ?? [])]) listener(payload);\n };\n endpoint.register(\n widgetHostCapabilitiesService,\n {\n async read(uri: string) {\n if (!options.fs) throw new Error(`No HostFs configured for ${uri}`);\n try {\n return await options.fs.read(uri);\n } catch (error) {\n if (isHostFsError(error)) {\n const payload = toHostFsErrorPayload(error);\n throw Object.assign(new Error(JSON.stringify(payload)), { name: 'HostFsError' });\n }\n throw error;\n }\n },\n },\n {\n transfer: (member, value) =>\n member === 'read' && value instanceof Uint8Array ? [value.buffer] : [],\n },\n );\n endpoint.register(widgetHostControlService, { event: dispatch });\n const guest = endpoint.getProxy(widgetGuestService) as unknown as Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n >;\n const audio = endpoint.getProxy(widgetAudioGuestService, {\n transfer: (member, args) => (member === 'attachPort' ? [args[0] as MessagePort] : []),\n });\n return {\n get state() {\n return worker.state;\n },\n directDevice: devicePort !== undefined,\n call: (method, ...args) => guest[method]!(...args),\n on: (type, listener) => {\n let set = listeners.get(type);\n if (!set) listeners.set(type, (set = new Set()));\n set.add(listener);\n return () => set?.delete(listener);\n },\n emit: (type, payload, transfer) => {\n void endpoint\n .getProxy(widgetGuestControlService, { transfer: () => transfer ?? [] })\n .dispatchEvent(type, payload)\n .catch(() => undefined);\n },\n audio: {\n attachPort: (port) => {\n void audio.attachPort(port).catch(() => undefined);\n },\n setState: (state) => {\n void audio.setState(state).catch(() => undefined);\n },\n },\n terminate: async (reason) => {\n logRegistration?.dispose();\n endpoint.dispose();\n await worker.terminate(reason);\n },\n } satisfies WidgetSandbox;\n}\n","import { SandboxWorker } from '@mica-js/sandbox';\nimport type { SandboxWorkerOptions } from '@mica-js/sandbox';\nimport guestScript from '../guest/widget/entry.ts?sandbox-worker-code';\n\n/**\n * The widget guest worker script, bundled and minified into this module by\n * `@mica-js/sandbox/vite` while the package itself is built.\n *\n * It is a classic script: every dependency is inlined, so the sandbox can run it without a module\n * loader and the package publishes no separate `*.sandbox.js` file.\n */\nexport const widgetGuestScript: string = guestScript;\n\n/**\n * Creates the widget host guest worker.\n *\n * Hosts start the guest, then wire its RPC surface with `createWidgetSandboxFromWorker`.\n */\nexport function createWidgetHostGuestSandbox(options: SandboxWorkerOptions = {}): SandboxWorker {\n return new SandboxWorker(widgetGuestScript, { name: 'widget', ...options });\n}\n"],"mappings":";;;;;;;;AAmBA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CACA;CACA;CAEA,YAAY,MAA2B,SAAiB,UAAkC,CAAC,GAAG;EAC5F,MAAM,SAAS,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;EACjF,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,YAAY,QAAQ;EACzB,KAAK,OAAO,QAAQ;CACtB;AACF;;;ACRA,IAAM,eAAe;AACrB,IAAM,iBAAiB;AACvB,IAAM,2BAA2B;;AAEjC,IAAM,aAAa;;;;;;;AAqBnB,eAAsB,kBAAkB,OAA6C;CACnF,MAAM,WAAW,MAAM,aAAa,KAAK;CACzC,MAAM,UAAwC,CAAC;CAC/C,MAAM,UAAyC,CAAC;CAEhD,KAAK,MAAM,SAAS,SAAS,SAAS;EACpC,MAAM,aAAa,MAAM,eAAe,OAAO,SAAS,IAAI,KAAK;EACjE,MAAM,qBAAqB,qBAAqB,MAAM,IAAI;EAC1D,MAAM,OAAO,MAAM,mBAAmB,OAAO,SAAS,IAAI,MAAM,IAAI,kBAAkB;EACtF,QAAQ,MAAM,MAAM;GAAE;GAAY;EAAK;EACvC,QAAQ,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC;CAC/B;CAGA,MAAM,cAAc,MAAM,UAAU,KAAK,UAAU,OAAO,GAAG,SAAS,EAAE;CACxE,OAAO;EAAE,IAAI,SAAS;EAAI,SAAS,SAAS;EAAS;EAAa;CAAQ;AAC5E;AAEA,eAAe,aAAa,OAA+C;CACzE,IAAI;CACJ,IAAI;EACF,QAAQ,MAAM,MAAM,KAAK,YAAY;CACvC,SAAS,OAAO;EACd,M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