@mica-js/editor 0.13.0 → 0.15.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.
@@ -1 +0,0 @@
1
- {"version":3,"file":"runtime-hyeAcSP7.js","names":["closeBitmap","IDLE"],"sources":["../src/fused/runtime/protocol.ts","../src/fused/runtime/packages.ts","../src/fused/runtime/host/audio.ts","../src/fused/runtime/host/connection.ts","../src/fused/runtime/host/display.ts","../src/fused/runtime/model-events.ts","../src/fused/runtime/host/model.ts","../src/fused/runtime/host/runtime.ts","../src/fused/runtime/values.ts","../src/fused/runtime/simulation/model-channel.ts","../src/fused/runtime/simulation/guest.ts","../src/fused/runtime/audio.ts","../src/fused/runtime/display/model.ts","../src/fused/runtime/display/view.ts","../src/fused/runtime/display/guest.ts","../src/fused/runtime/index.ts"],"sourcesContent":["/**\n * Wire contracts of the fused editor runtime bridge (RFC 0022 / RFC 0025).\n *\n * One simulation guest owns the document snapshot, the locked packages and every model; one display\n * guest owns the declared `view2d.entry` modules and draws overlays. Both are `SandboxWorker` guests\n * and speak only these typed RPC services over ports created with `createRpc`: the main thread never\n * imports a model or an author view module.\n *\n * Binary payloads, package bytes and overlay bitmaps travel through registration transfer hooks; the\n * model lane is a direct port between the two guests, so a display input handler reaches its model\n * without a hop through the editor.\n */\nimport { defineRpcService } from '@mica-js/core/rpc';\nimport type { TimePs } from '@mica-js/core';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { WidgetAudioMountInfo, WidgetAudioState } from '@mica-js/widget/audio-guest';\nimport type { IFusedAudio } from './audio';\nimport type {\n DeviceLock,\n FusedDocument,\n Geometry2D,\n PackageFile,\n Point2D,\n Value,\n} from '@mica-js/document/fused';\nimport type {\n ProgramArtifact,\n ProgramFile,\n ProgramTarget,\n MemoryProgram,\n ProgramFiles,\n ModelEvent,\n ResourceRequest,\n RuntimeDiagnostic,\n} from '@mica-js/sdk/fused';\n\n/** Session status the host mirrors; `idle` means no models are mounted (edit mode). */\nexport type FusedSessionStatus =\n 'idle' | 'starting' | 'paused' | 'running' | 'faulted' | 'disposed';\n\n/** Wall-clock pacing of continuous simulation in the editor worker. */\nexport type FusedSimulationPacing = 'realtime' | 'unlimited';\n\n/** Presentation mode of one workbench (RFC 0025). */\nexport type FusedDisplayMode = 'edit' | 'run';\n\n/** One loaded firmware segment of a presentation snapshot (RFC 0026). */\nexport interface IFusedFirmwareSegment {\n readonly addressSpace: string;\n readonly address: number;\n /** Segment bytes; an independent copy owned by the presentation snapshot. */\n readonly bytes: Uint8Array;\n}\n\n/** Read-only firmware snapshot a presentation may read (RFC 0026). */\nexport interface IFusedFirmwareSnapshot {\n readonly kind: 'firmware';\n readonly segments: readonly IFusedFirmwareSegment[];\n}\n\nexport interface IFusedProgramFilesSnapshot {\n readonly kind: 'filesystem';\n readonly files: readonly ProgramFile[];\n}\n\n/**\n * One resolved property value a presentation may read.\n *\n * Scalars stay plain; `image` and `binary` properties are their resolved bytes; `firmware`\n * properties are the loaded, segment-addressable snapshot. Resolution happens in the simulation\n * worker, so an unresolved property rejects the presentation instead of shrinking its props.\n */\nexport type FusedPresentationValue =\n | string\n | number\n | boolean\n | null\n | Uint8Array\n | IFusedFirmwareSnapshot\n | IFusedProgramFilesSnapshot;\n\nexport type FusedResolvedPresentationProps = Readonly<\n Record<string, string | number | boolean | null | Uint8Array | MemoryProgram | ProgramFiles>\n>;\n\n/** Read-only plain property snapshot handed to a 2D presentation. */\nexport type FusedPresentationProps = Readonly<Record<string, FusedPresentationValue>>;\n\n/** State of the simulation session as the host sees it. */\nexport interface IFusedSessionState {\n readonly status: FusedSessionStatus;\n readonly simTime: TimePs;\n}\n\n/**\n * Everything the display worker needs to prepare one instance.\n *\n * Geometry and the property projection are resolved inside the simulation worker, so the host never\n * parses a manifest or evaluates an author module.\n */\nexport interface IFusedInstancePresentation {\n readonly instanceId: string;\n /** Full `publisher:name` device id the instance locks. */\n readonly device: string;\n readonly lock: DeviceLock;\n readonly geometry: Geometry2D;\n /** Package-root relative `.js` overlay entry; `undefined` for a geometry-only device. */\n readonly view: string | undefined;\n /**\n * Resolved property snapshot, identical to the one the model receives: manifest default and\n * document override through the SDK, with resource bytes and the loaded firmware image. An\n * instance whose props cannot be projected has no presentation at all, so this is never partial.\n */\n readonly props: FusedPresentationProps;\n /** Declared model method names; empty for a device without a model. */\n readonly methods: readonly string[];\n /** Declared model event names; empty for a device without a model. */\n readonly events: readonly string[];\n}\n\n/** Preparation request of the simulation guest: verify packages and describe the scene. */\nexport interface IFusedPrepareRequest {\n readonly document: FusedDocument;\n readonly mode: FusedDisplayMode;\n}\n\nexport interface IFusedPrepareResult {\n readonly instances: readonly IFusedInstancePresentation[];\n}\n\n/** Request that creates the models of one run session. */\nexport interface IFusedLoadRequest {\n readonly document: FusedDocument;\n /** Fixed positive step of every advance, in picoseconds. */\n readonly step: TimePs;\n readonly simulationPacing?: FusedSimulationPacing;\n /** Explicit simulator batch-execution switch; omitted uses the board default. */\n readonly batchExecution?: boolean;\n}\n\n/** Request that prepares the boot path ahead of a run session. */\nexport interface IFusedWarmupRequest {\n readonly document: FusedDocument;\n /** Fixed positive step of every advance, in picoseconds. */\n readonly step: TimePs;\n /** Explicit simulator batch-execution switch; omitted uses the board default. */\n readonly batchExecution?: boolean;\n}\n\n/** One model event as it crosses the sandbox boundary. */\nexport interface IFusedModelEventWire {\n readonly instanceId: string;\n readonly event: string;\n readonly payload: ModelEvent<Value>;\n}\n\n/** Dynamic methods of one display-side model client; only declared names resolve. */\nexport type FusedModelMethods = Readonly<Record<string, (params: Value) => Promise<Value>>>;\n\n/** Declared event outlets of one model client. */\nexport type FusedModelEvents = Readonly<Record<string, Event<ModelEvent<Value>>>>;\n\n/**\n * Model client handed to a presentation or to the editor.\n *\n * Structurally the RFC 0021 `ModelClient` of a dynamically declared interface: methods are\n * asynchronous and every event is a core `Event` of a `ModelEvent` payload.\n */\nexport interface IFusedModelClient {\n readonly methods: FusedModelMethods;\n readonly events: FusedModelEvents;\n}\n\n/** Package resources one presentation may read (RFC 0022 `ViewAssets`). */\nexport interface IFusedViewAssets {\n /** Reads one declared package file; bytes are copied into the caller. */\n read(path: string): Promise<Uint8Array>;\n /** Decodes one image; the caller owns the bitmap and must `close()` it. */\n loadImage(path: string): Promise<ImageBitmap>;\n}\n\nexport type FusedViewInputType = 'pointerdown' | 'pointerup' | 'pointermove';\n\n/** Local pointer input delivered to one presentation (RFC 0022). */\nexport interface IFusedViewInput {\n readonly type: FusedViewInputType;\n /** Position in the device's local coordinates. */\n readonly position: Point2D;\n /** DOM button number of the event. */\n readonly button: number;\n /** DOM button bit mask of the buttons currently held. */\n readonly buttons: number;\n}\n\n/** Context a `view2d.entry` factory receives (RFC 0022). */\nexport interface IFusedView2DContext {\n readonly mode: FusedDisplayMode;\n readonly props: FusedResolvedPresentationProps;\n readonly geometry: Geometry2D;\n /** Proxy of the owning instance; `undefined` in edit mode and for devices without a model. */\n readonly model: IFusedModelClient | undefined;\n readonly assets: IFusedViewAssets;\n /** Instance audio, independent of overlay rendering and HTML panels. */\n readonly audio: IFusedAudio;\n /** Marks the overlay stale; the host decides when to repaint. */\n invalidate(): void;\n}\n\n/** Object a `view2d.entry` default factory returns (RFC 0022). */\nexport interface IFusedView2D {\n initialize?(): void | Promise<void>;\n renderOverlay?(context: OffscreenCanvasRenderingContext2D): void;\n input?(event: IFusedViewInput): void | Promise<void>;\n dispose?(): void;\n}\n\n/** Default export of a `view2d.entry` module. */\nexport type FusedView2DFactory = (context: IFusedView2DContext) => IFusedView2D;\n\n/** Simulation guest, reached through {@link fusedSimulationService}. */\nexport interface IFusedSimulationService {\n prepare(request: IFusedPrepareRequest): Promise<IFusedPrepareResult>;\n load(request: IFusedLoadRequest): Promise<IFusedSessionState>;\n /**\n * Translates the boot path ahead of time: builds a throwaway session, advances it once and\n * releases it, so the next real run reuses the generated code. Emits no state or model events;\n * resolves without work when models are already mounted. A following `prepare`/`load` cancels it.\n */\n warmup(request: IFusedWarmupRequest): Promise<void>;\n step(): Promise<IFusedSessionState>;\n resume(): Promise<void>;\n /** Stops advancement synchronously; the RPC result acknowledges the paused state. */\n pause(): void;\n reset(): Promise<void>;\n /** Releases the models and keeps the captured package bytes for the next load. */\n dispose(): Promise<void>;\n /**\n * Drops cached program artifacts so the next resolution asks the host again.\n *\n * `projectId` omitted means every project; with a `fingerprint`, entries whose cached artifact\n * already carries that fingerprint are kept.\n */\n invalidatePrograms(projectId?: string, fingerprint?: string): Promise<void>;\n call(instanceId: string, method: string, params: Value): Promise<Value>;\n getState(): IFusedSessionState;\n onDidChangeState(listener: (state: IFusedSessionState) => void): () => void;\n onDidReportDiagnostic(listener: (diagnostic: RuntimeDiagnostic) => void): () => void;\n /** Every model event of the session, in production order. */\n onDidModelEvent(listener: (event: IFusedModelEventWire) => void): () => void;\n}\n\n/** Paths of one locked package, resolved by the host (RFC 0020). */\nexport interface IFusedPackageFilesWire {\n readonly lock: DeviceLock;\n readonly files: Readonly<Record<string, PackageFile>>;\n}\n\n/** Host package access both guests share; the host owns the bytes and verifies nothing twice. */\nexport interface IFusedHostPackageService {\n open(lock: DeviceLock): Promise<IFusedPackageFilesWire>;\n /** Returns a copy the guest may keep; the reply transfers its buffer. */\n read(lock: DeviceLock, path: string): Promise<Uint8Array>;\n}\n\n/** Host resources the simulation guest reaches during preparation (RFC 0020 / RFC 0026). */\nexport interface IFusedHostResourceService {\n readResource(request: ResourceRequest): Promise<Uint8Array>;\n resolveProgramProject(projectId: string, target: ProgramTarget): Promise<ProgramArtifact>;\n}\n\n/** Model lane served by the simulation guest to the display guest over the direct port. */\nexport interface IFusedModelChannelService {\n call(instanceId: string, method: string, params: Value): Promise<Value>;\n subscribe(instanceId: string, event: string): void;\n unsubscribe(instanceId: string, event: string): void;\n /** Replies on the model lane after every event already sent on that lane. */\n settle(): void;\n}\n\n/** Model event lane served by the display guest to the simulation guest. */\nexport interface IFusedModelSinkService {\n deliver(event: IFusedModelEventWire): void;\n}\n\n/** Preparation of the display guest: one mode and the instances of the current session. */\nexport interface IFusedDisplayPrepareRequest {\n readonly mode: FusedDisplayMode;\n readonly instances: readonly IFusedInstancePresentation[];\n}\n\n/** Pixels per local unit and the overlay extent the host reserves for one instance. */\nexport interface IFusedDisplayLayout {\n /** Overlay width in device pixels. */\n readonly width: number;\n /** Overlay height in device pixels. */\n readonly height: number;\n /** Device pixels per local unit. */\n readonly scale: number;\n}\n\n/** One overlay render request. */\nexport interface IFusedRenderRequest extends IFusedDisplayLayout {\n readonly instanceId: string;\n /** Monotonic request number the frame echoes back, so stale results are dropped. */\n readonly generation: number;\n}\n\n/** Rendered overlay of one instance; the bitmap lives in the host after the transfer. */\nexport interface IFusedOverlayFrame extends IFusedDisplayLayout {\n readonly instanceId: string;\n readonly generation: number;\n readonly bitmap: ImageBitmap;\n}\n\n/** A presentation asked for a repaint. */\nexport interface IFusedInvalidateEvent {\n readonly instanceId: string;\n}\n\n/** Display guest, reached through {@link fusedDisplayService}. */\nexport interface IFusedDisplayService {\n /** Direct display guest to audio worklet lane, transferred by the host. */\n attachAudio(port: MessagePort): void;\n setAudioState(state: WidgetAudioState): void;\n /**\n * Creates the presentation factories of one mode; nothing is initialized yet.\n *\n * It runs before the models exist, so a factory can subscribe to model events and still observe\n * the events the model produces while it initializes.\n */\n prepare(request: IFusedDisplayPrepareRequest): Promise<void>;\n /**\n * Runs `initialize` of every prepared presentation, after the models are mounted and their initial\n * events were delivered (RFC 0025 startup barrier).\n */\n activate(): Promise<void>;\n /** Renders one overlay; `undefined` when the instance has no dynamic overlay. */\n render(request: IFusedRenderRequest): Promise<IFusedOverlayFrame | undefined>;\n /** Delivers local pointer input; the guest reports a failing handler as `view2d/input-failed`. */\n input(instanceId: string, event: IFusedViewInput): void;\n release(instanceId: string): void;\n dispose(): Promise<void>;\n onDidInvalidate(listener: (change: IFusedInvalidateEvent) => void): () => void;\n onDidReportDiagnostic(listener: (diagnostic: RuntimeDiagnostic) => void): () => void;\n}\n\n/** Wire name of the simulation guest. */\nexport const fusedSimulationService = defineRpcService<IFusedSimulationService>('fused-simulation');\n\n/** Wire name of the 2D presentation guest. */\nexport const fusedDisplayService = defineRpcService<IFusedDisplayService>('fused-display');\n\n/** Wire name of the host package access both guests use. */\nexport const fusedHostPackageService =\n defineRpcService<IFusedHostPackageService>('fused-host-package');\n\n/** Wire name of the host resource access of the simulation guest. */\nexport const fusedHostResourceService =\n defineRpcService<IFusedHostResourceService>('fused-host-resource');\n\n/** Wire name of the model lane the simulation guest serves. */\nexport const fusedModelChannelService =\n defineRpcService<IFusedModelChannelService>('fused-model-channel');\n\n/** Wire name of the model sink the display guest serves. */\nexport const fusedModelSinkService = defineRpcService<IFusedModelSinkService>('fused-model-sink');\n\n/** Host opens and revokes instance generations; samples use the separate worklet port. */\nexport interface IFusedHostAudioService {\n open(instanceId: string): Promise<WidgetAudioMountInfo>;\n close(instanceId: string, session: string): void;\n}\n\nexport const fusedHostAudioService = defineRpcService<IFusedHostAudioService>('fused-host-audio');\n","/**\n * Package access of the sandbox guests (RFC 0020).\n *\n * The host owns the packages, so both guests reach the same typed service: `open` proves the lock\n * resolves and `read` hands over one declared file. The guest caches the bytes, because preparation\n * reads the same file for its digest and again for its content, and each reply transfers ownership.\n */\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { DeviceLock, DeviceRegistry } from '@mica-js/document/fused';\nimport { fusedHostPackageService } from './protocol';\nimport type { IFusedPackageFilesWire } from './protocol';\nimport { FusedBridgeError } from './wire';\n\n/** Wire key of one locked package. */\nexport function packageLockKey(lock: DeviceLock): string {\n return `${lock.id}@${lock.version}#${lock.integrity}`;\n}\n\n/** Registry implementation served by the host over `endpoint`. */\nexport function createHostPackageGateway(endpoint: RpcEndpoint): DeviceRegistry {\n const host = endpoint.getProxy(fusedHostPackageService);\n const opened = new Map<string, Promise<IFusedPackageFilesWire>>();\n const cache = new Map<string, Uint8Array>();\n const openLock = (lock: DeviceLock): Promise<IFusedPackageFilesWire> => {\n const key = packageLockKey(lock);\n let pending = opened.get(key);\n if (pending === undefined) {\n pending = host.open(lock);\n opened.set(key, pending);\n }\n return pending;\n };\n return {\n open(lock: DeviceLock) {\n return openLock(lock).then((files) => ({\n lock: files.lock,\n files: files.files,\n read: async (path: string) => {\n const key = `${packageLockKey(lock)}\\u0000${path}`;\n const cached = cache.get(key);\n if (cached !== undefined) return cached.slice();\n const bytes = await host.read(lock, path);\n if (!(bytes instanceof Uint8Array)) {\n throw new FusedBridgeError(\n 'package/not-found',\n `The host returned no bytes for ${lock.id}/${path}.`,\n );\n }\n // The reply transferred ownership, so the cache keeps the only copy of this realm.\n cache.set(key, bytes);\n return bytes.slice();\n },\n }));\n },\n };\n}\n","import { WidgetAudioEngine } from '@mica-js/widget/audio-host';\nimport type { RpcEndpoint, RpcProxy } from '@mica-js/core/rpc';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport type { IFusedAudioControls, IFusedAudioOptions } from '../audio';\nimport { fusedHostAudioService, type IFusedDisplayService } from '../protocol';\n\n/** Browser-owned audio engine; the guest only receives session tokens and a worklet port. */\nexport function connectFusedAudio(\n rpc: RpcEndpoint,\n display: Pick<RpcProxy<IFusedDisplayService>, 'attachAudio' | 'setAudioState'>,\n options: IFusedAudioOptions | undefined,\n report: (diagnostic: RuntimeDiagnostic) => void,\n): IFusedAudioControls & { clear(): void; dispose(): void } {\n const instances = new Set<string>();\n const reported = new Set<string>();\n let disposed = false;\n function bridgeFailure(operation: string, cause: unknown): void {\n if (disposed || reported.has(operation)) return;\n reported.add(operation);\n report({ code: 'audio/failed', message: `Audio bridge ${operation} failed: ${String(cause)}` });\n }\n const engine =\n options === undefined\n ? undefined\n : new WidgetAudioEngine({\n context: options.context,\n ...(options.destination === undefined ? {} : { destination: options.destination }),\n ...(options.limits === undefined ? {} : { limits: options.limits }),\n ...(options.getAudioWorklet === undefined\n ? {}\n : {\n loadWorklet: () => options.getAudioWorklet!(options.context),\n }),\n notify: {\n emitPort: (port) => {\n void display.attachAudio(port).catch((cause: unknown) => {\n port.close();\n bridgeFailure('attachAudio', cause);\n });\n },\n emitState: (state) => {\n void display.setAudioState(state).catch((cause: unknown) => {\n bridgeFailure('setAudioState', cause);\n });\n },\n },\n report: (code, instanceId, message) =>\n report({\n code: code.replace('widget/audio-', 'audio/'),\n message,\n ...(instanceId === '' ? {} : { instanceId }),\n }),\n });\n engine?.suspend();\n rpc.register(fusedHostAudioService, {\n async open(instanceId) {\n instances.add(instanceId);\n return (await engine?.open(instanceId)) ?? { state: 'unavailable' };\n },\n close(instanceId, session) {\n engine?.closeSession(instanceId, session);\n },\n });\n return {\n get state() {\n return engine?.state ?? 'unavailable';\n },\n suspend: () => engine?.suspend(),\n resume: () => engine?.resume(),\n setMuted: (muted) => engine?.setMuted(muted),\n setInstanceVolume: (id, volume) => engine?.setInstanceVolume(id, volume),\n clear() {\n for (const id of instances) engine?.close(id);\n instances.clear();\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n engine?.dispose();\n },\n };\n}\n","/**\n * Worker wiring of one fused workbench (RFC 0025).\n *\n * Both guests start from the generated `?sandbox-worker` classes: the host waits for the sandbox to\n * boot, transfers one end of three `MessageChannel`s and creates the typed RPC endpoints. From then\n * on nothing but `createRpc` traffic crosses the boundary.\n */\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint, RpcProxy } from '@mica-js/core/rpc';\nimport type { DeviceLock, DeviceRegistry, PackageFiles } from '@mica-js/document/fused';\nimport type { ProgramSources, ResourceResolver, RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport {\n fusedDisplayService,\n fusedHostPackageService,\n fusedHostResourceService,\n fusedSimulationService,\n} from '../protocol';\nimport type { IFusedDisplayService, IFusedSimulationService } from '../protocol';\nimport { packageLockKey } from '../packages';\nimport { transferProgramArtifact, transferPackageBytes, transferResourceBytes } from '../wire';\nimport type { IFusedWorkerFactories } from './types';\nimport type { IFusedAudioOptions } from '../audio';\nimport { connectFusedAudio } from './audio';\n\nexport interface IFusedConnectionOptions {\n readonly audio?: IFusedAudioOptions;\n readonly workers: IFusedWorkerFactories;\n /** Host package access both guests share. */\n readonly registry: DeviceRegistry;\n /** Element that hosts the two hidden sandbox iframes. */\n readonly container?: HTMLElement;\n readonly resolveResource?: ResourceResolver;\n readonly programs?: ProgramSources;\n readonly onDiagnostic?: (diagnostic: RuntimeDiagnostic) => void;\n}\n\n/** Two guests of one workbench plus the endpoints that reach them. */\nexport interface IFusedConnection {\n readonly audio: ReturnType<typeof connectFusedAudio>;\n readonly simulation: RpcProxy<IFusedSimulationService>;\n readonly display: RpcProxy<IFusedDisplayService>;\n dispose(): Promise<void>;\n}\n\n/** Boots both guests of one workbench and wires their RPC surfaces. */\nexport async function connectFusedWorkbench(\n options: IFusedConnectionOptions,\n): Promise<IFusedConnection> {\n const workerOptions = options.container === undefined ? {} : { container: options.container };\n const simulationWorker = options.workers.createSimulationWorker(workerOptions);\n const displayWorker = options.workers.createDisplayWorker(workerOptions);\n const subscriptions: Array<() => void> = [];\n let simulationRpc: RpcEndpoint | undefined;\n let displayRpc: RpcEndpoint | undefined;\n try {\n await Promise.all([simulationWorker.ready, displayWorker.ready]);\n const simulationChannel = new MessageChannel();\n const displayChannel = new MessageChannel();\n const modelChannel = new MessageChannel();\n // Ports arrive in the guest as `event.ports`: the RPC port first, the model lane second.\n simulationWorker.postMessage(null, [simulationChannel.port2, modelChannel.port1]);\n displayWorker.postMessage(null, [displayChannel.port2, modelChannel.port2]);\n simulationRpc = createRpc(simulationChannel.port1);\n displayRpc = createRpc(displayChannel.port1);\n registerHostServices(simulationRpc, options);\n registerHostServices(displayRpc, options);\n const simulation = simulationRpc.getProxy(fusedSimulationService);\n const display = displayRpc.getProxy(fusedDisplayService, {\n transfer: (member, args) => (member === 'attachAudio' ? [args[0] as MessagePort] : []),\n });\n const audio = connectFusedAudio(displayRpc, display, options.audio, (diagnostic) =>\n options.onDiagnostic?.(diagnostic),\n );\n subscriptions.push(\n simulation.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)),\n display.onDidReportDiagnostic((entry) => options.onDiagnostic?.(entry)),\n );\n const ownedSimulationRpc = simulationRpc;\n const ownedDisplayRpc = displayRpc;\n let disposal: Promise<void> | undefined;\n return {\n audio,\n simulation,\n display,\n dispose() {\n return (disposal ??= (async () => {\n audio.dispose();\n for (const stop of subscriptions.splice(0)) {\n try {\n stop();\n } catch {\n // The endpoint may already be closed.\n }\n }\n ownedSimulationRpc.dispose();\n ownedDisplayRpc.dispose();\n const results = await Promise.allSettled([\n simulationWorker.terminate('fused runtime disposed'),\n displayWorker.terminate('fused runtime disposed'),\n ]);\n const problems = results\n .filter((result): result is PromiseRejectedResult => result.status === 'rejected')\n .map((result) => result.reason as unknown);\n if (problems.length > 0) {\n throw new AggregateError(problems, 'Fused sandbox workers failed to terminate.');\n }\n })());\n },\n };\n } catch (cause) {\n for (const stop of subscriptions.splice(0)) {\n try {\n stop();\n } catch {\n // The endpoint may already be closed.\n }\n }\n simulationRpc?.dispose();\n displayRpc?.dispose();\n await Promise.allSettled([\n simulationWorker.terminate('fused runtime failed to start'),\n displayWorker.terminate('fused runtime failed to start'),\n ]);\n throw cause;\n }\n}\n\n/** Package and resource services every guest of one workbench pulls from. */\nfunction registerHostServices(endpoint: RpcEndpoint, options: IFusedConnectionOptions): void {\n const opened = new Map<string, Promise<PackageFiles>>();\n const openLock = (lock: DeviceLock): Promise<PackageFiles> => {\n const key = packageLockKey(lock);\n let pending = opened.get(key);\n if (pending === undefined) {\n pending = options.registry.open(lock);\n opened.set(key, pending);\n }\n return pending;\n };\n endpoint.register(\n fusedHostPackageService,\n {\n async open(lock: DeviceLock) {\n const files = await openLock(lock);\n return { lock: files.lock, files: files.files };\n },\n async read(lock: DeviceLock, path: string) {\n const files = await openLock(lock);\n const bytes = await files.read(path);\n if (!(bytes instanceof Uint8Array)) {\n throw new Error(`The registry returned no bytes for ${lock.id}/${path}.`);\n }\n // The transfer hands the buffer to the guest, so the editor keeps its own copy.\n return bytes.slice();\n },\n },\n { transfer: transferPackageBytes },\n );\n endpoint.register(\n fusedHostResourceService,\n {\n async readResource(request) {\n if (options.resolveResource === undefined) {\n throw new Error(\n `No resource resolver is configured for ${request.instanceId}/${request.property}.`,\n );\n }\n return (await options.resolveResource(request)).slice();\n },\n async resolveProgramProject(id, target) {\n if (!options.programs?.projects) throw new Error('No program project provider configured.');\n const artifact = await options.programs.projects.resolve(id, target);\n // The transfer hands the buffers to the guest, so the editor keeps its own copy; the\n // fingerprint identifies that copy and must survive the rebuild.\n const copy =\n artifact.kind === 'memory'\n ? { kind: 'memory' as const, format: artifact.format, data: artifact.data.slice() }\n : {\n kind: 'filesystem' as const,\n files: artifact.files.map((file) => ({ path: file.path, data: file.data.slice() })),\n };\n return artifact.fingerprint === undefined\n ? copy\n : { ...copy, fingerprint: artifact.fingerprint };\n },\n },\n {\n transfer: (member, value) =>\n member === 'resolveProgramProject'\n ? transferProgramArtifact(member, value)\n : transferResourceBytes(member, value),\n },\n );\n}\n","/**\n * Host-side 2D presentation surface (RFC 0022).\n *\n * The host reserves the overlay extent, numbers every request so a late frame can never overwrite a\n * newer one, and repaints instances whose presentation called `invalidate()`. Bitmaps of discarded\n * frames are closed instead of leaked.\n */\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { RpcProxy } from '@mica-js/core/rpc';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport type {\n FusedDisplayMode,\n IFusedDisplayLayout,\n IFusedDisplayService,\n IFusedInstancePresentation,\n IFusedInvalidateEvent,\n IFusedOverlayFrame,\n IFusedViewInput,\n} from '../protocol';\nimport type { IFusedDisplay, IFusedDisplayPrepareInput } from './types';\nimport { isImageBitmap, mapWireFailure, messageOf } from '../wire';\n\nexport interface IFusedDisplayHostOptions {\n readonly proxy: RpcProxy<IFusedDisplayService>;\n readonly onOverlay?: (frame: IFusedOverlayFrame) => void;\n readonly onDiagnostic?: (diagnostic: RuntimeDiagnostic) => void;\n /** Overlay extent of one instance; defaults to its bounds at one device pixel per local unit. */\n readonly measure?: (instance: IFusedInstancePresentation) => IFusedDisplayLayout;\n /** Repaints when a presentation asks for it; defaults to `true`. */\n readonly autoRender?: boolean;\n}\n\n/** Display surface plus the preparation the runtime drives. */\nexport interface IFusedDisplayHost {\n readonly display: IFusedDisplay;\n /** Replaces the presentation of one mode; drops every pending frame of the previous one. */\n prepare(\n input: IFusedDisplayPrepareInput,\n instances: readonly IFusedInstancePresentation[],\n ): Promise<void>;\n /** Runs the author `initialize` hooks once the models of the mode exist. */\n activate(): Promise<void>;\n dispose(): Promise<void>;\n}\n\nexport function createFusedDisplay(options: IFusedDisplayHostOptions): IFusedDisplayHost {\n const { proxy } = options;\n const invalidations = new Emitter<IFusedInvalidateEvent>();\n const generations = new Map<string, number>();\n const dirty = new Set<string>();\n /** Reported framework failures of the current preparation, so a flood reports once. */\n const reported = new Set<string>();\n let prepared: readonly IFusedInstancePresentation[] = [];\n let mode: FusedDisplayMode | undefined;\n /** Incremented by every preparation, so results of a replaced mode are dropped. */\n let epoch = 0;\n let pumping = false;\n let disposed = false;\n let disposal: Promise<void> | undefined;\n\n const stopInvalidate = proxy.onDidInvalidate((change) => {\n if (disposed) return;\n invalidations.fire(change);\n if (options.autoRender !== false) schedule(change.instanceId);\n });\n\n const display: IFusedDisplay = {\n get mode() {\n return mode;\n },\n get instances() {\n return prepared;\n },\n onDidInvalidate: invalidations.event,\n render,\n input,\n invalidate,\n dispose,\n };\n\n return { display, prepare, activate, dispose };\n\n async function prepare(\n input: IFusedDisplayPrepareInput,\n instances: readonly IFusedInstancePresentation[],\n ): Promise<void> {\n if (disposed) {\n throw new Error('The fused display is disposed.');\n }\n epoch += 1;\n generations.clear();\n dirty.clear();\n reported.clear();\n await mapWireFailure(() => proxy.prepare({ mode: input.mode, instances }));\n mode = input.mode;\n prepared = instances;\n }\n\n async function activate(): Promise<void> {\n if (disposed) return;\n await mapWireFailure(() => proxy.activate());\n }\n\n async function render(\n instanceId: string,\n layout?: IFusedDisplayLayout,\n ): Promise<IFusedOverlayFrame | undefined> {\n const instance = prepared.find((entry) => entry.instanceId === instanceId);\n if (instance === undefined || disposed) return undefined;\n const extent = layout ?? defaultLayout(instance);\n const generation = (generations.get(instanceId) ?? 0) + 1;\n generations.set(instanceId, generation);\n const attempt = epoch;\n const frame = await mapWireFailure(() => proxy.render({ instanceId, generation, ...extent }));\n if (frame === undefined) return undefined;\n if (disposed || attempt !== epoch || generation !== generations.get(instanceId)) {\n closeBitmap(frame.bitmap);\n return undefined;\n }\n options.onOverlay?.(frame);\n return frame;\n }\n\n function input(instanceId: string, event: IFusedViewInput): void {\n if (disposed) return;\n void proxy.input(instanceId, event).catch((cause: unknown) => {\n // The guest reports author callback failures itself as `view2d/input-failed`; a rejection here\n // means the call never reached the presentation, so it is reported once per instance.\n reportOnce(instanceId, 'runtime/presentation-failed', messageOf(cause));\n });\n }\n\n /**\n * Reports a framework failure of one instance once per distinct message.\n *\n * A dead guest fails every queued pointer event and every scheduled frame; without the dedupe the\n * same cause would flood the diagnostic sink.\n */\n function reportOnce(instanceId: string, code: string, message: string): void {\n const key = `${instanceId}\\u0000${code}\\u0000${message}`;\n if (reported.has(key)) return;\n reported.add(key);\n options.onDiagnostic?.({ code, message, instanceId });\n }\n\n function invalidate(instanceId?: string): void {\n if (disposed) return;\n if (instanceId !== undefined) {\n schedule(instanceId);\n return;\n }\n for (const instance of prepared) schedule(instance.instanceId);\n }\n\n function schedule(instanceId: string): void {\n if (!prepared.some((entry) => entry.instanceId === instanceId)) return;\n dirty.add(instanceId);\n if (pumping) return;\n pumping = true;\n void Promise.resolve().then(pump);\n }\n\n async function pump(): Promise<void> {\n while (!disposed) {\n const batch = [...dirty];\n if (batch.length === 0) {\n pumping = false;\n return;\n }\n dirty.clear();\n for (const instanceId of batch) {\n try {\n await render(instanceId);\n } catch (cause) {\n reportOnce(instanceId, 'runtime/presentation-failed', messageOf(cause));\n }\n }\n }\n pumping = false;\n }\n\n function defaultLayout(instance: IFusedInstancePresentation): IFusedDisplayLayout {\n const measured = options.measure?.(instance);\n if (measured !== undefined) return measured;\n const bounds = instance.geometry.bounds;\n return {\n width: Math.max(1, Math.round(bounds.width)),\n height: Math.max(1, Math.round(bounds.height)),\n scale: 1,\n };\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n disposed = true;\n disposal = (async () => {\n const problems: unknown[] = [];\n try {\n stopInvalidate();\n } catch (cause) {\n problems.push(cause);\n }\n try {\n await mapWireFailure(() => proxy.dispose());\n } catch (cause) {\n problems.push(cause);\n }\n invalidations.dispose();\n dirty.clear();\n prepared = [];\n mode = undefined;\n if (problems.length > 0) {\n throw new AggregateError(problems, 'The fused presentation failed to release its guests.');\n }\n })();\n return disposal;\n }\n}\n\nfunction closeBitmap(bitmap: ImageBitmap | undefined): void {\n if (bitmap !== undefined && isImageBitmap(bitmap)) bitmap.close();\n}\n","/**\n * Local fan-out of model events (RFC 0021).\n *\n * The host and the display guest both expose `Event<ModelEvent<T>>` outlets whose subscriptions are\n * lazy: the first listener of one instance and event subscribes on the wire, the last one\n * unsubscribes, and a released instance drops every local listener.\n */\nimport { Emitter, toDisposable } from '@mica-js/core/lifecycle';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { Value } from '@mica-js/document/fused';\nimport type { ModelEvent } from '@mica-js/sdk/fused';\n\n/** Wire subscriptions the router needs from its owner. */\nexport interface IFusedModelEventChannel {\n subscribe(instanceId: string, event: string): void;\n unsubscribe(instanceId: string, event: string): void;\n}\n\nexport interface IFusedModelEventRouter {\n /** Declared event outlet of one instance; only listeners create a wire subscription. */\n event(instanceId: string, event: string): Event<ModelEvent<Value>>;\n /** Delivers one event to the listeners active at this moment. */\n deliver(instanceId: string, event: string, payload: ModelEvent<Value>): void;\n /** Drops every listener of one instance. */\n release(instanceId: string): void;\n dispose(): void;\n /** Number of live wire subscriptions; used to keep the wire silent without listeners. */\n readonly activeSubscriptions: number;\n}\n\nexport function channelKey(instanceId: string, event: string): string {\n return `${instanceId}\\u0000${event}`;\n}\n\nexport function createModelEventRouter(channel: IFusedModelEventChannel): IFusedModelEventRouter {\n const entries = new Map<string, { emitter: Emitter<ModelEvent<Value>>; listeners: number }>();\n\n const event = (instanceId: string, name: string): Event<ModelEvent<Value>> => {\n const key = channelKey(instanceId, name);\n return (listener) => {\n let entry = entries.get(key);\n if (entry === undefined) {\n entry = { emitter: new Emitter<ModelEvent<Value>>(), listeners: 0 };\n entries.set(key, entry);\n }\n const current = entry;\n current.listeners += 1;\n if (current.listeners === 1) channel.subscribe(instanceId, name);\n const subscription = current.emitter.event(listener);\n return toDisposable(() => {\n subscription.dispose();\n current.listeners -= 1;\n if (current.listeners > 0) return;\n entries.delete(key);\n current.emitter.dispose();\n channel.unsubscribe(instanceId, name);\n });\n };\n };\n\n const drop = (key: string, instanceId: string, name: string): void => {\n const entry = entries.get(key);\n if (entry === undefined) return;\n entries.delete(key);\n entry.emitter.dispose();\n channel.unsubscribe(instanceId, name);\n };\n\n return {\n event,\n deliver(instanceId, name, payload) {\n entries.get(channelKey(instanceId, name))?.emitter.fire(payload);\n },\n release(instanceId) {\n const prefix = `${instanceId}\\u0000`;\n for (const key of [...entries.keys()]) {\n if (!key.startsWith(prefix)) continue;\n drop(key, instanceId, key.slice(prefix.length));\n }\n },\n dispose() {\n for (const key of [...entries.keys()]) {\n const separator = key.indexOf('\\u0000');\n drop(key, key.slice(0, separator), key.slice(separator + 1));\n }\n },\n get activeSubscriptions() {\n return entries.size;\n },\n };\n}\n","/**\n * Host-side model clients of the fused runtime (RFC 0021).\n *\n * The editor calls a model through the simulation worker, never in its own thread. Event outlets are\n * lazy: one wire listener serves every local subscription and is released with the last of them.\n */\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { RpcProxy } from '@mica-js/core/rpc';\nimport type { Value } from '@mica-js/document/fused';\nimport type { ModelEvent } from '@mica-js/sdk/fused';\nimport { createModelEventRouter } from '../model-events';\nimport type { IFusedModelEventRouter } from '../model-events';\nimport type {\n IFusedInstancePresentation,\n IFusedModelClient,\n FusedModelMethods,\n IFusedSimulationService,\n} from '../protocol';\nimport { FusedBridgeError, mapWireFailure } from '../wire';\n\n/** Model clients of one runtime, keyed by the instance they belong to. */\nexport interface IFusedHostModelRouter {\n client(instance: IFusedInstancePresentation): IFusedModelClient;\n release(instanceId: string): void;\n dispose(): void;\n}\n\nexport function createHostModelRouter(\n proxy: RpcProxy<IFusedSimulationService>,\n): IFusedHostModelRouter {\n let router: IFusedModelEventRouter | undefined;\n let subscriptions = 0;\n let stop: (() => void) | undefined;\n router = createModelEventRouter({\n subscribe() {\n subscriptions += 1;\n if (subscriptions > 1 || stop !== undefined) return;\n stop = proxy.onDidModelEvent((event) => {\n router?.deliver(event.instanceId, event.event, event.payload);\n });\n },\n unsubscribe() {\n subscriptions = Math.max(0, subscriptions - 1);\n if (subscriptions > 0) return;\n stop?.();\n stop = undefined;\n },\n });\n\n const active = (): IFusedModelEventRouter => {\n if (router === undefined) {\n throw new Error('The fused model router is disposed.');\n }\n return router;\n };\n\n const invoke = (instanceId: string, method: string, params: Value): Promise<Value> => {\n if (router === undefined) {\n return Promise.reject(\n new FusedBridgeError(\n 'model/disconnected',\n 'The model client is disconnected from any live model.',\n { instanceId },\n ),\n );\n }\n return mapWireFailure(() => proxy.call(instanceId, method, params));\n };\n return {\n client(instance) {\n const declared = new Set(instance.methods);\n const methods = new Proxy(Object.create(null) as Record<string, unknown>, {\n get(_target, name) {\n if (typeof name !== 'string' || !declared.has(name)) return undefined;\n return (params: Value) => invoke(instance.instanceId, name, params);\n },\n has(_target, name) {\n return typeof name === 'string' && declared.has(name);\n },\n }) as FusedModelMethods;\n const events: Record<string, Event<ModelEvent<Value>>> = {};\n for (const name of instance.events) {\n events[name] = active().event(instance.instanceId, name);\n }\n return { methods, events };\n },\n release(instanceId) {\n router?.release(instanceId);\n },\n dispose() {\n stop?.();\n stop = undefined;\n router?.dispose();\n router = undefined;\n },\n };\n}\n","/**\n * Fused editor runtime bridge of one workbench (RFC 0025).\n *\n * One simulation worker runs the document, the packages and the models; one presentation worker runs\n * the declared 2D view modules. The editor schedules both and never imports model or author code.\n *\n * Every asynchronous transition is numbered: a preparation, reset or disposal that was superseded\n * never applies its result, and a frame produced for a replaced presentation is closed, not shown.\n */\nimport { timePs } from '@mica-js/core';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport type {\n IFusedInstancePresentation,\n IFusedModelClient,\n IFusedOverlayFrame,\n IFusedSessionState,\n} from '../protocol';\nimport { connectFusedWorkbench } from './connection';\nimport { createFusedDisplay } from './display';\nimport { createHostModelRouter } from './model';\nimport type { IFusedDisplayPrepareInput, IFusedRuntime, IFusedRuntimeOptions } from './types';\nimport type { IFusedWorkerFactories } from './types';\nimport { FusedBridgeError, mapWireFailure } from '../wire';\n\nconst IDLE: IFusedSessionState = Object.freeze({ status: 'idle', simTime: timePs(0) });\n\n/** Creates the runtime bridge of one workbench from a document, a registry and a fixed step. */\nexport async function createFusedRuntime(options: IFusedRuntimeOptions): Promise<IFusedRuntime> {\n const workers: IFusedWorkerFactories =\n options.workers ?? (await import('../workers')).fusedWorkerFactories;\n const diagnostics = new Emitter<RuntimeDiagnostic>();\n const overlays = new Emitter<IFusedOverlayFrame>();\n const states = new Emitter<IFusedSessionState>();\n const report = (entry: RuntimeDiagnostic): void => {\n diagnostics.fire(entry);\n options.onDiagnostic?.(entry);\n };\n const connection = await connectFusedWorkbench({\n workers,\n registry: options.registry,\n ...(options.audio === undefined ? {} : { audio: options.audio }),\n ...(options.container === undefined ? {} : { container: options.container }),\n ...(options.resolveResource === undefined ? {} : { resolveResource: options.resolveResource }),\n ...(options.programs === undefined ? {} : { programs: options.programs }),\n onDiagnostic: report,\n });\n const models = createHostModelRouter(connection.simulation);\n const displayHost = createFusedDisplay({\n proxy: connection.display,\n onDiagnostic: report,\n onOverlay: (frame) => {\n overlays.fire(frame);\n options.onOverlay?.(frame);\n },\n ...(options.measure === undefined ? {} : { measure: options.measure }),\n });\n\n let state: IFusedSessionState = IDLE;\n let prepared: readonly IFusedInstancePresentation[] = [];\n let mode: 'edit' | 'run' | undefined;\n let preparation = 0;\n let closed = false;\n let disposal: Promise<void> | undefined;\n const clients = new Map<string, IFusedModelClient>();\n\n const stopState = connection.simulation.onDidChangeState((next) => setState(next));\n /**\n * 宿主能主动报告产物变化时按通知作废缓存;没有这条通道时退回「每次进入运行前重新解析」,\n * 否则代码工程重新编译并发布的固件进不了下一次运行。\n */\n const stopProgramChanges = options.programs?.projects?.onDidChange?.((projectId, fingerprint) => {\n void connection.simulation.invalidatePrograms(projectId, fingerprint).catch(() => undefined);\n });\n\n const runtime: IFusedRuntime = {\n audio: connection.audio,\n getState: () => state,\n onDidChangeState: states.event,\n onDidReportDiagnostic: diagnostics.event,\n onDidRenderOverlay: overlays.event,\n getModel,\n display: displayHost.display,\n prepareDisplay,\n warmup,\n resume,\n pause,\n step,\n reset,\n dispose,\n };\n try {\n await prepareDisplay({ mode: options.mode ?? 'edit' });\n } catch (cause) {\n await dispose().catch(() => undefined);\n throw cause;\n }\n return runtime;\n\n function setState(next: IFusedSessionState): void {\n if (next.status === 'running') connection.audio.resume();\n else connection.audio.suspend();\n if (next.status === state.status && next.simTime === state.simTime) return;\n state = next;\n states.fire(next);\n }\n\n function assertOpen(): void {\n if (closed) {\n throw new FusedBridgeError('runtime/unavailable-state', 'The fused runtime is disposed.');\n }\n }\n\n function assertRun(operation: string): void {\n assertOpen();\n if (mode !== 'run') {\n throw new FusedBridgeError(\n 'runtime/unavailable-state',\n `${operation} requires a run session; prepare the run mode first.`,\n );\n }\n }\n\n function getModel(instanceId: string): IFusedModelClient {\n if (closed || mode !== 'run') {\n throw new FusedBridgeError(\n 'model/disconnected',\n 'No model is mounted: the fused runtime is not in run mode.',\n { instanceId },\n );\n }\n const instance = prepared.find((entry) => entry.instanceId === instanceId);\n if (instance === undefined) {\n throw new FusedBridgeError(\n 'model/unknown-instance',\n `No live model for instance \"${instanceId}\".`,\n { instanceId },\n );\n }\n let client = clients.get(instanceId);\n if (client === undefined) {\n client = models.client(instance);\n clients.set(instanceId, client);\n }\n return client;\n }\n\n async function prepareDisplay(\n input: IFusedDisplayPrepareInput,\n ): Promise<readonly IFusedInstancePresentation[]> {\n assertOpen();\n const attempt = ++preparation;\n connection.audio.suspend();\n connection.audio.clear();\n const current = (): boolean => !closed && attempt === preparation;\n if (input.mode === 'run' && stopProgramChanges === undefined) {\n // 没有变更通知:进入运行前先作废缓存的程序产物,下一次解析才拿得到新固件。\n await mapWireFailure(() => connection.simulation.invalidatePrograms());\n }\n const described = await mapWireFailure(() =>\n connection.simulation.prepare({ document: options.document, mode: input.mode }),\n );\n if (!current()) return prepared;\n if (input.mode === 'edit') {\n // Edit mode mounts presentation only: the models are released before any view is created.\n await mapWireFailure(() => connection.simulation.dispose());\n if (!current()) return prepared;\n }\n // Factories run before the models exist, so their subscriptions observe the initial events.\n await displayHost.prepare({ mode: input.mode }, described.instances);\n if (!current()) return prepared;\n if (input.mode === 'run') {\n try {\n const loaded = await mapWireFailure(() =>\n connection.simulation.load({\n document: options.document,\n step: options.step,\n ...(options.simulationPacing === undefined\n ? {}\n : { simulationPacing: options.simulationPacing }),\n ...(options.batchExecution === undefined\n ? {}\n : { batchExecution: options.batchExecution }),\n }),\n );\n if (!current()) return prepared;\n setState(loaded);\n } catch (cause) {\n // The factories of a session that never mounted must not keep drawing a dead model lane.\n await displayHost.prepare({ mode: input.mode }, []).catch(() => undefined);\n throw cause;\n }\n }\n prepared = described.instances;\n mode = input.mode;\n clients.clear();\n // `initialize` runs after the models mounted and delivered their initial events.\n await displayHost.activate();\n if (!current()) return prepared;\n // Static views need an initial frame even when they never invalidate themselves.\n displayHost.display.invalidate();\n if (input.mode === 'run') {\n // A run session starts advancing once every presentation subscribed to its model.\n await mapWireFailure(() => connection.simulation.resume());\n }\n return prepared;\n }\n\n /**\n * Translates the boot path in the background, for a run the user has not started yet.\n *\n * Only meaningful in edit mode: a mounted run session is already translated. The guest releases\n * the throwaway session it builds, so nothing of it survives except the generated code.\n */\n async function warmup(): Promise<void> {\n assertOpen();\n if (mode !== 'edit') return;\n await mapWireFailure(() =>\n connection.simulation.warmup({\n document: options.document,\n step: options.step,\n ...(options.batchExecution === undefined ? {} : { batchExecution: options.batchExecution }),\n }),\n );\n }\n\n async function resume(): Promise<void> {\n assertRun('resume');\n await mapWireFailure(() => connection.simulation.resume());\n }\n\n async function pause(): Promise<void> {\n if (closed || mode !== 'run') return;\n await mapWireFailure(() => connection.simulation.pause());\n }\n\n async function step(): Promise<void> {\n assertRun('step');\n const next = await mapWireFailure(() => connection.simulation.step());\n setState(next);\n }\n\n async function reset(): Promise<void> {\n assertRun('reset');\n connection.audio.suspend();\n connection.audio.clear();\n const attempt = ++preparation;\n const current = (): boolean => !closed && attempt === preparation;\n const instances = prepared;\n // The rebuilt presentation subscribes first; the replacement models then deliver initial events.\n await displayHost.prepare({ mode: 'run' }, instances);\n if (!current()) return;\n clients.clear();\n await mapWireFailure(() => connection.simulation.reset());\n if (!current()) return;\n await displayHost.activate();\n if (!current()) return;\n displayHost.display.invalidate();\n await mapWireFailure(() => connection.simulation.resume());\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n closed = true;\n connection.audio.dispose();\n disposal = (async () => {\n const problems: unknown[] = [];\n // Presentation first: input stops and views release before the models go away.\n try {\n await displayHost.dispose();\n } catch (cause) {\n problems.push(cause);\n }\n try {\n await mapWireFailure(() => connection.simulation.dispose());\n } catch (cause) {\n problems.push(cause);\n }\n try {\n stopState();\n } catch (cause) {\n problems.push(cause);\n }\n try {\n stopProgramChanges?.();\n } catch (cause) {\n problems.push(cause);\n }\n models.dispose();\n try {\n await connection.dispose();\n } catch (cause) {\n problems.push(cause);\n }\n states.dispose();\n diagnostics.dispose();\n overlays.dispose();\n if (problems.length > 0) {\n throw new AggregateError(problems, 'The fused runtime failed to release every resource.');\n }\n })();\n return disposal;\n }\n}\n","/** Small shared helpers of the fused sandbox bridge. */\nimport type { DevicePropertyDescriptor } from '@mica-js/document/fused';\nimport { createProgramFiles, readonlyBytes } from '@mica-js/sdk/fused';\nimport type {\n FusedPresentationProps,\n FusedPresentationValue,\n FusedResolvedPresentationProps,\n IFusedFirmwareSegment,\n IFusedFirmwareSnapshot,\n} from './protocol';\nimport { FusedBridgeError } from './wire';\n\n/**\n * Resolved property snapshot handed to one presentation.\n *\n * Every declared property must appear in `resolved` (the simulation worker resolves the manifest\n * defaults and document overrides through the SDK, exactly like the model snapshot does). Byte and\n * firmware values are copied into independent arrays, because the snapshot crosses an RPC boundary\n * and is transferred to the presentation worker afterwards.\n *\n * @throws {FusedBridgeError} `runtime/presentation-failed` naming the property and its declared\n * type whenever a value cannot be projected. A presentation never receives a partial snapshot.\n */\nexport function presentationProps(\n resolved: Readonly<Record<string, unknown>>,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n): FusedPresentationProps {\n const props: Record<string, FusedPresentationValue> = {};\n for (const [name, descriptor] of Object.entries(descriptors)) {\n if (!Object.hasOwn(resolved, name)) {\n throw unpresentable(name, descriptor.type, 'has no resolved value');\n }\n const value = resolved[name];\n if (value === undefined) {\n throw unpresentable(name, descriptor.type, 'resolved to undefined');\n }\n switch (descriptor.type) {\n case 'string':\n case 'color':\n case 'enum':\n if (typeof value === 'string') {\n props[name] = value;\n continue;\n }\n break;\n case 'integer':\n case 'number':\n if (typeof value === 'number') {\n props[name] = value;\n continue;\n }\n break;\n case 'boolean':\n if (typeof value === 'boolean') {\n props[name] = value;\n continue;\n }\n break;\n case 'image':\n case 'binary':\n if (value === null) {\n props[name] = null;\n continue;\n }\n props[name] = copyBytes(name, descriptor.type, value);\n continue;\n case 'firmware':\n if (value === null) {\n props[name] = null;\n continue;\n }\n props[name] = firmwareSnapshot(name, value);\n continue;\n case 'program':\n if (value === null && descriptor.nullable === true) {\n props[name] = null;\n continue;\n }\n if (descriptor.loader === 'memory') props[name] = firmwareSnapshot(name, value);\n else {\n const files = value as { readonly paths?: unknown; readonly read?: unknown };\n if (!files || !Array.isArray(files.paths) || typeof files.read !== 'function')\n throw unpresentable(name, 'program', 'is not a file snapshot');\n props[name] = Object.freeze({\n kind: 'filesystem',\n files: Object.freeze(\n files.paths.map((path: string) =>\n Object.freeze({\n path,\n data: copyBytes(name, 'program', (files.read as (path: string) => unknown)(path)),\n }),\n ),\n ),\n });\n }\n continue;\n default:\n break;\n }\n\n if (value === null && descriptor.nullable === true) {\n props[name] = null;\n continue;\n }\n throw unpresentable(name, descriptor.type, `resolved to ${describeValue(value)}`);\n }\n return Object.freeze(props);\n}\n\nexport function reconstructPresentationProps(\n props: FusedPresentationProps,\n): FusedResolvedPresentationProps {\n return Object.freeze(\n Object.fromEntries(\n Object.entries(props).map(([name, value]) => {\n if (value !== null && typeof value === 'object' && !(value instanceof Uint8Array)) {\n if (value.kind === 'filesystem') return [name, createProgramFiles(value.files)];\n return [\n name,\n Object.freeze({\n segments: Object.freeze(\n value.segments.map((segment) =>\n Object.freeze({\n addressSpace: segment.addressSpace,\n address: segment.address,\n data: readonlyBytes(segment.bytes),\n }),\n ),\n ),\n }),\n ];\n }\n return [name, value];\n }),\n ),\n );\n}\n\n/** Copies one read-only byte snapshot; the SDK hands `ReadonlyBytes`, not raw arrays. */\nfunction copyBytes(name: string, type: string, value: unknown): Uint8Array {\n if (value instanceof Uint8Array) return value.slice();\n const candidate = value as { readonly slice?: unknown } | null;\n if (\n candidate !== null &&\n typeof candidate === 'object' &&\n typeof candidate.slice === 'function'\n ) {\n const copy = (candidate.slice as () => unknown).call(candidate);\n if (copy instanceof Uint8Array) return copy;\n }\n throw unpresentable(name, type, 'is not a byte snapshot');\n}\n\n/** Projects one loaded firmware image (RFC 0026) into a transferable snapshot. */\nfunction firmwareSnapshot(name: string, value: unknown): IFusedFirmwareSnapshot {\n const segments = (value as { readonly segments?: unknown } | null)?.segments;\n if (!Array.isArray(segments)) {\n throw unpresentable(name, 'firmware', 'is not a firmware image');\n }\n const projected: IFusedFirmwareSegment[] = [];\n for (const segment of segments) {\n const candidate = segment as {\n readonly addressSpace?: unknown;\n readonly address?: unknown;\n readonly data?: unknown;\n };\n if (typeof candidate.addressSpace !== 'string' || typeof candidate.address !== 'number') {\n throw unpresentable(name, 'firmware', 'has a segment without an address space or address');\n }\n projected.push({\n addressSpace: candidate.addressSpace,\n address: candidate.address,\n bytes: copyBytes(name, 'firmware', candidate.data),\n });\n }\n return Object.freeze({ kind: 'firmware', segments: Object.freeze(projected) });\n}\n\nfunction unpresentable(name: string, type: string, reason: string): FusedBridgeError {\n return new FusedBridgeError(\n 'runtime/presentation-failed',\n `Property \"${name}\" (${type}) ${reason}; the presentation cannot receive a partial snapshot.`,\n );\n}\n\nfunction describeValue(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'an array';\n return `a value of type ${typeof value}`;\n}\n\n/** Whether a callback returned a promise instead of finishing synchronously. */\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { readonly then?: unknown }).then === 'function'\n );\n}\n\n/**\n * Evaluates one verified package module inside the guest.\n *\n * The bytes were verified against the package lock before this runs; a blob URL keeps the module\n * out of the host document and is revoked as soon as the namespace settles.\n */\nexport function importCode(code: string): Promise<unknown> {\n const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));\n return import(/* @vite-ignore */ url).finally(() => URL.revokeObjectURL(url));\n}\n\n/** Copies bytes into a plain `ArrayBuffer`, as `Blob` and transfer lists require. */\nexport function byteBuffer(bytes: Uint8Array): ArrayBuffer {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy.buffer;\n}\n\n/** Decodes package bytes as UTF-8 module source, tolerating a leading byte order mark. */\nexport function decodeSource(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes).replace(/^\\uFEFF/, '');\n}\n","/**\n * Model lane between the simulation guest and the display guest (RFC 0025).\n *\n * The host transfers one end of a `MessageChannel` to each guest, so a display input handler calls\n * its model directly instead of asking the editor to relay the call. The simulation guest serves\n * {@link fusedModelChannelService} and pushes events to the display sink only while the display is\n * subscribed to that instance and event.\n */\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { Value } from '@mica-js/document/fused';\nimport { fusedModelChannelService, fusedModelSinkService } from '../protocol';\nimport { channelKey } from '../model-events';\nimport type { IFusedModelEventWire } from '../protocol';\n\n/** Guest-side capabilities the display lane reaches through this port. */\nexport interface IFusedModelChannelHandlers {\n /** Invokes one declared model method; failures are already encoded for the wire. */\n readonly call: (instanceId: string, method: string, params: Value) => Promise<Value>;\n}\n\nexport interface IFusedSimulationModelChannel {\n /** Delivers one model event to the display guest when it subscribed to it. */\n deliver(event: IFusedModelEventWire): void;\n /** Drops every display subscription, e.g. when the session was replaced. */\n reset(): void;\n dispose(): void;\n}\n\n/** Starts the simulation end of the model lane over `port`. */\nexport function startSimulationModelChannel(\n port: MessagePort,\n handlers: IFusedModelChannelHandlers,\n createEndpoint: (port: MessagePort) => RpcEndpoint = createRpc,\n): IFusedSimulationModelChannel {\n const endpoint = createEndpoint(port);\n const sink = endpoint.getProxy(fusedModelSinkService);\n const subscriptions = new Set<string>();\n endpoint.register(fusedModelChannelService, {\n call: handlers.call,\n subscribe(instanceId, event) {\n subscriptions.add(channelKey(instanceId, event));\n },\n unsubscribe(instanceId, event) {\n subscriptions.delete(channelKey(instanceId, event));\n },\n settle: () => undefined,\n });\n return {\n deliver(event) {\n if (!subscriptions.has(channelKey(event.instanceId, event.event))) return;\n void sink.deliver(event).catch(() => undefined);\n },\n reset() {\n subscriptions.clear();\n },\n dispose() {\n subscriptions.clear();\n endpoint.dispose();\n },\n };\n}\n","/**\n * Simulation guest of the fused editor runtime (RFC 0025).\n *\n * The guest owns the production headless runtime: the document snapshot, the verified package bytes,\n * the models and the electrical solve. The editor keeps no model code on its own thread; it reaches\n * this guest through typed RPC and receives model events, state changes and diagnostics as events.\n *\n * Package bytes, host resources and firmware artifacts are pulled from host services registered on\n * the same RPC endpoint, so verification, preparation and model execution all happen here.\n */\nimport { timePs, toTimePs } from '@mica-js/core';\nimport type { TimePs } from '@mica-js/core';\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport type { Disposable } from '@mica-js/core/lifecycle';\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport { parseFusedDocument, parseGeometry2D, parseStrictJson } from '@mica-js/document/fused';\nimport type {\n DeviceLock,\n DevicePropertyDescriptor,\n DeviceRegistry,\n FusedDocument,\n FusedInstance,\n PackageFiles,\n Value,\n} from '@mica-js/document/fused';\nimport {\n createHeadlessRuntime,\n FusedPreparationError,\n openDevicePackage,\n PreparationError,\n resolveInstanceProperties,\n} from '@mica-js/sdk/fused';\nimport type {\n ProgramSources,\n ProgramArtifact,\n ProgramFile,\n HeadlessRuntime,\n ResourceResolver,\n RuntimeDiagnostic,\n RuntimeModelEvent,\n VerifiedPackage,\n} from '@mica-js/sdk/fused';\nimport { fusedHostResourceService, fusedSimulationService } from '../protocol';\nimport type {\n FusedSimulationPacing,\n IFusedInstancePresentation,\n IFusedLoadRequest,\n IFusedModelEventWire,\n IFusedPrepareRequest,\n IFusedPrepareResult,\n IFusedSessionState,\n IFusedWarmupRequest,\n} from '../protocol';\nimport { decodeSource, importCode, presentationProps } from '../values';\nimport { FusedBridgeError, messageOf, toWireFailure, transferPresentationBytes } from '../wire';\nimport { createHostPackageGateway, packageLockKey } from '../packages';\nimport { startSimulationModelChannel } from './model-channel';\nimport type { IFusedSimulationModelChannel } from './model-channel';\n\n/** Replaceable guest dependencies, so the runtime can be exercised outside a browser worker. */\nexport interface IFusedSimulationGuestOptions {\n /** Creates the endpoint over the startup port; tests inject a fake. */\n readonly createEndpoint?: (port: MessagePort) => RpcEndpoint;\n /**\n * Startup ports after the RPC port. The first one is the model lane (RFC 0025), the display guest\n * holds the other end of the same channel.\n */\n readonly ports?: readonly MessagePort[];\n /** Evaluates one verified package module; defaults to a blob URL plus dynamic `import()`. */\n readonly importModule?: (code: string) => Promise<unknown>;\n}\n\n/** Guest runtime plus the RPC endpoint that serves it. */\nexport interface IFusedSimulationGuest {\n readonly rpc: RpcEndpoint;\n dispose(): Promise<void>;\n}\n\nconst IDLE: IFusedSessionState = Object.freeze({ status: 'idle', simTime: timePs(0) });\nconst PS_PER_MS = toTimePs(1, 'ms');\nconst SLICE_MS = 4;\nconst MAX_CATCH_UP_MS = 50;\nconst MAX_STEPS_PER_SLICE = 2_048;\n/**\n * 首个固定步要把整段启动路径翻译成 JS,可能要数秒。长步长的首步被切成这么多份,\n * 每份之间回到事件循环:宿主可以在启动期间停止,界面也能报告进度。\n */\nconst BOOT_SLICES = 16;\n/** 低于这个步长时首步覆盖的代码太少,切片只增加开销。 */\nconst BOOT_SLICE_MIN_STEP = toTimePs(1, 'ms');\n/** 预热同样切片,好让真实的准备与装载插进来并立即取消它。 */\nconst WARMUP_SLICES = 8;\n\ninterface ContinuousRun {\n wallStartMs: number;\n simStartPs: TimePs;\n timer: ReturnType<typeof setTimeout> | undefined;\n /** Resolves the boot yield in flight, so a stop during boot does not wait for the timer. */\n waiting: (() => void) | undefined;\n}\n\ninterface Session {\n readonly runtime: HeadlessRuntime;\n readonly subscriptions: Disposable[];\n readonly step: TimePs;\n readonly pacing: FusedSimulationPacing;\n run: ContinuousRun | undefined;\n}\n\n/** Starts the simulation guest on the startup port of a sandbox worker. */\nexport function startFusedSimulationGuest(\n port: MessagePort,\n options: IFusedSimulationGuestOptions = {},\n): IFusedSimulationGuest {\n const endpoint = (options.createEndpoint ?? createRpc)(port);\n const importModule = options.importModule ?? importCode;\n const packages = createHostPackageGateway(endpoint);\n /** 已校验的器件包与已求值的模块都按发布身份缓存:同一 realm 里的下一次 load 直接复用。 */\n const openedPackages = new Map<string, Promise<VerifiedPackage>>();\n const openedModules = new Map<string, Promise<unknown>>();\n\n /**\n * 校验并缓存一个发布。\n *\n * 校验结论只取决于宿主交来的字节,而宿主按发布身份缓存字节,所以同一 lock 在\n * 一个 realm 里只需要校验一次。\n */\n function openVerifiedPackage(lock: DeviceLock): Promise<VerifiedPackage> {\n const key = packageLockKey(lock);\n const cached = openedPackages.get(key);\n if (cached !== undefined) return cached;\n const pending = openDevicePackage(packages, lock);\n openedPackages.set(key, pending);\n void pending.catch(() => {\n if (openedPackages.get(key) === pending) openedPackages.delete(key);\n });\n return pending;\n }\n\n /** 校验接口原样交给运行时,避免它把同一份发布再校验一遍。 */\n const verifiedRegistry: DeviceRegistry = {\n open: (lock) => openVerifiedPackage(lock).then((entry) => entry.source),\n };\n const resources = createResourceGateway(endpoint);\n const diagnostics = new Emitter<RuntimeDiagnostic>();\n const states = new Emitter<IFusedSessionState>();\n const events = new Emitter<IFusedModelEventWire>();\n const modelPort = options.ports?.[0];\n const modelChannel: IFusedSimulationModelChannel | undefined =\n modelPort === undefined\n ? undefined\n : startSimulationModelChannel(modelPort, {\n call: (instanceId, method, params) => callModel(instanceId, method, params),\n });\n\n let state: IFusedSessionState = IDLE;\n let session: Session | undefined;\n /** Identity of the live session, so events of a discarded candidate never reach a listener. */\n let sessionToken: object | undefined;\n /** Incremented by every session transition, so late results of a replaced session are dropped. */\n let sequence = 0;\n /** 递增即取消正在进行的预热;真实的准备与装载都会取消它。 */\n let warmupGeneration = 0;\n let warmupPending: Promise<void> | undefined;\n let closing = false;\n let disposal: Promise<void> | undefined;\n\n endpoint.register(\n fusedSimulationService,\n {\n prepare,\n load,\n warmup,\n step,\n resume,\n pause,\n reset,\n dispose: releaseModels,\n invalidatePrograms: async (projectId, fingerprint) => {\n resources.invalidatePrograms(projectId, fingerprint);\n },\n call: (instanceId, method, params) => callModel(instanceId, method, params),\n getState: () => state,\n onDidChangeState(listener) {\n const subscription = states.event((value) => listener(value));\n return () => subscription.dispose();\n },\n onDidReportDiagnostic(listener) {\n const subscription = diagnostics.event((value) => listener(value));\n return () => subscription.dispose();\n },\n onDidModelEvent(listener) {\n const subscription = events.event((value) => listener(value));\n return () => subscription.dispose();\n },\n },\n // Presentation byte and firmware snapshots are handed over, never cloned.\n { transfer: transferPresentationBytes },\n );\n\n return {\n rpc: endpoint,\n dispose,\n };\n\n function report(entry: RuntimeDiagnostic): void {\n diagnostics.fire(entry);\n }\n\n function setState(next: IFusedSessionState): void {\n if (next.status === state.status && next.simTime === state.simTime) return;\n state = next;\n states.fire(next);\n }\n\n function assertOpen(): void {\n if (closing) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/unavailable-state',\n 'The fused simulation guest is disposed.',\n ),\n );\n }\n }\n\n function requireSession(operation: string): Session {\n assertOpen();\n if (session === undefined) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/unavailable-state',\n `${operation} requires mounted models; prepare a run session first.`,\n ),\n );\n }\n return session;\n }\n\n async function prepare(request: IFusedPrepareRequest): Promise<IFusedPrepareResult> {\n assertOpen();\n cancelWarmup();\n const document = parseFusedDocument(request.document);\n const problems: RuntimeDiagnostic[] = [];\n const instances: IFusedInstancePresentation[] = [];\n for (const [index, instance] of document.instances.entries()) {\n try {\n const described = await describeInstance(index, document, instance);\n if (described !== undefined) instances.push(described);\n } catch (cause) {\n // A presentation-only failure drops the view of that instance; the models of a run session\n // and every other presentation keep going (RFC 0025 `runtime/presentation-failed`).\n if (cause instanceof FusedBridgeError && cause.code === 'runtime/presentation-failed') {\n report({ code: cause.code, message: cause.message, instanceId: instance.id });\n continue;\n }\n problems.push({\n code: 'runtime/prepare-failed',\n message: `${instance.id}: ${messageOf(cause)}`,\n instanceId: instance.id,\n });\n }\n }\n for (const problem of problems) report(problem);\n if (problems.length > 0) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/prepare-failed',\n `${problems.length} instance(s) cannot join the 2D scene.`,\n ),\n );\n }\n return { instances };\n }\n\n async function describeInstance(\n index: number,\n document: FusedDocument,\n instance: FusedInstance,\n ): Promise<IFusedInstancePresentation | undefined> {\n const dependency = document.dependencies[instance.device];\n if (dependency === undefined) {\n throw new FusedBridgeError(\n 'document/unlocked-device',\n `Instance \"${instance.id}\" uses the unlocked device \"${instance.device}\".`,\n { instanceId: instance.id },\n );\n }\n const lock: DeviceLock = {\n id: instance.device,\n version: dependency.version,\n integrity: dependency.integrity,\n };\n const verified = await openVerifiedPackage(lock);\n const view = verified.manifest.view2d;\n if (view === undefined) {\n report({\n code: 'view2d/unsupported',\n message: `${instance.device} declares no 2D geometry; \"${instance.id}\" stays out of the 2D scene.`,\n instanceId: instance.id,\n });\n return undefined;\n }\n const pins = Object.keys(verified.manifest.pins ?? {});\n const geometryValue =\n typeof view.geometry === 'string'\n ? parseStrictJson(decodeSource(await verified.read(view.geometry)))\n : view.geometry;\n const descriptors = verified.manifest.properties ?? {};\n return {\n instanceId: instance.id,\n device: instance.device,\n lock,\n geometry: parseGeometry2D(geometryValue, pins),\n view: view.entry,\n props: presentationProps(\n await resolvePresentationProps(verified, descriptors, instance, index),\n descriptors,\n ),\n methods: Object.keys(verified.manifest.model?.methods ?? {}),\n events: Object.keys(verified.manifest.model?.events ?? {}),\n };\n }\n\n /**\n * Resolves the declared properties a presentation reads through the SDK, so the projection is the\n * same snapshot the model receives: manifest defaults, document overrides, package and host\n * resources, and a loaded firmware image.\n *\n * @throws {FusedBridgeError} `runtime/presentation-failed` naming every property that failed.\n */\n async function resolvePresentationProps(\n verified: VerifiedPackage,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n instance: FusedInstance,\n index: number,\n ): Promise<Readonly<Record<string, unknown>>> {\n try {\n const resolution = await resolveInstanceProperties({\n instanceId: instance.id,\n package: verified,\n descriptors,\n overrides: instance.properties ?? {},\n // The model IR adds nothing to `props`: an empty map keeps this resolution identical to the\n // one the runtime performs while it builds the board, so edit mode needs no model module.\n irProperties: new Map<string, never>(),\n pointer: ['instances', String(index), 'properties'],\n resolveResource: resources.resolveResource,\n programs: resources.programs,\n });\n return resolution.props;\n } catch (cause) {\n throw new FusedBridgeError(\n 'runtime/presentation-failed',\n `Presentation properties of \"${instance.id}\" cannot be resolved: ${describeProblems(\n cause,\n descriptors,\n )}`,\n { instanceId: instance.id },\n );\n }\n }\n\n /**\n * 在空闲时段先把启动路径翻译好。\n *\n * 首个固定步的翻译是廉价的生成代码 + 昂贵的 IR 处理,且生成的代码在同一 realm 内跨\n * JIT 注册复用;这里用一个临时会话把这段翻译做掉就释放,真实的运行随后只需重建模型。\n * 不发出状态与模型事件:预热不属于任何会话,用户看不到它。\n */\n async function warmup(request: IFusedWarmupRequest): Promise<void> {\n assertOpen();\n // 模型已经挂载(或正在装载)时没有可预热的对象。\n if (session !== undefined || warmupPending !== undefined) return await warmupPending;\n const step = request.step;\n if (!Number.isSafeInteger(step) || step <= 0) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/invalid-time',\n `\\`step\\` must be a positive integer number of picoseconds, received ${String(step)}.`,\n ),\n );\n }\n const generation = ++warmupGeneration;\n const current = (): boolean => !closing && generation === warmupGeneration;\n const task = runWarmup(request, step, current).finally(() => {\n if (warmupPending === task) warmupPending = undefined;\n });\n warmupPending = task;\n return await task;\n }\n\n async function runWarmup(\n request: IFusedWarmupRequest,\n step: TimePs,\n current: () => boolean,\n ): Promise<void> {\n let created: HeadlessRuntime | undefined;\n try {\n created = await createHeadlessRuntime({\n document: parseFusedDocument(request.document),\n registry: verifiedRegistry,\n loadModule,\n step,\n ...(request.batchExecution === undefined ? {} : { batchExecution: request.batchExecution }),\n resolveResource: resources.resolveResource,\n programs: resources.programs,\n // 预热没有任何界面:模型事件与诊断都不外发,真正的运行会重新报告一次。\n onModelEvent: () => {},\n });\n if (!current()) return;\n const slice = Math.floor(step / WARMUP_SLICES);\n for (let index = 1; index <= WARMUP_SLICES; index++) {\n if (!current()) return;\n const amount = index === WARMUP_SLICES ? step - slice * (WARMUP_SLICES - 1) : slice;\n await created.step(timePs(amount));\n // 回到宏任务:真实的准备与装载排在同一个消息队列里,能立刻取消这次预热。\n if (index < WARMUP_SLICES) await yieldToHost();\n }\n } catch {\n // 预热失败不是错误:用户点运行时还会完整地再走一遍,并在那时报告真实原因。\n } finally {\n if (created !== undefined) await created.dispose().catch(() => undefined);\n }\n }\n\n /** 取消在途的预热;切片之间会立即停下,已翻译的代码留在共享缓存里。 */\n function cancelWarmup(): void {\n warmupGeneration += 1;\n warmupPending = undefined;\n }\n\n async function load(request: IFusedLoadRequest): Promise<IFusedSessionState> {\n assertOpen();\n cancelWarmup();\n const step = request.step;\n if (!Number.isSafeInteger(step) || step <= 0) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/invalid-time',\n `\\`step\\` must be a positive integer number of picoseconds, received ${String(step)}.`,\n ),\n );\n }\n const pacing = request.simulationPacing;\n if (pacing !== undefined && pacing !== 'realtime' && pacing !== 'unlimited') {\n throw toWireFailure(\n new FusedBridgeError('runtime/invalid-pacing', 'Expected realtime or unlimited pacing.'),\n );\n }\n const document = parseFusedDocument(request.document);\n const attempt = ++sequence;\n const token = {};\n const superseded = (): boolean => closing || attempt !== sequence;\n /** Events of the factory phase are queued and delivered once the session is adopted. */\n const pending: RuntimeModelEvent[] = [];\n let created: HeadlessRuntime;\n try {\n created = await createHeadlessRuntime({\n document,\n registry: verifiedRegistry,\n loadModule,\n step,\n ...(request.batchExecution === undefined ? {} : { batchExecution: request.batchExecution }),\n resolveResource: resources.resolveResource,\n programs: resources.programs,\n onModelEvent: (event) => {\n if (sessionToken === token) publishModelEvent(event);\n else if (!superseded()) pending.push(event);\n },\n onDiagnostic: (entry) => {\n if (!superseded()) report(entry);\n },\n });\n } catch (cause) {\n if (cause instanceof FusedPreparationError) {\n for (const entry of cause.diagnostics) report(entry);\n }\n throw toWireFailure(cause);\n }\n if (superseded()) {\n await created.dispose().catch(() => undefined);\n return state;\n }\n const previous = session;\n session = undefined;\n sessionToken = undefined;\n if (previous !== undefined) {\n // The candidate session exists before the running one is released, so a failed load keeps it.\n await releaseSession(previous, false);\n }\n // The model lane keeps the display subscriptions of the presentation prepared before this load.\n sessionToken = token;\n const adopted: Session = {\n runtime: created,\n step,\n pacing: pacing ?? 'unlimited',\n run: undefined,\n subscriptions: [\n created.onDidChangeState((next) => {\n if (sessionToken !== token) return;\n // The SDK stays paused between explicit steps. A continuous run publishes once per slice.\n if (next.status === 'paused' && adopted.run !== undefined) return;\n stopRun(adopted);\n setState(next);\n }),\n created.onDidReportDiagnostic((entry) => {\n if (sessionToken === token) report(entry);\n }),\n ],\n };\n session = adopted;\n for (const event of pending.splice(0)) publishModelEvent(event);\n const initial = created.getState();\n setState({ status: initial.status, simTime: initial.simTime });\n return state;\n }\n\n async function step(): Promise<IFusedSessionState> {\n const target = requireSession('step');\n if (target.run !== undefined) {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/unavailable-state',\n 'step requires the paused state; pause the runtime first.',\n ),\n );\n }\n await mapGuestCall(() => target.runtime.step());\n return state;\n }\n\n async function resume(): Promise<void> {\n const target = requireSession('resume');\n if (target.run !== undefined) return;\n const current = target.runtime.getState();\n if (current.status === 'faulted') {\n throw toWireFailure(\n new FusedBridgeError(\n 'runtime/model-failed',\n 'resume is not allowed while the runtime is faulted; call reset first.',\n ),\n );\n }\n const run: ContinuousRun = {\n wallStartMs: performance.now(),\n simStartPs: current.simTime,\n timer: undefined,\n waiting: undefined,\n };\n target.run = run;\n // 首步覆盖整段启动代码的翻译,可能要几秒。这里只 ACK「已开始推进」:\n // 宿主据此结束准备界面,运行状态在首步落地后转为 running。\n setState({ status: 'starting', simTime: current.simTime });\n run.timer = setTimeout(() => {\n run.timer = undefined;\n void bootRun(target, run);\n }, 0);\n }\n\n /** 把首个固定步拆开执行,让启动期间的停止请求能在切片之间生效。 */\n async function bootRun(target: Session, run: ContinuousRun): Promise<void> {\n const slices = target.step >= BOOT_SLICE_MIN_STEP ? BOOT_SLICES : 1;\n const slice = Math.floor(target.step / slices);\n for (let index = 1; index <= slices; index++) {\n if (target.run !== run) return;\n const amount = index === slices ? target.step - slice * (slices - 1) : slice;\n try {\n await target.runtime.step(timePs(amount));\n } catch {\n // The SDK already reported the diagnostic. A faulted or over-range step ends this run.\n if (target.run === run) pause();\n return;\n }\n if (target.run !== run) return;\n if (index < slices) await yieldToSlice(run);\n }\n if (target.run !== run) return;\n // Start pacing after the first step so cold initialization does not build up lag.\n run.wallStartMs = performance.now();\n run.simStartPs = target.runtime.getState().simTime;\n setState({ status: 'running', simTime: run.simStartPs });\n scheduleSlice(target, run, run.wallStartMs);\n }\n\n /** Returns to the event loop; `stopRun` resolves the same promise so a stop is immediate. */\n function yieldToSlice(run: ContinuousRun): Promise<void> {\n return new Promise<void>((resolve) => {\n run.waiting = resolve;\n run.timer = setTimeout(() => {\n run.timer = undefined;\n run.waiting = undefined;\n resolve();\n }, 0);\n });\n }\n\n function scheduleSlice(target: Session, run: ContinuousRun, lastStartedAt: number): void {\n let delay = 0;\n if (target.pacing === 'realtime') {\n const nextPs = target.runtime.getState().simTime + target.step;\n const due = run.wallStartMs + (nextPs - run.simStartPs) / PS_PER_MS;\n // One browser timer can cover many fixed steps, including the default 10 µs steps.\n delay = Math.max(0, Math.ceil(Math.max(due, lastStartedAt + SLICE_MS) - performance.now()));\n }\n run.timer = setTimeout(() => {\n run.timer = undefined;\n void advanceSlice(target, run);\n }, delay);\n }\n\n async function advanceSlice(target: Session, run: ContinuousRun): Promise<void> {\n if (target.run !== run) return;\n const startedAt = performance.now();\n const from = target.runtime.getState().simTime;\n let limit = from + target.step;\n if (target.pacing === 'realtime') {\n let elapsedMs = startedAt - run.wallStartMs;\n const maxLagMs = Math.max(MAX_CATCH_UP_MS, target.step / PS_PER_MS);\n if (elapsedMs - (from - run.simStartPs) / PS_PER_MS > maxLagMs) {\n // Rebase after a long stall, such as a throttled browser tab.\n run.wallStartMs = startedAt - maxLagMs;\n run.simStartPs = from;\n elapsedMs = maxLagMs;\n }\n limit = run.simStartPs + Math.floor(elapsedMs * PS_PER_MS);\n }\n let simTime: number = from;\n try {\n for (let step = 0; step < MAX_STEPS_PER_SLICE && simTime + target.step <= limit; step++) {\n if (target.run !== run) return;\n await target.runtime.step();\n simTime += target.step;\n if (performance.now() - startedAt >= SLICE_MS) break;\n }\n } catch {\n // The SDK already reported the diagnostic. A time-range error also ends this run.\n if (target.run === run) pause();\n return;\n }\n if (target.run !== run) return;\n setState({ status: 'running', simTime: target.runtime.getState().simTime });\n scheduleSlice(target, run, startedAt);\n }\n\n function stopRun(target: Session): void {\n const run = target.run;\n target.run = undefined;\n if (run === undefined) return;\n clearTimeout(run.timer);\n run.timer = undefined;\n const waiting = run.waiting;\n run.waiting = undefined;\n waiting?.();\n }\n\n function pause(): void {\n if (session === undefined) return;\n stopRun(session);\n setState(session.runtime.getState());\n }\n\n async function reset(): Promise<void> {\n const target = requireSession('reset');\n pause();\n await mapGuestCall(() => target.runtime.reset());\n }\n\n async function callModel(instanceId: string, method: string, params: Value): Promise<Value> {\n const target = session;\n if (closing || target === undefined) {\n throw toWireFailure(\n new FusedBridgeError(\n 'model/disconnected',\n 'No model is mounted; prepare a run session first.',\n {\n instanceId,\n },\n ),\n );\n }\n try {\n const client = target.runtime.getModel(instanceId);\n const invoke = client.methods[method];\n if (invoke === undefined) {\n throw new FusedBridgeError(\n 'model/unknown-method',\n `The model of \"${instanceId}\" declares no method \"${method}\".`,\n { instanceId },\n );\n }\n return await invoke(params);\n } catch (cause) {\n throw toWireFailure(cause);\n }\n }\n\n async function releaseModels(): Promise<void> {\n assertOpen();\n await releaseCurrent(true);\n }\n\n async function releaseCurrent(strict: boolean): Promise<void> {\n const target = session;\n session = undefined;\n sessionToken = undefined;\n sequence += 1;\n modelChannel?.reset();\n setState(IDLE);\n if (target !== undefined) await releaseSession(target, strict);\n }\n\n async function releaseSession(target: Session, strict: boolean): Promise<void> {\n stopRun(target);\n for (const subscription of target.subscriptions.splice(0)) subscription.dispose();\n try {\n await target.runtime.dispose();\n } catch (cause) {\n report({\n code: 'runtime/model-failed',\n message: `Releasing the models failed: ${messageOf(cause)}`,\n });\n if (strict) throw toWireFailure(cause);\n }\n }\n\n function publishModelEvent(event: RuntimeModelEvent): void {\n const wire: IFusedModelEventWire = {\n instanceId: event.instanceId,\n event: event.event,\n payload: event.payload,\n };\n modelChannel?.deliver(wire);\n events.fire(wire);\n }\n\n /**\n * 求值一个器件包模块,并按发布身份缓存结果。\n *\n * 每个模块都是一次 blob + `import()`,V8 要重新解析整份源码;同一 realm 里重复求值\n * 同一个发布没有意义,模块命名空间按 URL 缓存本来就是 ESM 的常规行为。\n */\n async function loadModule(files: PackageFiles, path: string) {\n const key = `${packageLockKey(files.lock)}\\u0000${path}`;\n const cached = openedModules.get(key);\n if (cached !== undefined) return await cached;\n const pending = files.read(path).then((bytes) => importModule(decodeSource(bytes)));\n openedModules.set(key, pending);\n void pending.catch(() => {\n if (openedModules.get(key) === pending) openedModules.delete(key);\n });\n return await pending;\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n closing = true;\n disposal = (async () => {\n sequence += 1;\n modelChannel?.dispose();\n const target = session;\n session = undefined;\n sessionToken = undefined;\n const problems: unknown[] = [];\n if (target !== undefined) {\n try {\n await releaseSession(target, true);\n } catch (cause) {\n problems.push(cause);\n }\n }\n endpoint.dispose();\n diagnostics.dispose();\n states.dispose();\n events.dispose();\n if (problems.length > 0) throw problems[0];\n })();\n return disposal;\n }\n}\n\n/** One guest call whose rejection is rebuilt on the host. */\nasync function mapGuestCall<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (cause) {\n throw toWireFailure(cause);\n }\n}\n\n/** Returns to the event loop so a queued RPC request can run before the next slice. */\nfunction yieldToHost(): Promise<void> {\n return new Promise<void>((resolve) => {\n setTimeout(resolve, 0);\n });\n}\n\n/** Host resources the runtime pulls while it resolves instance properties. */\nfunction createResourceGateway(endpoint: RpcEndpoint): {\n readonly resolveResource: ResourceResolver;\n readonly programs: ProgramSources;\n /** 丢掉已缓存的程序产物;`projectId` 缺省表示全部,指纹相同则保留。 */\n invalidatePrograms(projectId?: string, fingerprint?: string): void;\n} {\n const host = endpoint.getProxy(fusedHostResourceService);\n // The presentation snapshot and the model snapshot resolve the same properties; the cache keeps\n // one host round trip per resource and one artifact fetch per project, and hands out copies.\n const resources = new Map<string, Uint8Array>();\n const programs = new Map<string, CachedProgram>();\n const copyFiles = (files: readonly ProgramFile[]) =>\n files.map((file) => ({ path: file.path, data: file.data.slice() }));\n const copyArtifact = (artifact: ProgramArtifact): ProgramArtifact =>\n artifact.kind === 'memory'\n ? { ...artifact, data: artifact.data.slice() }\n : { ...artifact, files: copyFiles(artifact.files) };\n return {\n programs: {\n projects: {\n resolve: async (id, target) => {\n const key = JSON.stringify([target.deviceId, target.property, target.loader, id]);\n const cached = programs.get(key);\n if (cached !== undefined) return copyArtifact(cached.artifact);\n const fetched = await host.resolveProgramProject(id, target);\n const artifact = copyArtifact(fetched);\n programs.set(key, { projectId: id, artifact });\n return copyArtifact(artifact);\n },\n },\n },\n resolveResource: async (request) => {\n const key = `${request.instanceId}\\u0000${request.property}`;\n const cached = resources.get(key);\n if (cached !== undefined) return cached.slice();\n const bytes = await host.readResource(request);\n resources.set(key, bytes.slice());\n return bytes;\n },\n invalidatePrograms(projectId, fingerprint) {\n for (const [key, cached] of programs) {\n if (projectId !== undefined && cached.projectId !== projectId) continue;\n if (fingerprint !== undefined && cached.artifact.fingerprint === fingerprint) continue;\n programs.delete(key);\n }\n },\n };\n}\n\n/** 一个已解析的程序产物;`projectId` 用于按工程作废缓存。 */\ninterface CachedProgram {\n readonly projectId: string;\n readonly artifact: ProgramArtifact;\n}\n\n/** Flattens preparation problems, naming the property and its declared type. */\nfunction describeProblems(\n cause: unknown,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n): string {\n if (cause instanceof PreparationError) {\n return cause.problems\n .map((problem) => {\n const property = propertyOfPointer(problem.pointer, descriptors);\n const where = problem.pointer === '' ? '' : ` at ${problem.pointer}`;\n return `${problem.code}${where}${property === undefined ? '' : ` (${property})`}: ${problem.message}`;\n })\n .join('; ');\n }\n return messageOf(cause);\n}\n\n/** Names one property and its declared type from a JSON Pointer into the instance properties. */\nfunction propertyOfPointer(\n pointer: string,\n descriptors: Readonly<Record<string, DevicePropertyDescriptor>>,\n): string | undefined {\n const segments = pointer.split('/');\n const at = segments.indexOf('properties');\n const name = at < 0 ? undefined : segments[at + 1];\n if (name === undefined) return undefined;\n const type = descriptors[name]?.type;\n return type === undefined ? `property \"${name}\"` : `property \"${name}\", type ${type}`;\n}\n","import type { Event } from '@mica-js/core/lifecycle';\nimport type {\n WidgetAudioApi,\n WidgetAudioStream,\n WidgetAudioState,\n WidgetAudioStreamStatus,\n} from '@mica-js/widget/audio-guest';\n\nexport type {\n WidgetAudioOptions as IFusedAudioOptions,\n WidgetAudioControls as IFusedAudioControls,\n} from '@mica-js/widget/audio-host';\nexport type {\n WidgetAudioState as FusedAudioState,\n WidgetAudioTone as IFusedAudioTone,\n WidgetAudioToneOptions as IFusedAudioToneOptions,\n WidgetAudioStreamOptions as IFusedAudioStreamOptions,\n} from '@mica-js/widget/audio-guest';\n\nexport interface IFusedAudioStream extends Omit<WidgetAudioStream, 'onDrain' | 'onStatus'> {\n readonly onDidDrain: Event<void>;\n readonly onDidChangeStatus: Event<WidgetAudioStreamStatus>;\n}\n\n/** Audio handles belong to one instance generation, including while its body is hidden. */\nexport interface IFusedAudio extends Omit<WidgetAudioApi, 'onStateChange' | 'createStream'> {\n readonly onDidChangeState: Event<WidgetAudioState>;\n createStream(options: Parameters<WidgetAudioApi['createStream']>[0]): IFusedAudioStream;\n}\n\n/** Adapt the shared audio implementation's subscriptions to the editor lifecycle convention. */\nexport function fusedAudio(api: WidgetAudioApi): IFusedAudio {\n return {\n get state() {\n return api.state;\n },\n onDidChangeState: (listener) => ({ dispose: api.onStateChange(listener) }),\n tone: (options) => api.tone(options),\n createStream(options) {\n const stream = api.createStream(options);\n return Object.assign(stream, {\n onDidDrain: ((listener) => ({ dispose: stream.onDrain(() => listener()) })) as Event<void>,\n onDidChangeStatus: ((listener) => ({\n dispose: stream.onStatus(listener),\n })) as Event<WidgetAudioStreamStatus>,\n });\n },\n };\n}\n","/**\n * Display-side model client of one instance (RFC 0021 / RFC 0022).\n *\n * The client talks to the simulation guest over the direct model lane: a presentation input handler\n * calls its model without a hop through the editor, and `invalidate()` remains the only repaint\n * trigger. Only the methods and events the manifest declares resolve.\n */\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type { Value } from '@mica-js/document/fused';\nimport type { ModelEvent } from '@mica-js/sdk/fused';\nimport { createModelEventRouter } from '../model-events';\nimport { fusedModelChannelService, fusedModelSinkService } from '../protocol';\nimport type {\n IFusedInstancePresentation,\n IFusedModelClient,\n FusedModelMethods,\n IFusedModelEventWire,\n} from '../protocol';\nimport { mapWireFailure } from '../wire';\n\n/** Model lane as the display guest sees it. */\nexport interface IFusedDisplayModelChannel {\n /** Model client of one prepared instance. */\n client(instance: IFusedInstancePresentation): IFusedModelClient;\n /** Drops every listener of a released instance. */\n release(instanceId: string): void;\n /**\n * Resolves once subscriptions reach the simulation guest and prior model events reach this guest.\n *\n * Preparation awaits this before the models are mounted, so an event produced while a model\n * initializes is never lost to a subscription that is still in flight.\n */\n settle(): Promise<void>;\n dispose(): void;\n}\n\n/** Starts the display end of the model lane over `port`. */\nexport function startDisplayModelChannel(\n port: MessagePort,\n createEndpoint: (port: MessagePort) => RpcEndpoint = createRpc,\n): IFusedDisplayModelChannel {\n const endpoint = createEndpoint(port);\n const lane = endpoint.getProxy(fusedModelChannelService);\n /** Wire subscriptions still in flight, so preparation can wait for the model lane to catch up. */\n const inFlight = new Set<Promise<void>>();\n const router = createModelEventRouter({\n subscribe(instanceId, event) {\n const call = lane.subscribe(instanceId, event).catch(() => undefined);\n inFlight.add(call);\n void call.finally(() => inFlight.delete(call));\n },\n unsubscribe(instanceId, event) {\n const call = lane.unsubscribe(instanceId, event).catch(() => undefined);\n inFlight.add(call);\n void call.finally(() => inFlight.delete(call));\n },\n });\n endpoint.register(fusedModelSinkService, {\n deliver(event: IFusedModelEventWire) {\n if (!isModelEvent(event)) return;\n router.deliver(event.instanceId, event.event, event.payload);\n },\n });\n return {\n client(instance) {\n const declared = new Set(instance.methods);\n const methods = new Proxy(Object.create(null) as Record<string, unknown>, {\n get(_target, name) {\n if (typeof name !== 'string' || !declared.has(name)) return undefined;\n return (params: Value) =>\n mapWireFailure(() => lane.call(instance.instanceId, name, params));\n },\n has(_target, name) {\n return typeof name === 'string' && declared.has(name);\n },\n }) as FusedModelMethods;\n const events: Record<string, Event<ModelEvent<Value>>> = {};\n for (const name of instance.events) {\n events[name] = router.event(instance.instanceId, name);\n }\n return { methods, events };\n },\n release(instanceId) {\n router.release(instanceId);\n },\n async settle() {\n while (inFlight.size > 0) {\n await Promise.allSettled([...inFlight]);\n }\n await lane.settle();\n },\n dispose() {\n router.dispose();\n endpoint.dispose();\n },\n };\n}\n\nfunction isModelEvent(value: unknown): value is IFusedModelEventWire {\n if (typeof value !== 'object' || value === null) return false;\n const candidate = value as { readonly instanceId?: unknown; readonly event?: unknown };\n return typeof candidate.instanceId === 'string' && typeof candidate.event === 'string';\n}\n","/**\n * One 2D presentation of the display guest (RFC 0022).\n *\n * A session evaluates one verified `view2d.entry` module, builds the factory context and owns the\n * overlay canvas. Drawing is synchronous and never drives the model: `renderOverlay` only reads the\n * data the model already produced, and `invalidate()` is the only way a presentation asks for a\n * repaint.\n */\nimport type { Geometry2D } from '@mica-js/document/fused';\nimport { createWidgetAudioRuntime } from '@mica-js/widget/audio-guest';\nimport { fusedAudio, type IFusedAudio } from '../audio';\nimport type {\n FusedDisplayMode,\n IFusedInstancePresentation,\n IFusedModelClient,\n IFusedRenderRequest,\n IFusedView2DContext,\n FusedView2DFactory,\n IFusedViewAssets,\n IFusedViewInput,\n} from '../protocol';\nimport { byteBuffer, decodeSource, isThenable, reconstructPresentationProps } from '../values';\nimport { FusedBridgeError, messageOf } from '../wire';\n\n/** Canvas one overlay is painted into; injectable so the guest runs off-browser in tests. */\nexport interface IFusedOverlaySurface {\n readonly width: number;\n readonly height: number;\n getContext(type: '2d'): OffscreenCanvasRenderingContext2D | null;\n transferToImageBitmap(): ImageBitmap;\n}\n\nexport type FusedSurfaceFactory = (width: number, height: number) => IFusedOverlaySurface;\n\n/** Requests the display guest performs on behalf of one session. */\nexport interface IFusedViewSessionOptions {\n readonly instance: IFusedInstancePresentation;\n readonly mode: FusedDisplayMode;\n readonly model: IFusedModelClient | undefined;\n readonly audio?: IFusedAudio;\n readonly readAsset: (path: string) => Promise<Uint8Array>;\n readonly importModule: (code: string) => Promise<unknown>;\n readonly createSurface: FusedSurfaceFactory;\n readonly invalidate: () => void;\n readonly report: (code: string, message: string) => void;\n}\n\nexport interface IFusedViewSession {\n readonly instanceId: string;\n readonly geometry: Geometry2D;\n /** Runs the author `initialize` hook once; safe to call again. */\n activate(): Promise<void>;\n /** Paints one overlay frame; the caller owns the returned bitmap. */\n render(request: IFusedRenderRequest): ImageBitmap | undefined;\n input(event: IFusedViewInput): void;\n dispose(): void;\n}\n\n/**\n * Evaluates the presentation entry of one instance and initializes it.\n *\n * @throws {FusedBridgeError} when the module has no factory or `initialize` fails.\n */\nexport async function createViewSession(\n options: IFusedViewSessionOptions,\n): Promise<IFusedViewSession> {\n const { instance } = options;\n const entry = instance.view;\n if (entry === undefined) {\n throw new FusedBridgeError(\n 'view2d/unsupported',\n `${instance.device} declares no \\`view2d.entry\\`.`,\n { instanceId: instance.instanceId },\n );\n }\n const namespace = (await options.importModule(decodeSource(await options.readAsset(entry)))) as {\n readonly default?: unknown;\n } | null;\n const factory =\n namespace !== null && typeof namespace === 'object' ? namespace.default : undefined;\n if (typeof factory !== 'function') {\n throw new FusedBridgeError(\n 'runtime/presentation-failed',\n `${instance.device}/${entry} must default-export a presentation factory.`,\n { instanceId: instance.instanceId },\n );\n }\n\n let disposed = false;\n const localAudio = options.audio === undefined ? createWidgetAudioRuntime({}) : undefined;\n let surface: IFusedOverlaySurface | undefined;\n const assets: IFusedViewAssets = {\n read: (path: string) => options.readAsset(path),\n loadImage: async (path: string) =>\n createImageBitmap(new Blob([byteBuffer(await options.readAsset(path))])),\n };\n const context: IFusedView2DContext = {\n mode: options.mode,\n props: reconstructPresentationProps(instance.props),\n geometry: instance.geometry,\n model: options.model,\n assets,\n audio: options.audio ?? fusedAudio(localAudio!.api(instance.instanceId)),\n invalidate: () => {\n if (!disposed) options.invalidate();\n },\n };\n const view = (factory as FusedView2DFactory)(context);\n if (typeof view !== 'object' || view === null) {\n throw new FusedBridgeError(\n 'runtime/presentation-failed',\n `${instance.device}/${entry} returned no presentation object.`,\n { instanceId: instance.instanceId },\n );\n }\n let activated = false;\n\n return {\n instanceId: instance.instanceId,\n geometry: instance.geometry,\n /**\n * Runs `initialize` once, after the models exist (RFC 0025 startup barrier). The factory itself\n * only registers listeners, so a presentation sees the initial model events before this runs.\n */\n async activate() {\n if (disposed || activated) return;\n activated = true;\n const initialized = view.initialize?.();\n if (isThenable(initialized)) await initialized;\n },\n render(request) {\n const draw = view.renderOverlay;\n if (disposed || draw === undefined) return undefined;\n const target = surfaceFor(request.width, request.height);\n const context2d = target.getContext('2d');\n if (context2d === null) {\n throw new FusedBridgeError(\n 'view2d/render-failed',\n 'The overlay canvas has no 2D context.',\n {\n instanceId: instance.instanceId,\n },\n );\n }\n context2d.save();\n try {\n context2d.setTransform(1, 0, 0, 1, 0, 0);\n context2d.clearRect(0, 0, request.width, request.height);\n const bounds = instance.geometry.bounds;\n context2d.setTransform(\n request.scale,\n 0,\n 0,\n request.scale,\n -bounds.x * request.scale,\n -bounds.y * request.scale,\n );\n const result = draw.call(view, context2d);\n if (isThenable(result)) {\n throw new FusedBridgeError(\n 'view2d/render-failed',\n 'renderOverlay must draw synchronously.',\n { instanceId: instance.instanceId },\n );\n }\n } finally {\n context2d.restore();\n }\n return target.transferToImageBitmap();\n },\n input(event) {\n const handle = view.input;\n if (disposed || handle === undefined) return;\n try {\n const result = handle.call(view, event);\n if (isThenable(result)) {\n void Promise.resolve(result).catch((cause: unknown) => {\n options.report('view2d/input-failed', messageOf(cause));\n });\n }\n } catch (cause) {\n options.report('view2d/input-failed', messageOf(cause));\n }\n },\n dispose() {\n if (disposed) return;\n disposed = true;\n localAudio?.dispose();\n try {\n view.dispose?.();\n } catch (cause) {\n options.report(\n 'runtime/presentation-failed',\n `Releasing the presentation failed: ${messageOf(cause)}`,\n );\n }\n },\n };\n\n function surfaceFor(width: number, height: number): IFusedOverlaySurface {\n if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {\n throw new FusedBridgeError(\n 'view2d/render-failed',\n `The overlay extent ${String(width)}x${String(height)} must be positive.`,\n { instanceId: instance.instanceId },\n );\n }\n if (surface === undefined || surface.width !== width || surface.height !== height) {\n surface = options.createSurface(width, height);\n }\n return surface;\n }\n}\n","/**\n * 2D presentation guest of the fused editor runtime (RFC 0022 / RFC 0025).\n *\n * One guest serves every instance of the workbench: it evaluates the declared `view2d.entry` modules\n * of the current mode, draws overlays into its own canvases and reports the bitmaps to the host. It\n * holds no document and no model: geometry, properties and the model lane all come from the\n * simulation guest through the host.\n */\nimport { Emitter } from '@mica-js/core/lifecycle';\nimport { createWidgetAudioRuntime } from '@mica-js/widget/audio-guest';\nimport { fusedAudio } from '../audio';\nimport { createRpc } from '@mica-js/core/rpc';\nimport type { RpcEndpoint } from '@mica-js/core/rpc';\nimport type { DeviceLock } from '@mica-js/document/fused';\nimport type { RuntimeDiagnostic } from '@mica-js/sdk/fused';\nimport { fusedDisplayService, fusedHostAudioService } from '../protocol';\nimport type {\n IFusedDisplayPrepareRequest,\n IFusedInvalidateEvent,\n IFusedOverlayFrame,\n IFusedRenderRequest,\n IFusedViewInput,\n} from '../protocol';\nimport { createHostPackageGateway } from '../packages';\nimport { importCode } from '../values';\nimport {\n FusedBridgeError,\n isImageBitmap,\n messageOf,\n toWireFailure,\n transferOverlayFrame,\n} from '../wire';\nimport { startDisplayModelChannel } from './model';\nimport type { IFusedDisplayModelChannel } from './model';\nimport { createViewSession } from './view';\nimport type { FusedSurfaceFactory, IFusedViewSession } from './view';\n\n/** Replaceable guest dependencies, so the presentation runs off-browser in tests. */\nexport interface IFusedDisplayGuestOptions {\n readonly createEndpoint?: (port: MessagePort) => RpcEndpoint;\n /** Startup ports after the RPC port; the first one is the model lane (RFC 0025). */\n readonly ports?: readonly MessagePort[];\n /** Evaluates one verified view module; defaults to a blob URL plus dynamic `import()`. */\n readonly importModule?: (code: string) => Promise<unknown>;\n /** Creates the overlay canvas; defaults to `OffscreenCanvas`. */\n readonly createSurface?: FusedSurfaceFactory;\n}\n\nexport interface IFusedDisplayGuest {\n readonly rpc: RpcEndpoint;\n dispose(): Promise<void>;\n}\n\n/** Starts the 2D presentation guest on the startup port of a sandbox worker. */\nexport function startFusedDisplayGuest(\n port: MessagePort,\n options: IFusedDisplayGuestOptions = {},\n): IFusedDisplayGuest {\n const endpoint = (options.createEndpoint ?? createRpc)(port);\n const importModule = options.importModule ?? importCode;\n const createSurface: FusedSurfaceFactory =\n options.createSurface ?? ((width, height) => new OffscreenCanvas(width, height));\n const packages = createHostPackageGateway(endpoint);\n const diagnostics = new Emitter<RuntimeDiagnostic>();\n const audio = createWidgetAudioRuntime({\n onListenerError: (instanceId, cause) =>\n diagnostics.fire({\n code: 'audio/listener-failed',\n message: messageOf(cause),\n instanceId,\n }),\n });\n const hostAudio = endpoint.getProxy(fusedHostAudioService);\n const audioSessions = new Map<string, string>();\n const invalidations = new Emitter<IFusedInvalidateEvent>();\n const modelPort = options.ports?.[0];\n const modelChannel: IFusedDisplayModelChannel | undefined =\n modelPort === undefined ? undefined : startDisplayModelChannel(modelPort);\n\n let sessions = new Map<string, IFusedViewSession>();\n /** Incremented by every preparation, so late initializations of a replaced mode are dropped. */\n let sequence = 0;\n let closing = false;\n let disposal: Promise<void> | undefined;\n\n // The overlay bitmap is transferable-only: cloning one is invalid, so the hook hands it over.\n endpoint.register(\n fusedDisplayService,\n {\n attachAudio: (port) => audio.attachPort(port),\n setAudioState: (state) => audio.setState(state),\n prepare,\n activate,\n render,\n input,\n release,\n dispose: releaseAll,\n onDidInvalidate(listener) {\n const subscription = invalidations.event((value) => listener(value));\n return () => subscription.dispose();\n },\n onDidReportDiagnostic(listener) {\n const subscription = diagnostics.event((value) => listener(value));\n return () => subscription.dispose();\n },\n },\n { transfer: transferOverlayFrame },\n );\n\n return { rpc: endpoint, dispose };\n\n function report(entry: RuntimeDiagnostic): void {\n diagnostics.fire(entry);\n }\n\n function readAsset(lock: DeviceLock, path: string): Promise<Uint8Array> {\n return packages.open(lock).then((files) => files.read(path));\n }\n\n async function prepare(request: IFusedDisplayPrepareRequest): Promise<void> {\n if (closing) {\n throw toWireFailure(\n new FusedBridgeError('runtime/unavailable-state', 'The fused display guest is disposed.'),\n );\n }\n const attempt = ++sequence;\n dropSessions();\n for (const instance of request.instances) {\n if (instance.view === undefined) continue;\n const instanceId = instance.instanceId;\n try {\n if (request.mode === 'run') {\n const info = await hostAudio.open(instanceId);\n if (closing || attempt !== sequence) {\n if (info.session !== undefined)\n void hostAudio.close(instanceId, info.session).catch(() => undefined);\n return;\n }\n audio.open(instanceId, info);\n if (info.session !== undefined) audioSessions.set(instanceId, info.session);\n } else audio.open(instanceId, undefined);\n const session = await createViewSession({\n instance,\n mode: request.mode,\n model: request.mode === 'run' ? modelChannel?.client(instance) : undefined,\n audio: fusedAudio(audio.api(instanceId)),\n readAsset: (path) => readAsset(instance.lock, path),\n importModule,\n createSurface,\n invalidate: () => {\n if (attempt === sequence && !closing) invalidations.fire({ instanceId });\n },\n report: (code, message) => report({ code, message, instanceId }),\n });\n if (closing || attempt !== sequence) {\n session.dispose();\n return;\n }\n sessions.set(instanceId, session);\n } catch (cause) {\n releaseAudio(instanceId);\n // One broken presentation must not take the other instances down (RFC 0025).\n report({\n code: 'runtime/presentation-failed',\n message: messageOf(cause),\n instanceId,\n });\n }\n }\n // The runtime loads the models only after this resolves, so factory subscriptions are live.\n await modelChannel?.settle();\n }\n\n /**\n * Runs the author `initialize` hook of every prepared presentation.\n *\n * The runtime calls it after the models exist and their initial events were delivered, so a query\n * started here observes the state the model already has. A failing hook faults its own\n * presentation only (RFC 0025 `runtime/presentation-failed`).\n */\n async function activate(): Promise<void> {\n if (closing) return;\n const attempt = sequence;\n // Host activation and model events use different ports; synchronize on the model lane first.\n await modelChannel?.settle();\n if (closing || attempt !== sequence) return;\n for (const [instanceId, session] of [...sessions]) {\n try {\n await session.activate();\n } catch (cause) {\n if (closing || attempt !== sequence) {\n session.dispose();\n return;\n }\n report({\n code: 'runtime/presentation-failed',\n message: `Initializing the presentation failed: ${messageOf(cause)}`,\n instanceId,\n });\n release(instanceId);\n }\n }\n }\n\n async function render(request: IFusedRenderRequest): Promise<IFusedOverlayFrame | undefined> {\n if (closing) return undefined;\n const session = sessions.get(request.instanceId);\n if (session === undefined) return undefined;\n const attempt = sequence;\n let bitmap: ImageBitmap | undefined;\n try {\n bitmap = session.render(request);\n } catch (cause) {\n report({\n code: 'view2d/render-failed',\n message: messageOf(cause),\n instanceId: request.instanceId,\n });\n return undefined;\n }\n if (bitmap === undefined) return undefined;\n if (closing || attempt !== sequence) {\n closeBitmap(bitmap);\n return undefined;\n }\n return {\n instanceId: request.instanceId,\n generation: request.generation,\n width: request.width,\n height: request.height,\n scale: request.scale,\n bitmap,\n };\n }\n\n function input(instanceId: string, event: IFusedViewInput): void {\n if (closing) return;\n sessions.get(instanceId)?.input(event);\n }\n\n function release(instanceId: string): void {\n releaseAudio(instanceId);\n const session = sessions.get(instanceId);\n if (session === undefined) return;\n sessions.delete(instanceId);\n session.dispose();\n modelChannel?.release(instanceId);\n }\n\n async function releaseAll(): Promise<void> {\n if (closing) return;\n sequence += 1;\n dropSessions();\n }\n\n function dropSessions(): void {\n for (const instanceId of [...audioSessions.keys()]) releaseAudio(instanceId);\n const current = sessions;\n sessions = new Map<string, IFusedViewSession>();\n for (const session of current.values()) {\n releaseAudio(session.instanceId);\n session.dispose();\n modelChannel?.release(session.instanceId);\n }\n }\n\n function dispose(): Promise<void> {\n if (disposal !== undefined) return disposal;\n closing = true;\n disposal = (async () => {\n sequence += 1;\n dropSessions();\n modelChannel?.dispose();\n audio.dispose();\n endpoint.dispose();\n diagnostics.dispose();\n invalidations.dispose();\n })();\n return disposal;\n }\n\n function releaseAudio(instanceId: string): void {\n audio.release(instanceId);\n const token = audioSessions.get(instanceId);\n audioSessions.delete(instanceId);\n if (token !== undefined) void hostAudio.close(instanceId, token).catch(() => undefined);\n }\n}\n\nfunction closeBitmap(bitmap: ImageBitmap): void {\n if (isImageBitmap(bitmap)) bitmap.close();\n}\n","/**\n * `@mica-js/editor/fused/runtime`: the browser bridge of the fused editor runtime (RFC 0022 / 0025).\n *\n * Two sandbox workers serve one workbench. The simulation worker owns the document, the locked\n * packages and every model; the presentation worker runs the declared `view2d.entry` modules and\n * returns overlay bitmaps. They talk over typed RPC services and one direct model lane, and the\n * editor thread never imports model or author view code.\n *\n * ```ts\n * const runtime = await createFusedRuntime({\n * document,\n * registry,\n * step: toTimePs(1, 'ms'),\n * mode: 'run', // mounts the models; advancing starts as soon as the presentations are ready\n * onOverlay: (frame) => paint(frame.instanceId, frame.bitmap),\n * onDiagnostic: (entry) => report(entry),\n * });\n * runtime.display.input(instanceId, { type: 'pointerdown', position, button: 0, buttons: 1 });\n * const frame = await runtime.display.render(instanceId);\n * await runtime.pause(); // step() requires the paused state\n * await runtime.dispose();\n * ```\n */\nimport type { IFusedWorkerFactories } from './host/types';\nexport type * from './audio';\n\nexport { createFusedRuntime } from './host/runtime';\n\n/**\n * Loads the generated worker factories on demand.\n *\n * `createFusedRuntime` does this itself; call it to preload both guest bundles, or to pass the\n * same factories to several runtimes.\n */\nexport async function loadFusedWorkerFactories(): Promise<IFusedWorkerFactories> {\n const { fusedWorkerFactories } = await import('./workers');\n return fusedWorkerFactories;\n}\nexport { connectFusedWorkbench } from './host/connection';\nexport type { IFusedConnection, IFusedConnectionOptions } from './host/connection';\nexport { createFusedDisplay } from './host/display';\nexport type { IFusedDisplayHost, IFusedDisplayHostOptions } from './host/display';\nexport { createHostModelRouter } from './host/model';\nexport type { IFusedHostModelRouter } from './host/model';\nexport type {\n IFusedDisplay,\n IFusedDisplayPrepareInput,\n IFusedRuntime,\n IFusedRuntimeOptions,\n IFusedWorker,\n IFusedWorkerFactories,\n IFusedWorkerOptions,\n} from './host/types';\n\nexport { startFusedSimulationGuest } from './simulation/guest';\nexport type { IFusedSimulationGuest, IFusedSimulationGuestOptions } from './simulation/guest';\nexport { startFusedDisplayGuest } from './display/guest';\nexport type { IFusedDisplayGuest, IFusedDisplayGuestOptions } from './display/guest';\nexport { createViewSession } from './display/view';\nexport type {\n IFusedOverlaySurface,\n FusedSurfaceFactory,\n IFusedViewSession,\n IFusedViewSessionOptions,\n} from './display/view';\nexport { createModelEventRouter, channelKey } from './model-events';\nexport type { IFusedModelEventChannel, IFusedModelEventRouter } from './model-events';\nexport { createHostPackageGateway, packageLockKey } from './packages';\n\nexport {\n FUSED_WIRE_FAILURE,\n FusedBridgeError,\n fromWireFailure,\n isFusedBridgeError,\n mapWireFailure,\n toWireFailure,\n} from './wire';\nexport type { IFusedBridgeErrorOptions, IFusedFailurePayload } from './wire';\n\nexport {\n fusedDisplayService,\n fusedHostPackageService,\n fusedHostResourceService,\n fusedModelChannelService,\n fusedModelSinkService,\n fusedSimulationService,\n} from './protocol';\nexport type {\n FusedDisplayMode,\n FusedPresentationProps,\n FusedPresentationValue,\n FusedSessionStatus,\n FusedSimulationPacing,\n FusedViewInputType,\n IFusedDisplayLayout,\n IFusedDisplayPrepareRequest,\n IFusedDisplayService,\n IFusedHostPackageService,\n IFusedHostResourceService,\n IFusedInstancePresentation,\n IFusedInvalidateEvent,\n IFusedLoadRequest,\n IFusedModelChannelService,\n IFusedModelClient,\n IFusedModelEventWire,\n FusedModelEvents,\n FusedModelMethods,\n IFusedModelSinkService,\n IFusedOverlayFrame,\n IFusedPackageFilesWire,\n IFusedPrepareRequest,\n IFusedPrepareResult,\n IFusedRenderRequest,\n IFusedSessionState,\n IFusedSimulationService,\n IFusedView2D,\n IFusedView2DContext,\n FusedView2DFactory,\n IFusedViewAssets,\n IFusedViewInput,\n} from './protocol';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2VA,IAAa,yBAAyB,iBAA0C,kBAAkB;;AAGlG,IAAa,sBAAsB,iBAAuC,eAAe;;AAGzF,IAAa,0BACX,iBAA2C,oBAAoB;;AAGjE,IAAa,2BACX,iBAA4C,qBAAqB;;AAGnE,IAAa,2BACX,iBAA4C,qBAAqB;;AAGnE,IAAa,wBAAwB,iBAAyC,kBAAkB;AAQhG,IAAa,wBAAwB,iBAAyC,kBAAkB;;;;ACvWhG,SAAgB,eAAe,MAA0B;CACvD,OAAO,GAAG,KAAK,GAAG,GAAG,KAAK,QAAQ,GAAG,KAAK;AAC5C;;AAGA,SAAgB,yBAAyB,UAAuC;CAC9E,MAAM,OAAO,SAAS,SAAS,uBAAuB;CACtD,MAAM,yBAAS,IAAI,IAA6C;CAChE,MAAM,wBAAQ,IAAI,IAAwB;CAC1C,MAAM,YAAY,SAAsD;EACtE,MAAM,MAAM,eAAe,IAAI;EAC/B,IAAI,UAAU,OAAO,IAAI,GAAG;EAC5B,IAAI,YAAY,KAAA,GAAW;GACzB,UAAU,KAAK,KAAK,IAAI;GACxB,OAAO,IAAI,KAAK,OAAO;EACzB;EACA,OAAO;CACT;CACA,OAAO,EACL,KAAK,MAAkB;EACrB,OAAO,SAAS,IAAI,CAAC,CAAC,MAAM,WAAW;GACrC,MAAM,MAAM;GACZ,OAAO,MAAM;GACb,MAAM,OAAO,SAAiB;IAC5B,MAAM,MAAM,GAAG,eAAe,IAAI,EAAE,QAAQ;IAC5C,MAAM,SAAS,MAAM,IAAI,GAAG;IAC5B,IAAI,WAAW,KAAA,GAAW,OAAO,OAAO,MAAM;IAC9C,MAAM,QAAQ,MAAM,KAAK,KAAK,MAAM,IAAI;IACxC,IAAI,EAAE,iBAAiB,aACrB,MAAM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;;;;ACjQA,eAAsB,2BAA2D;CAC/E,MAAM,EAAE,yBAAyB,MAAM,OAAO;CAC9C,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"wire-BDHL5Aj9.js","names":[],"sources":["../src/fused/runtime/wire.ts"],"sourcesContent":["/**\n * Failure and transfer conventions of the fused sandbox bridge (RFC 0025).\n *\n * RPC carries only `name` and `message` across a sandbox boundary, so a contract failure travels as\n * JSON inside the message and is rebuilt on the other side. Nothing here imports device or model\n * code: the main thread must never pull model execution into its own bundle.\n */\nimport type { Value } from '@mica-js/document/fused';\nimport type {\n IFusedFirmwareSnapshot,\n IFusedProgramFilesSnapshot,\n IFusedOverlayFrame,\n IFusedPrepareResult,\n} from './protocol';\n\n/** `name` of a failure whose message carries a {@link IFusedFailurePayload}. */\nexport const FUSED_WIRE_FAILURE = 'FusedSandboxFailure';\n\n/** One failure of a guest call, flattened for the wire. */\nexport interface IFusedFailurePayload {\n /** `method` keeps a business rejection, `runtime` a contract error, `failure` anything else. */\n readonly kind: 'method' | 'runtime' | 'failure';\n readonly code: string;\n readonly message: string;\n readonly instanceId?: string;\n /** JSON-safe snapshot of a `MethodError` payload. */\n readonly details?: unknown;\n}\n\nexport interface IFusedBridgeErrorOptions {\n readonly instanceId?: string;\n readonly details?: Value;\n /**\n * Error name. A method rejection keeps `MethodError`, so the SDK predicate of the consumer still\n * recognizes it; every other failure keeps the default name.\n */\n readonly name?: string;\n}\n\n/**\n * Host-side failure of the fused sandbox bridge.\n *\n * Mirrors `FusedRuntimeError` (`code`, optional `instanceId`) and keeps the business payload of a\n * model `MethodError` rejection. Guest code uses the same class to build the failure it throws.\n */\nexport class FusedBridgeError extends Error {\n readonly code: string;\n readonly instanceId: string | undefined;\n readonly details: Value | undefined;\n\n constructor(code: string, message: string, options: IFusedBridgeErrorOptions = {}) {\n super(message);\n this.name = options.name ?? 'FusedBridgeError';\n this.code = code;\n this.instanceId = options.instanceId;\n this.details = options.details;\n }\n}\n\nexport function isFusedBridgeError(value: unknown): value is FusedBridgeError {\n return value instanceof FusedBridgeError;\n}\n\n/** Encodes one failure as an `Error` the RPC layer can carry. */\nexport function toWireFailure(cause: unknown): Error {\n const payload = failurePayload(cause);\n return Object.assign(new Error(JSON.stringify(payload)), { name: FUSED_WIRE_FAILURE });\n}\n\n/** Rebuilds the failure of a rejected guest call; other errors pass through. */\nexport function fromWireFailure(cause: unknown): Error {\n if (!(cause instanceof Error) || cause.name !== FUSED_WIRE_FAILURE) {\n return cause instanceof Error ? cause : new Error(String(cause));\n }\n const payload = decodePayload(cause.message);\n if (payload === undefined) {\n return cause;\n }\n return new FusedBridgeError(payload.code, payload.message, {\n ...(payload.kind === 'method' ? { name: 'MethodError' } : {}),\n ...(payload.instanceId === undefined ? {} : { instanceId: payload.instanceId }),\n ...(payload.details === undefined ? {} : { details: payload.details as Value }),\n });\n}\n\n/** Runs one guest call and rebuilds a wire failure of its rejection. */\nexport async function mapWireFailure<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (cause) {\n throw fromWireFailure(cause);\n }\n}\n\n/** Whether a value is a decodable overlay bitmap of this realm. */\nexport function isImageBitmap(value: unknown): value is ImageBitmap {\n return typeof ImageBitmap !== 'undefined' && value instanceof ImageBitmap;\n}\n\n/** Transfer list of one `prepare` result: every byte snapshot of the presentation props. */\nexport function transferPresentationBytes(member: string, value: unknown): readonly Transferable[] {\n if (member !== 'prepare') return [];\n const instances = (value as IFusedPrepareResult | undefined)?.instances ?? [];\n const buffers = new Set<ArrayBuffer>();\n for (const instance of instances) {\n for (const prop of Object.values(instance.props)) collectPropBytes(prop, buffers);\n }\n return [...buffers];\n}\n\nfunction collectPropBytes(value: unknown, buffers: Set<ArrayBuffer>): void {\n if (value instanceof Uint8Array) {\n if (value.buffer instanceof ArrayBuffer) buffers.add(value.buffer);\n return;\n }\n const snapshot = value as IFusedFirmwareSnapshot | IFusedProgramFilesSnapshot | null;\n if (snapshot === null || typeof snapshot !== 'object') return;\n if (snapshot.kind === 'filesystem') {\n for (const file of snapshot.files) collectPropBytes(file.data, buffers);\n return;\n }\n if (snapshot.kind !== 'firmware') return;\n for (const segment of snapshot.segments) {\n if (segment.bytes instanceof Uint8Array && segment.bytes.buffer instanceof ArrayBuffer) {\n buffers.add(segment.bytes.buffer);\n }\n }\n}\n/** Transfer list of one `render` result. */\nexport function transferOverlayFrame(member: string, value: unknown): readonly Transferable[] {\n if (member !== 'render') return [];\n const frame = value as IFusedOverlayFrame | undefined;\n if (frame === undefined || frame === null) return [];\n return isImageBitmap(frame.bitmap) ? [frame.bitmap] : [];\n}\n\n/** Transfer list of one `Uint8Array` result. */\nexport function transferBytes(value: unknown): readonly Transferable[] {\n if (!(value instanceof Uint8Array)) return [];\n if (!(value.buffer instanceof ArrayBuffer)) return [];\n if (value.byteOffset !== 0 || value.byteLength !== value.buffer.byteLength) return [];\n return [value.buffer];\n}\n\n/** Transfer list of one host package `read` result. */\nexport function transferPackageBytes(member: string, value: unknown): readonly Transferable[] {\n return member === 'read' ? transferBytes(value) : [];\n}\n\n/** Transfer list of one host `readResource` result. */\nexport function transferResourceBytes(member: string, value: unknown): readonly Transferable[] {\n return member === 'readResource' ? transferBytes(value) : [];\n}\n\nexport function transferProgramArtifact(member: string, value: unknown): readonly Transferable[] {\n if (member !== 'resolveProgramProject') return [];\n const artifact = value as {\n readonly kind?: string;\n readonly data?: Uint8Array;\n readonly files?: readonly { readonly data: Uint8Array }[];\n };\n const files = artifact.files;\n return [\n ...new Set(\n files ? files.flatMap((file) => transferBytes(file.data)) : transferBytes(artifact.data),\n ),\n ];\n}\n\nfunction failurePayload(cause: unknown): IFusedFailurePayload {\n const message = messageOf(cause);\n const method = methodErrorOf(cause);\n if (method !== undefined) {\n return {\n kind: 'method',\n code: method.code,\n message: method.message,\n ...(method.details === undefined ? {} : { details: jsonSafe(method.details) }),\n };\n }\n const code = codeOf(cause);\n const instanceId = instanceIdOf(cause);\n return {\n kind: code === 'Error' ? 'failure' : 'runtime',\n code,\n message,\n ...(instanceId === undefined ? {} : { instanceId }),\n };\n}\n\nfunction decodePayload(message: string): IFusedFailurePayload | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const candidate = parsed as Record<string, unknown>;\n if (typeof candidate['code'] !== 'string' || typeof candidate['message'] !== 'string') {\n return undefined;\n }\n const kind =\n candidate['kind'] === 'method' || candidate['kind'] === 'runtime'\n ? candidate['kind']\n : 'failure';\n return {\n kind,\n code: candidate['code'],\n message: candidate['message'],\n ...(typeof candidate['instanceId'] === 'string' ? { instanceId: candidate['instanceId'] } : {}),\n ...(candidate['details'] === undefined ? {} : { details: candidate['details'] }),\n };\n}\n\nfunction codeOf(cause: unknown): string {\n if (typeof cause !== 'object' || cause === null) return 'Error';\n const code = (cause as { readonly code?: unknown }).code;\n if (typeof code === 'string' && code.length > 0) return code;\n const name = (cause as { readonly name?: unknown }).name;\n return typeof name === 'string' && name.length > 0 ? name : 'Error';\n}\n\nfunction instanceIdOf(cause: unknown): string | undefined {\n if (typeof cause !== 'object' || cause === null) return undefined;\n const instanceId = (cause as { readonly instanceId?: unknown }).instanceId;\n return typeof instanceId === 'string' ? instanceId : undefined;\n}\n\n/**\n * Recognizes a model business rejection without importing the SDK: the runtime and its guests may\n * carry different copies of the class, so the shape plus the registered name is what counts.\n */\nfunction methodErrorOf(\n cause: unknown,\n): { readonly code: string; readonly message: string; readonly details?: unknown } | undefined {\n if (typeof cause !== 'object' || cause === null) return undefined;\n const candidate = cause as {\n readonly name?: unknown;\n readonly code?: unknown;\n readonly message?: unknown;\n readonly details?: unknown;\n };\n if (candidate.name !== 'MethodError' || typeof candidate.code !== 'string') return undefined;\n if (typeof candidate.message !== 'string') return undefined;\n return {\n code: candidate.code,\n message: candidate.message,\n ...(candidate.details === undefined ? {} : { details: candidate.details }),\n };\n}\n\n/** JSON-safe copy of a model value; byte payloads become number arrays. */\nfunction jsonSafe(value: unknown): unknown {\n if (value instanceof Uint8Array) return [...value];\n if (Array.isArray(value)) return value.map((item: unknown) => jsonSafe(item));\n if (typeof value === 'object' && value !== null) {\n const record: Record<string, unknown> = {};\n for (const [key, member] of Object.entries(value)) record[key] = jsonSafe(member);\n return record;\n }\n return value;\n}\n\nexport function messageOf(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n"],"mappings":";;AAgBA,IAAa,qBAAqB;;;;;;;AA6BlC,IAAa,mBAAb,cAAsC,MAAM;CAC1C;CACA;CACA;CAEA,YAAY,MAAc,SAAiB,UAAoC,CAAC,GAAG;EACjF,MAAM,OAAO;EACb,KAAK,OAAO,QAAQ,QAAQ;EAC5B,KAAK,OAAO;EACZ,KAAK,aAAa,QAAQ;EAC1B,KAAK,UAAU,QAAQ;CACzB;AACF;AAEA,SAAgB,mBAAmB,OAA2C;CAC5E,OAAO,iBAAiB;AAC1B;;AAGA,SAAgB,cAAc,OAAuB;CACnD,MAAM,UAAU,eAAe,KAAK;CACpC,OAAO,OAAO,OAAO,IAAI,MAAM,KAAK,UAAU,OAAO,CAAC,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACvF;;AAGA,SAAgB,gBAAgB,OAAuB;CACrD,IAAI,EAAE,iBAAiB,UAAU,MAAM,SAAA,uBACrC,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;CAEjE,MAAM,UAAU,cAAc,MAAM,OAAO;CAC3C,IAAI,YAAY,KAAA,GACd,OAAO;CAET,OAAO,IAAI,iBAAiB,QAAQ,MAAM,QAAQ,SAAS;EACzD,GAAI,QAAQ,SAAS,WAAW,EAAE,MAAM,cAAc,IAAI,CAAC;EAC3D,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;EAC7E,GAAI,QAAQ,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAiB;CAC/E,CAAC;AACH;;AAGA,eAAsB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