@powerhousedao/reactor-browser 6.2.3-dev.54 → 6.2.3-dev.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/rpc/index.d.ts
CHANGED
|
@@ -191,6 +191,8 @@ export declare class SyncManagerProxy implements ISyncManager, ISyncInspector, I
|
|
|
191
191
|
triggerPull(name: string): void;
|
|
192
192
|
remove(name: string): Promise<void>;
|
|
193
193
|
list(): Remote[];
|
|
194
|
+
/** Re-reads the worker's remotes after a change made outside this proxy. */
|
|
195
|
+
refresh(): Promise<void>;
|
|
194
196
|
waitForSync(): Promise<never>;
|
|
195
197
|
getSyncStatus(documentId: string): SyncStatus | undefined;
|
|
196
198
|
onSyncStatusChange(callback: SyncStatusChangeCallback): () => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/rpc/adopt-sync-peer.ts","../../../src/rpc/reactor-host.ts","../../../src/rpc/local-sync-peer-handlers.ts","../../../src/rpc/inspector-ops.ts","../../../src/rpc/op-channel.ts","../../../src/rpc/live-query-proxy.ts","../../../src/rpc/relational-db-proxy.ts","../../../src/rpc/event-bus-proxy.ts","../../../src/rpc/forwarded-events.ts","../../../src/rpc/connect-reactor.ts","../../../src/rpc/sync-manager-proxy.ts","../../../src/rpc/worker-package-loader.ts"],"mappings":";;;;;;KAIY;EACV;EACA;;EAEA;EACA;EACA,QAAQ;;KAGE;EACV;EACA;EACA;;;wBAIc,kBACd,QAAQ,iBACR,QAAQ,qBACR,MAAM,cACL;;wBAmBa,mBACd,QAAQ,iBACR,QAAQ,uBACP;;;KCOS;EACV,SAAS;EACT,SAAS,uBAAuB,QAAQ;EACxC,oBACE,iBACA,UAAU,4BACP;EACL,sBAAsB,oBAAoB;EAC1C,cAAc,MAAM;EACpB,YAAY,gBAAgB,oBAAoB;EAChD,UAAU,gBAAgB,oBAAoB;EAC9C,iBAAiB,gBAAgB,oBAAoB;;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AAgB;;;qBC1CtD;qBASA;;;KCDD;EACV,SAAS;EACT;EACA;;wBAGc,qBACd,QAAQ,iBACR,OAAO,cACP,YAAY,gBAAgB,6BAC5B,WAAW,yBACV;wBAaa,oBACd,QAAQ,iBACR,MAAM;;;qBCGK;KAED;EACV;EACA,QAAQ;;qBAoFG,4BACA,cAAc,gBAAgB;mBAExB;mBACA;mBAIA;mBACA;mBACA;UACT;UACA;UACA;EAER,YAAY,QAAQ,iBAAe,UAAU;;EAsBvC,UACJ;IACG;MAAmC;EAgBxC,YAAY;EAIZ,UAAU,eAAe;EAQzB,QAAQ,aAAa;EAQf,IACJ,cACA,cAAc,mBACd,eAAe,eACf,SAAS,cACT,UAAU,gBACT,QAAQ;EAYL,gBACJ,YACA,UAAU,sBACT;;EAMH,iBAAiB;EAIX,UAAU;IACd;IACA;MACE,QAAQ;EAIZ,aAAa;UAOL;EASF,WAAW,YAAY,uBAAuB;EAKpD,YAAY;EAMN,OAAO,eAAe;EAK5B,QAAQ;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/rpc/adopt-sync-peer.ts","../../../src/rpc/reactor-host.ts","../../../src/rpc/local-sync-peer-handlers.ts","../../../src/rpc/inspector-ops.ts","../../../src/rpc/op-channel.ts","../../../src/rpc/live-query-proxy.ts","../../../src/rpc/relational-db-proxy.ts","../../../src/rpc/event-bus-proxy.ts","../../../src/rpc/forwarded-events.ts","../../../src/rpc/connect-reactor.ts","../../../src/rpc/sync-manager-proxy.ts","../../../src/rpc/worker-package-loader.ts"],"mappings":";;;;;;KAIY;EACV;EACA;;EAEA;EACA;EACA,QAAQ;;KAGE;EACV;EACA;EACA;;;wBAIc,kBACd,QAAQ,iBACR,QAAQ,qBACR,MAAM,cACL;;wBAmBa,mBACd,QAAQ,iBACR,QAAQ,uBACP;;;KCOS;EACV,SAAS;EACT,SAAS,uBAAuB,QAAQ;EACxC,oBACE,iBACA,UAAU,4BACP;EACL,sBAAsB,oBAAoB;EAC1C,c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;mBACA;mBACA;mBACA;mBACA;mBAKA;mBAEA;mBAEA;mBACA;mBACA;mBACA;mBACA;mBACA;UACT;EAER,YAAY,SAAS;EAYf,aAAa,kBAAkB,QAAQ;;EAQvC,YAAY,SAAS,0BAAwB;;;;;;;;;EAc7C,cACJ,SAAS,0BACR;IAAU;IAAiB,UAAU;;EAmBlC,KAAK,uBAAuB,QAAQ;MAqBtC,UAAU;MAIV,oBAAoB;MAIpB,gBAAgB;;UAKZ;UAaA;UAuBM;UAQN;UAgBM;UAoCA;;UA2BN"}
|
package/dist/src/rpc/index.js
CHANGED
|
@@ -314,6 +314,10 @@ var SyncManagerProxy = class {
|
|
|
314
314
|
list() {
|
|
315
315
|
return [...this.remotes];
|
|
316
316
|
}
|
|
317
|
+
/** Re-reads the worker's remotes after a change made outside this proxy. */
|
|
318
|
+
refresh() {
|
|
319
|
+
return this.refreshRemotes();
|
|
320
|
+
}
|
|
317
321
|
waitForSync() {
|
|
318
322
|
return Promise.reject(/* @__PURE__ */ new Error("waitForSync is not supported over the worker RPC boundary"));
|
|
319
323
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Listeners","createCorrelatedSubscriptions","fromErrorInfo","KeyedListeners","Listeners","KeyedListeners","createReactorClientProxy","SubscriptionStore","hostResponder","ReactorHostServer","createPortTransport","RPC_PROTOCOL_VERSION"],"sources":["../../../src/rpc/op-channel.ts","../../../src/rpc/adopt-sync-peer.ts","../../../src/rpc/local-sync-peer-handlers.ts","../../../src/rpc/admin-client.ts","../../../src/rpc/inspector-proxy.ts","../../../src/rpc/inspector-ops.ts","../../../src/rpc/live-query-proxy.ts","../../../src/rpc/relational-db-proxy.ts","../../../src/rpc/sync-manager-proxy.ts","../../../src/rpc/forwarded-events.ts","../../../src/rpc/event-bus-proxy.ts","../../../src/rpc/connect-reactor.ts","../../../src/rpc/reactor-host.ts","../../../src/rpc/worker-package-loader.ts"],"sourcesContent":["import type {\n MessageRouter,\n ClientMessage,\n OpKind,\n} from \"@powerhousedao/reactor/rpc\";\n\nexport const RPC_DEFAULT_TIMEOUT_MS = 30_000;\n\nexport function toVoid(promise: Promise<unknown>): Promise<void> {\n return promise.then(() => undefined);\n}\n\nexport interface IOpChannel {\n call(method: string, args?: unknown[]): Promise<unknown>;\n callVoid(method: string, args?: unknown[]): Promise<void>;\n}\n\nexport function opChannel(\n router: MessageRouter,\n kind: OpKind,\n timeoutMs: number = RPC_DEFAULT_TIMEOUT_MS,\n): IOpChannel {\n const call = (method: string, args: unknown[] = []): Promise<unknown> =>\n router.request((id) => ({ k: kind, id, method, args }) as ClientMessage, {\n timeoutMs,\n });\n return {\n call,\n callVoid: (method, args) => toVoid(call(method, args)),\n };\n}\n","import type { RemoteFilter } from \"@powerhousedao/reactor\";\nimport type { MessageRouter } from \"@powerhousedao/reactor/rpc\";\nimport { toVoid } from \"./op-channel.js\";\n\nexport type AdoptSyncPeerParams = {\n peerId: string;\n channelName: string;\n /** `DriveCollectionId.key`; the class does not survive structured clone. */\n collectionIdKey: string;\n remoteName: string;\n filter: RemoteFilter;\n};\n\nexport type RemoveSyncPeerParams = {\n peerId: string;\n channelName: string;\n remoteName: string;\n};\n\n/** Moves `port` to the host, which adopts the peer as a local remote over it. */\nexport function sendAdoptSyncPeer(\n router: MessageRouter,\n params: AdoptSyncPeerParams,\n port: MessagePort,\n): Promise<void> {\n return toVoid(\n router.request(\n (id) => ({\n k: \"adopt-sync-peer\",\n id,\n peerId: params.peerId,\n channelName: params.channelName,\n collectionIdKey: params.collectionIdKey,\n remoteName: params.remoteName,\n filter: params.filter,\n port,\n }),\n { transfer: [port] },\n ),\n );\n}\n\n/** Removes the peer's remote and closes its port in the host's registry. */\nexport function sendRemoveSyncPeer(\n router: MessageRouter,\n params: RemoveSyncPeerParams,\n): Promise<void> {\n return toVoid(\n router.request((id) => ({\n k: \"remove-sync-peer\",\n id,\n peerId: params.peerId,\n channelName: params.channelName,\n remoteName: params.remoteName,\n })),\n );\n}\n","import {\n collectionIdFromKey,\n messagePortTransport,\n registerLocalPeer,\n removeLocalPeer,\n type LocalChannelPortRegistry,\n type LocalPeerSyncManager,\n} from \"@powerhousedao/reactor\";\nimport type {\n AdoptSyncPeerParams,\n RemoveSyncPeerParams,\n} from \"./adopt-sync-peer.js\";\nimport type { ReactorHostOptions } from \"./reactor-host.js\";\n\n/** The host's adopt/remove handlers over the reactor's local peer registry. */\nexport function localSyncPeerHandlers(\n syncManager: LocalPeerSyncManager,\n registry: LocalChannelPortRegistry,\n): Required<Pick<ReactorHostOptions, \"onAdoptSyncPeer\" | \"onRemoveSyncPeer\">> {\n return {\n onAdoptSyncPeer: async (params: AdoptSyncPeerParams, port: MessagePort) => {\n await registerLocalPeer(\n syncManager,\n registry,\n {\n peerId: params.peerId,\n channelName: params.channelName,\n collectionId: collectionIdFromKey(params.collectionIdKey),\n remoteName: params.remoteName,\n filter: params.filter,\n },\n messagePortTransport(port),\n );\n },\n onRemoveSyncPeer: (params: RemoveSyncPeerParams) =>\n removeLocalPeer(syncManager, registry, params),\n };\n}\n","import {\n Listeners,\n type MessageRouter,\n type WorkerInspectorInfo,\n type WorkerMigrationState,\n} from \"@powerhousedao/reactor/rpc\";\nimport { RPC_DEFAULT_TIMEOUT_MS, toVoid } from \"./op-channel.js\";\n\nexport interface IWorkerAdminClient {\n info(): Promise<WorkerInspectorInfo>;\n restart(): Promise<void>;\n clearStorage(): Promise<void>;\n migrate(): Promise<void>;\n getMigrationState(): WorkerMigrationState;\n subscribeMigration(callback: () => void): () => void;\n}\n\n/** Worker lifecycle channel (info/restart/clearStorage/migrate) over the shared router. */\nexport function createWorkerAdminClient(\n router: MessageRouter,\n): IWorkerAdminClient {\n let migrationState: WorkerMigrationState = { status: \"idle\" };\n const migrationListeners = new Listeners();\n\n router.on(\"migration\", (msg) => {\n migrationState = msg.state;\n migrationListeners.emit();\n });\n\n const send = (\n method: \"info\" | \"restart\" | \"clearStorage\" | \"migrate\",\n ): Promise<unknown> =>\n router.request((id) => ({ k: \"admin\", id, method }), {\n timeoutMs: RPC_DEFAULT_TIMEOUT_MS,\n });\n\n return {\n info: () => send(\"info\") as Promise<WorkerInspectorInfo>,\n restart: () => toVoid(send(\"restart\")),\n clearStorage: () => toVoid(send(\"clearStorage\")),\n migrate: () => toVoid(send(\"migrate\")),\n getMigrationState: () => migrationState,\n subscribeMigration: (callback) => migrationListeners.add(callback),\n };\n}\n","import {\n INSPECTOR_OPS,\n type IInspector,\n type IInspectorAdmin,\n type IReactorDbQuery,\n} from \"@powerhousedao/reactor\";\nimport type { MessageRouter } from \"@powerhousedao/reactor/rpc\";\nimport { opChannel } from \"./op-channel.js\";\n\n/** `queryReactorDb` is the published name of `queryDb`. */\nexport interface IInspectorProxy\n extends IInspector, IInspectorAdmin, IReactorDbQuery {\n queryReactorDb(sql: string, params?: unknown[]): Promise<unknown[]>;\n}\n\n/** Every row of `INSPECTOR_OPS`; the host decides which tiers it serves. */\nexport function createInspectorProxy(router: MessageRouter): IInspectorProxy {\n const ops = opChannel(router, \"inspector-op\");\n const proxy: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const [key, spec] of Object.entries(INSPECTOR_OPS)) {\n proxy[key] = (...args) => ops.call(spec.rpc, args);\n }\n const queryDb = (sql: unknown, params?: unknown) =>\n ops.call(INSPECTOR_OPS.queryDb.rpc, [sql, params ?? []]);\n proxy.queryDb = queryDb;\n proxy.queryReactorDb = queryDb;\n return proxy as unknown as IInspectorProxy;\n}\n","import {\n dispatchTableOp,\n INSPECTOR_OPS,\n methodOf,\n opKeyOf,\n SYNC_INSPECTION_OPS,\n type IInspector,\n type IInspectorAdmin,\n type InspectorAccess,\n type IReactorDbQuery,\n type ISyncAdmin,\n type ISyncInspector,\n} from \"@powerhousedao/reactor\";\n\nexport type InspectorOpTargets = {\n inspector: IInspector & Partial<IInspectorAdmin>;\n dbQuery?: IReactorDbQuery;\n};\n\n/** Host side of `inspector-op`; refuses tiers `access` does not grant. */\nexport function dispatchInspectorOp(\n targets: InspectorOpTargets,\n access: InspectorAccess,\n method: string,\n args: unknown[],\n): Promise<unknown> {\n return dispatchTableOp(\n INSPECTOR_OPS,\n (key) =>\n key === \"queryDb\"\n ? methodOf(targets.dbQuery, key)\n : methodOf(targets.inspector, key),\n access,\n method,\n args,\n );\n}\n\nexport type SyncInspectionOpTargets = {\n inspector?: ISyncInspector;\n admin?: ISyncAdmin;\n};\n\n/** Whether `method` is one of the `sync-op` rows `dispatchSyncInspectionOp` serves. */\nexport function isSyncInspectionOp(method: string): boolean {\n return opKeyOf(SYNC_INSPECTION_OPS, method) !== undefined;\n}\n\n/** Host side of the inspection and repair rows of `sync-op`. */\nexport function dispatchSyncInspectionOp(\n targets: SyncInspectionOpTargets,\n access: InspectorAccess,\n method: string,\n args: unknown[],\n): Promise<unknown> {\n return dispatchTableOp(\n SYNC_INSPECTION_OPS,\n (key) =>\n SYNC_INSPECTION_OPS[key].tier === \"read\"\n ? methodOf(targets.inspector, key)\n : methodOf(targets.admin, key),\n access,\n method,\n args,\n );\n}\n","import {\n fromErrorInfo,\n type MessageRouter,\n createCorrelatedSubscriptions,\n} from \"@powerhousedao/reactor/rpc\";\n\nexport type LiveQueryResultsCallback = (results: unknown) => void;\nexport type LiveQueryErrorCallback = (error: unknown) => void;\n\nexport interface ILiveQueryProxy {\n query(\n sql: string,\n params: unknown[],\n onResults: LiveQueryResultsCallback,\n onError?: LiveQueryErrorCallback,\n ): () => void;\n}\n\ntype LiveSubscriber = {\n onResults: LiveQueryResultsCallback;\n onError?: LiveQueryErrorCallback;\n};\n\nexport function createLiveQueryProxy(router: MessageRouter): ILiveQueryProxy {\n const subs = createCorrelatedSubscriptions<\n LiveSubscriber,\n \"event-live\",\n \"live-err\"\n >(router, {\n idPrefix: \"live\",\n eventKind: \"event-live\",\n errKind: \"live-err\",\n onEvent: (sub, msg) => sub.onResults(msg.results),\n onError: (sub, msg) => sub.onError?.(fromErrorInfo(msg.error)),\n close: (id) => ({ k: \"unsub-live\", id }),\n });\n\n return {\n query(sql, params, onResults, onError) {\n return subs.subscribe({ onResults, onError }, (id) => ({\n k: \"sub-live\",\n id,\n sql,\n params,\n }));\n },\n };\n}\n","import type { PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport { createLiveQueryProxy } from \"./live-query-proxy.js\";\nimport type { MessageRouter } from \"@powerhousedao/reactor/rpc\";\nimport { opChannel } from \"./op-channel.js\";\n\nexport function createRelationalPgliteProxy(\n router: MessageRouter,\n): PGliteWithLive {\n const ops = opChannel(router, \"db-op\");\n const liveProxy = createLiveQueryProxy(router);\n\n const proxy = {\n query: async (sql: string, params?: unknown[]) => {\n const rows = await ops.call(\"query\", [sql, params ?? []]);\n return { rows };\n },\n live: {\n query: (\n sql: string,\n params: unknown[] | null | undefined,\n callback?: (results: unknown) => void,\n ) =>\n new Promise((resolve, reject) => {\n // Settle on the first result/error so a subscribe failure reaches the caller's retry path.\n let settled = false;\n const unsubscribe = liveProxy.query(\n sql,\n params ?? [],\n (results) => {\n if (!settled) {\n settled = true;\n resolve({ unsubscribe });\n }\n callback?.(results);\n },\n (error) => {\n if (!settled) {\n settled = true;\n reject(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n },\n );\n }),\n },\n };\n\n return proxy as unknown as PGliteWithLive;\n}\n","import type { PeerManifest } from \"@powerhousedao/shared/document-model\";\nimport {\n createPeerAgreement,\n DriveCollectionId,\n SYNC_INSPECTION_OPS,\n SyncEventTypes,\n type DeadLetterPage,\n type ISyncAdmin,\n type ISyncInspector,\n type RemoteSyncInspection,\n type SyncInspectionOpKey,\n type ChannelConfig,\n type ConnectionStateChangeCallback,\n type ConnectionStateChangedEvent,\n type ConnectionStateSnapshot,\n type IChannel,\n type IEventBus,\n type IMailbox,\n type IPeerAgreement,\n type PeerAgreementBasis,\n type ISyncManager,\n type Remote,\n type RemoteFilter,\n type RemoteMeta,\n type RemoteOptions,\n type RemotePeer,\n type ShutdownStatus,\n type SyncHold,\n type SyncOperation,\n type SyncStatus,\n type SyncStatusChangeCallback,\n} from \"@powerhousedao/reactor\";\nimport {\n KeyedListeners,\n Listeners,\n type MessageRouter,\n} from \"@powerhousedao/reactor/rpc\";\nimport { opChannel, type IOpChannel } from \"./op-channel.js\";\n\n// Synthetic bus channel id for sync-status deltas (not a reactor IEventBus type).\nexport const SYNC_STATUS_CHANGED_EVENT = 90001;\n\nexport type SyncStatusChangedBusEvent = {\n documentId: string;\n status: SyncStatus;\n};\n\nconst SEED_MAX_ATTEMPTS = 3;\nconst SEED_RETRY_DELAY_MS = 500;\n\n// Wire shapes: DriveCollectionId arrives prototype-less over postMessage.\ntype WireDriveCollectionId = { driveId: string; branch: string };\ntype WireRemoteMeta = {\n id: string;\n name: string;\n collectionId: WireDriveCollectionId;\n channelConfig: ChannelConfig;\n filter: RemoteFilter;\n options: RemoteOptions;\n peer?: RemotePeer;\n};\ntype WireRemote = {\n meta: WireRemoteMeta;\n connectionState: ConnectionStateSnapshot;\n};\n\nconst DEFAULT_SNAPSHOT: ConnectionStateSnapshot = {\n state: \"connecting\",\n failureCount: 0,\n lastSuccessUtcMs: 0,\n lastFailureUtcMs: 0,\n pushBlocked: false,\n pushFailureCount: 0,\n receivingPages: false,\n requiresAuth: false,\n};\n\n// Inert mailbox: a proxy remote carries no live sync operations tab-side.\nclass NoopMailbox implements IMailbox {\n get items(): readonly SyncOperation[] {\n return [];\n }\n get ackOrdinal(): number {\n return 0;\n }\n get latestOrdinal(): number {\n return 0;\n }\n init(): void {}\n advanceOrdinal(): void {}\n get(): undefined {\n return undefined;\n }\n add(): void {}\n remove(): void {}\n onAdded(): void {}\n onRemoved(): void {}\n pause(): void {}\n resume(): void {}\n flush(): void {}\n isPaused(): boolean {\n return false;\n }\n}\n\nconst NOOP_MAILBOX = new NoopMailbox();\n\nfunction rehydrateMeta(wire: WireRemoteMeta): RemoteMeta {\n return {\n id: wire.id,\n name: wire.name,\n collectionId: DriveCollectionId.forDrive(\n wire.collectionId.driveId,\n wire.collectionId.branch,\n ),\n channelConfig: wire.channelConfig,\n filter: wire.filter,\n options: wire.options,\n peer: wire.peer,\n };\n}\n\nfunction channelUrl(meta: RemoteMeta): string | undefined {\n const url = meta.channelConfig.parameters.url;\n return typeof url === \"string\" ? url : undefined;\n}\n\n// Tab-side ISyncManager: cache-backed reads fed by the bus, ops over sync-op RPC.\nexport class SyncManagerProxy\n implements ISyncManager, ISyncInspector, ISyncAdmin\n{\n private readonly ops: IOpChannel;\n private readonly connectionStates = new Map<\n string,\n ConnectionStateSnapshot\n >();\n private readonly connectionListeners = new KeyedListeners<string>();\n private readonly syncStatuses = new Map<string, SyncStatus>();\n private readonly syncStatusListeners = new Listeners<[string, SyncStatus]>();\n private remotes: Remote[] = [];\n private basis: PeerAgreementBasis | undefined;\n private seedPromise: Promise<void> | null = null;\n\n constructor(router: MessageRouter, busProxy: IEventBus) {\n this.ops = opChannel(router, \"sync-op\");\n\n busProxy.subscribe(\n SyncEventTypes.CONNECTION_STATE_CHANGED,\n (_type, event) => {\n const e = event as ConnectionStateChangedEvent;\n this.connectionStates.set(e.remoteName, e.snapshot);\n this.notifyConnection(e.remoteName);\n },\n );\n\n busProxy.subscribe(SYNC_STATUS_CHANGED_EVENT, (_type, event) => {\n const e = event as SyncStatusChangedBusEvent;\n this.syncStatuses.set(e.documentId, e.status);\n this.syncStatusListeners.emit(e.documentId, e.status);\n });\n\n void this.ensureSeeded();\n }\n\n /** Attempts that fail while `isWaiting()` (the worker waits on a store lock) are not counted. */\n async startup({\n isWaiting = () => false,\n }: { isWaiting?: () => boolean } = {}): Promise<void> {\n let failures = 0;\n for (;;) {\n try {\n await this.ensureSeeded();\n return;\n } catch (error) {\n if (!isWaiting()) failures++;\n if (failures >= SEED_MAX_ATTEMPTS) throw error;\n await new Promise((resolve) =>\n setTimeout(resolve, SEED_RETRY_DELAY_MS),\n );\n }\n }\n }\n\n shutdown(): ShutdownStatus {\n return { isShutdown: true, completed: Promise.resolve() };\n }\n\n getByName(name: string): Remote {\n const remote = this.remotes.find((r) => r.meta.name === name);\n if (!remote) {\n throw new Error(`Unknown remote: ${name}`);\n }\n return remote;\n }\n\n getById(id: string): Remote {\n const remote = this.remotes.find((r) => r.meta.id === id);\n if (!remote) {\n throw new Error(`Unknown remote id: ${id}`);\n }\n return remote;\n }\n\n async add(\n name: string,\n collectionId: DriveCollectionId,\n channelConfig: ChannelConfig,\n filter?: RemoteFilter,\n options?: RemoteOptions,\n ): Promise<Remote> {\n await this.callSyncOp(\"add\", [\n name,\n collectionId.key,\n channelConfig,\n filter,\n options,\n ]);\n await this.refreshRemotes();\n return this.getByName(name);\n }\n\n async setPeerManifest(\n id: string,\n manifest: PeerManifest | null,\n ): Promise<void> {\n await this.callSyncOp(\"setPeerManifest\", [id, manifest]);\n await this.refreshRemotes();\n }\n\n /** Fetched once; the worker's flags do not change at runtime. */\n localManifest(): PeerManifest {\n return this.agreementBasis().local;\n }\n\n async listHolds(filter?: {\n remoteName?: string;\n documentId?: string;\n }): Promise<SyncHold[]> {\n return (await this.callSyncOp(\"listHolds\", [filter])) as SyncHold[];\n }\n\n agreement(): IPeerAgreement {\n return createPeerAgreement(\n this.agreementBasis(),\n this.remotes.map((remote) => remote.meta),\n );\n }\n\n private agreementBasis(): PeerAgreementBasis {\n if (!this.basis) {\n throw new Error(\n \"Peer agreement has not been fetched from the worker yet\",\n );\n }\n return this.basis;\n }\n\n async bindRemote(id: string, boundAddress: string): Promise<void> {\n await this.callSyncOp(\"bindRemote\", [id, boundAddress]);\n await this.refreshRemotes();\n }\n\n triggerPull(name: string): void {\n this.callSyncOp(\"triggerPull\", [name]).catch((error: unknown) => {\n console.error(`triggerPull failed for remote \"${name}\":`, error);\n });\n }\n\n async remove(name: string): Promise<void> {\n await this.callSyncOp(\"remove\", [name]);\n await this.refreshRemotes();\n }\n\n list(): Remote[] {\n return [...this.remotes];\n }\n\n waitForSync(): Promise<never> {\n return Promise.reject(\n new Error(\"waitForSync is not supported over the worker RPC boundary\"),\n );\n }\n\n getSyncStatus(documentId: string): SyncStatus | undefined {\n return this.syncStatuses.get(documentId);\n }\n\n onSyncStatusChange(callback: SyncStatusChangeCallback): () => void {\n return this.syncStatusListeners.add(callback);\n }\n\n async inspectRemote(remoteName: string): Promise<RemoteSyncInspection> {\n return (await this.tableOp(\"inspectRemote\", [\n remoteName,\n ])) as RemoteSyncInspection;\n }\n\n async inspectRemotes(): Promise<RemoteSyncInspection[]> {\n return (await this.tableOp(\"inspectRemotes\", [])) as RemoteSyncInspection[];\n }\n\n async listDeadLetters(\n remoteName: string,\n cursor?: string,\n limit?: number,\n ): Promise<DeadLetterPage> {\n return (await this.tableOp(\"listDeadLetters\", [\n remoteName,\n cursor,\n limit,\n ])) as DeadLetterPage;\n }\n\n async resetChannel(remoteName: string): Promise<void> {\n await this.tableOp(\"resetChannel\", [remoteName]);\n }\n\n async requeueDeadLetter(remoteName: string, id: string): Promise<void> {\n await this.tableOp(\"requeueDeadLetter\", [remoteName, id]);\n }\n\n async clearDeadLetter(remoteName: string, id: string): Promise<void> {\n await this.tableOp(\"clearDeadLetter\", [remoteName, id]);\n }\n\n private tableOp(key: SyncInspectionOpKey, args: unknown[]): Promise<unknown> {\n return this.ops.call(SYNC_INSPECTION_OPS[key].rpc, args);\n }\n\n private callSyncOp(method: string, args: unknown[]): Promise<unknown> {\n return this.ops.call(method, args);\n }\n\n private notifyConnection(remoteName?: string): void {\n if (remoteName !== undefined) {\n this.connectionListeners.emit(remoteName);\n return;\n }\n this.connectionListeners.emitAll();\n }\n\n private makeChannel(remoteName: string, url: string | undefined): IChannel {\n const channel: IChannel & { config: { url?: string } } = {\n inbox: NOOP_MAILBOX,\n outbox: NOOP_MAILBOX,\n deadLetter: NOOP_MAILBOX,\n init: () => Promise.resolve(),\n shutdown: () => Promise.resolve(),\n getConnectionState: () =>\n this.connectionStates.get(remoteName) ?? DEFAULT_SNAPSHOT,\n onConnectionStateChange: (callback: ConnectionStateChangeCallback) => {\n const listener = () =>\n callback(this.connectionStates.get(remoteName) ?? DEFAULT_SNAPSHOT);\n return this.connectionListeners.add(remoteName, listener);\n },\n\n triggerPull: () => {\n this.callSyncOp(\"triggerPull\", [remoteName]).catch((error: unknown) => {\n console.error(\n `triggerPull failed for remote \"${remoteName}\":`,\n error,\n );\n });\n },\n notePoll: () => {},\n lastHolderPollUtcMs: () => undefined,\n setLocalManifest: () => {},\n onPeerManifest: () => () => {},\n config: { url },\n };\n return channel;\n }\n\n private async refreshRemotes(): Promise<void> {\n const wire = (await this.callSyncOp(\"list\", [])) as WireRemote[];\n const names = new Set<string>();\n this.remotes = wire.map((w) => {\n const meta = rehydrateMeta(w.meta);\n names.add(meta.name);\n if (!this.connectionStates.has(meta.name)) {\n this.connectionStates.set(meta.name, w.connectionState);\n }\n return { meta, channel: this.makeChannel(meta.name, channelUrl(meta)) };\n });\n for (const name of [...this.connectionStates.keys()]) {\n if (!names.has(name)) {\n this.connectionStates.delete(name);\n }\n }\n this.notifyConnection();\n }\n\n // Shared in-flight seed so the eager kick-off and startup() share one list RPC.\n private ensureSeeded(): Promise<void> {\n if (!this.basis) {\n this.callSyncOp(\"peerAgreementBasis\", [])\n .then((basis) => {\n this.basis = basis as PeerAgreementBasis;\n })\n .catch(() => {});\n }\n if (!this.seedPromise) {\n const pending = this.refreshRemotes();\n this.seedPromise = pending;\n\n pending.catch(() => {\n if (this.seedPromise === pending) {\n this.seedPromise = null;\n }\n });\n }\n return this.seedPromise;\n }\n}\n\nexport function createSyncManagerProxy(\n router: MessageRouter,\n busProxy: IEventBus,\n): ISyncManager {\n return new SyncManagerProxy(router, busProxy);\n}\n","import { ReactorEventTypes, SyncEventTypes } from \"@powerhousedao/reactor\";\nimport { SYNC_STATUS_CHANGED_EVENT } from \"./sync-manager-proxy.js\";\n\nexport const FORWARDED_EVENT_TYPES = [\n SyncEventTypes.SYNC_PENDING,\n SyncEventTypes.SYNC_SUCCEEDED,\n SyncEventTypes.SYNC_FAILED,\n SyncEventTypes.DEAD_LETTER_ADDED,\n SyncEventTypes.CONNECTION_STATE_CHANGED,\n ReactorEventTypes.MODEL_LOADED,\n];\n\nexport const FORWARDED_BUS_EVENT_TYPES: number[] = [\n ...FORWARDED_EVENT_TYPES,\n SYNC_STATUS_CHANGED_EVENT,\n];\n","import type { IEventBus, Unsubscribe } from \"@powerhousedao/reactor\";\nimport { FORWARDED_BUS_EVENT_TYPES } from \"./forwarded-events.js\";\nimport { KeyedListeners, type MessageRouter } from \"@powerhousedao/reactor/rpc\";\n\ntype BusSubscriber = (type: number, event: unknown) => void | Promise<void>;\n\n/** Tab-side IEventBus over bus-event; emit() is unsupported (the worker emits). */\nexport class ReactorEventBusProxy implements IEventBus {\n private readonly forwardedTypes = new Set<number>(FORWARDED_BUS_EVENT_TYPES);\n private readonly subscribers = new KeyedListeners<\n number,\n [number, unknown]\n >();\n\n constructor(router: MessageRouter) {\n router.on(\"bus-event\", (msg) => {\n this.subscribers.emit(msg.eventType, msg.eventType, msg.event);\n });\n }\n\n subscribe<K>(\n type: number,\n subscriber: (type: number, event: K) => void | Promise<void>,\n ): Unsubscribe {\n if (!this.forwardedTypes.has(type)) {\n throw new Error(\n `ReactorEventBusProxy cannot subscribe to event type ${type}: the worker forwards only [${[...this.forwardedTypes].join(\", \")}]`,\n );\n }\n const entry = subscriber as BusSubscriber;\n return this.subscribers.add(\n type,\n entry as (eventType: number, event: unknown) => void,\n );\n }\n\n emit(): Promise<void> {\n return Promise.reject(\n new Error(\n \"EventBus.emit is not supported tab-side; the reactor graph emits in the worker\",\n ),\n );\n }\n}\n\nexport function createReactorEventBusProxy(router: MessageRouter): IEventBus {\n return new ReactorEventBusProxy(router);\n}\n","import type {\n IDocumentModelRegistry,\n IReactorClient,\n} from \"@powerhousedao/reactor\";\nimport {\n createReactorClientProxy,\n type MessageRouter,\n type ReactorIdentity,\n type VersionFingerprint,\n} from \"@powerhousedao/reactor/rpc\";\n\nexport type ReactorHello = {\n version: VersionFingerprint;\n construct?: unknown;\n packages?: string[];\n};\n\nexport function connectReactorClient(\n router: MessageRouter,\n hello: ReactorHello,\n onReload?: (reason: string, workerGen?: string) => void,\n registry?: IDocumentModelRegistry,\n): IReactorClient {\n const client = createReactorClientProxy(router, { onReload, registry });\n router.post({\n k: \"hello\",\n id: \"hello\",\n version: hello.version,\n construct: hello.construct,\n packages: hello.packages,\n });\n return client;\n}\n\n// Push the current renown identity (null on logout) to the worker; re-send on login/logout.\nexport function postReactorIdentity(\n router: MessageRouter,\n user: ReactorIdentity | null,\n): void {\n router.post({ k: \"identity\", user });\n}\n","import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport type {\n AdoptSyncPeerParams,\n RemoveSyncPeerParams,\n} from \"./adopt-sync-peer.js\";\nimport {\n hostResponder,\n type IHostResponder,\n ReactorHostServer,\n SubscriptionStore,\n type ClientMessage,\n type CorrelationId,\n type ReactorIdentity,\n type RpcAdmin,\n type RpcAdoptSyncPeer,\n type RpcDbOp,\n type RpcHello,\n type RpcInspectorOp,\n type RpcLiveSubscribe,\n type RpcRegisterPackages,\n type RpcRemoveSyncPeer,\n type RpcSyncOp,\n type RpcUnregisterPackages,\n type VersionFingerprint,\n type WorkerInspectorInfo,\n type WorkerMigrationState,\n type WorkerPackageSource,\n RPC_PROTOCOL_VERSION,\n createPortTransport,\n type IRpcTransport,\n} from \"@powerhousedao/reactor/rpc\";\n\nfunction isDataMessage(\n msg: ClientMessage,\n): msg is ClientMessage & { id: CorrelationId } {\n return (\n msg.k === \"req\" ||\n msg.k === \"sub\" ||\n msg.k === \"page\" ||\n msg.k === \"sync-op\" ||\n msg.k === \"db-op\" ||\n msg.k === \"inspector-op\" ||\n msg.k === \"adopt-sync-peer\" ||\n msg.k === \"remove-sync-peer\" ||\n msg.k === \"sub-live\"\n );\n}\n\n/** A rejected adopt still owns the port it moved here, so close it. */\nfunction closeTransferredPort(msg: ClientMessage): void {\n if (msg.k === \"adopt-sync-peer\") msg.port.close();\n}\n\nexport type ReactorHostOptions = {\n client?: IReactorClient;\n build?: (construct: unknown) => Promise<IReactorClient>;\n registerPackages?: (\n specs: string[],\n sources?: WorkerPackageSource[],\n ) => Promise<void>;\n unregisterPackages?: (names: string[]) => Promise<void>;\n onIdentity?: (user: ReactorIdentity | null) => void;\n onSyncOp?: (method: string, args: unknown[]) => Promise<unknown>;\n onDbOp?: (method: string, args: unknown[]) => Promise<unknown>;\n onInspectorOp?: (method: string, args: unknown[]) => Promise<unknown>;\n /** See `localSyncPeerHandlers`, which builds both over the reactor's registry. */\n onAdoptSyncPeer?: (\n params: AdoptSyncPeerParams,\n port: MessagePort,\n ) => Promise<void>;\n onRemoveSyncPeer?: (params: RemoveSyncPeerParams) => Promise<void>;\n onLiveQuery?: (\n sql: string,\n params: unknown[],\n onResults: (results: unknown) => void,\n ) => Promise<() => void>;\n // Worker identity + restart for the admin/inspector channel.\n namespace?: string;\n appBuildId?: string;\n ownerId?: string;\n bootedAtMs?: number;\n onAdminRestart?: () => void;\n onAdminClearStorage?: () => Promise<void>;\n onAdminMigrate?: () => Promise<void>;\n /** Stops the reactor and releases its stores once the worker is retired. */\n onRetire?: (reason: string) => Promise<void>;\n /** Bounded; a deploy's reload waits on it while data is already refused. */\n drainBeforeReload?: () => Promise<void>;\n};\n\nfunction versionsCompatible(\n a: VersionFingerprint,\n b: VersionFingerprint,\n): boolean {\n return (\n a.appBuildId === b.appBuildId &&\n a.rpcProtocolVersion === b.rpcProtocolVersion &&\n (a.featureFlags ?? \"\") === (b.featureFlags ?? \"\")\n );\n}\n\n// Deterministic per version so every new-build tab converges on one fresh\n// worker; the flags are in it so a flag-only change lands on a fresh one too.\nfunction workerGenForVersion(version: VersionFingerprint): string {\n const flags = version.featureFlags ?? \"\";\n const suffix = flags === \"\" ? \"\" : `-${hashFlags(flags)}`;\n return `v${version.rpcProtocolVersion}-${version.appBuildId}${suffix}`;\n}\n\nconst VERSION_MISMATCH = \"reactor version mismatch\";\nconst FLAGS_CHANGED = \"reactor enforcement flags changed\";\n\n/** Whether a reload reason comes from a build fingerprint mismatch. */\nexport function isFingerprintMismatchReload(reason: string): boolean {\n return reason === VERSION_MISMATCH || reason.startsWith(FLAGS_CHANGED);\n}\n\n/** Names what differs, so a reload is diagnosable from the tab's console. */\nfunction mismatchReason(\n baseline: VersionFingerprint,\n incoming: VersionFingerprint,\n): string {\n if ((baseline.featureFlags ?? \"\") !== (incoming.featureFlags ?? \"\")) {\n return `${FLAGS_CHANGED} (worker: ${\n baseline.featureFlags || \"none\"\n }, tab: ${incoming.featureFlags || \"none\"})`;\n }\n return VERSION_MISMATCH;\n}\n\n// Worker names end up in devtools and IndexedDB keys, so the flag set is\n// reduced to a short stable token rather than spelled out.\nfunction hashFlags(flags: string): string {\n let hash = 0;\n for (let i = 0; i < flags.length; i++) {\n hash = (hash * 31 + flags.charCodeAt(i)) | 0;\n }\n return (hash >>> 0).toString(36);\n}\n\nexport const RETIRED_WORKER_RELOAD_REASON = \"worker retired\";\n\nfunction retiredError(): Error {\n return new Error(\"This worker was retired; reloading into the current one\");\n}\n\nexport class ReactorHost {\n private readonly options: ReactorHostOptions;\n private readonly disposers = new Set<() => void>();\n private readonly clients = new Set<IRpcTransport>();\n private clientPromise: Promise<IReactorClient> | null = null;\n // Ops after a failed build get its error until a hello rebuilds.\n private buildFailure: { error: unknown } | null = null;\n private baseline: VersionFingerprint | null = null;\n private readonly ownerId: string;\n private readonly bootedAtMs: number;\n private migrationState: WorkerMigrationState | null = null;\n private retirement: { reason: string; workerGen: string } | null = null;\n private reloadSent = false;\n\n constructor(options: ReactorHostOptions) {\n this.options = options;\n this.ownerId = options.ownerId ?? crypto.randomUUID();\n this.bootedAtMs = options.bootedAtMs ?? Date.now();\n if (options.client) {\n this.clientPromise = Promise.resolve(options.client);\n }\n }\n\n connect(transport: IRpcTransport): () => void {\n let server: ReactorHostServer | null = null;\n let ready = false;\n const buffer: ClientMessage[] = [];\n const liveSubs = new SubscriptionStore();\n const reply = hostResponder(transport);\n\n const ensureServer = async (construct?: unknown): Promise<void> => {\n if (server) {\n return;\n }\n const client = await this.resolveClient(construct);\n server = new ReactorHostServer(client, transport);\n };\n\n // Drain only after init (server + package registration) completes, in order.\n // Messages arriving mid-drain stay buffered (ready flips last) so order holds.\n const drainBuffer = async (): Promise<void> => {\n while (buffer.length > 0) {\n const message = buffer.shift()!;\n await server!.handleMessage(message);\n }\n ready = true;\n };\n\n const detach = transport.onMessage((message) => {\n const msg = message as ClientMessage;\n if (msg.k === \"ping\") {\n transport.post({\n k: \"pong\",\n id: msg.id,\n ownerId: this.ownerId,\n bootedAtMs: this.bootedAtMs,\n });\n return;\n }\n if (this.migrationState?.status === \"migrating\" && isDataMessage(msg)) {\n // Route the rejection to the kind's owner (sub -> sub-err, etc.).\n closeTransferredPort(msg);\n reply.errForKind(msg, new Error(\"migration in progress\"));\n return;\n }\n // No reload here: a tab past its poisoned-store budget stays put on purpose.\n if (this.retirement && isDataMessage(msg)) {\n closeTransferredPort(msg);\n reply.errForKind(msg, retiredError());\n return;\n }\n if (msg.k === \"hello\") {\n void this.handleHello(msg, transport, reply, ensureServer, drainBuffer);\n return;\n }\n if (msg.k === \"register-packages\") {\n void this.handleRegister(msg, reply);\n return;\n }\n if (msg.k === \"unregister-packages\") {\n void this.handleUnregister(msg, reply);\n return;\n }\n if (msg.k === \"identity\") {\n this.options.onIdentity?.(msg.user);\n return;\n }\n if (msg.k === \"sync-op\") {\n void this.handleOp(msg, this.options.onSyncOp, \"sync\", reply);\n return;\n }\n if (msg.k === \"db-op\") {\n void this.handleOp(msg, this.options.onDbOp, \"db\", reply);\n return;\n }\n if (msg.k === \"inspector-op\") {\n void this.handleOp(msg, this.options.onInspectorOp, \"inspector\", reply);\n return;\n }\n if (msg.k === \"adopt-sync-peer\") {\n void this.handleAdoptSyncPeer(msg, reply);\n return;\n }\n if (msg.k === \"remove-sync-peer\") {\n void this.handleRemoveSyncPeer(msg, reply);\n return;\n }\n if (msg.k === \"sub-live\") {\n void this.handleLiveSubscribe(msg, transport, reply, liveSubs);\n return;\n }\n if (msg.k === \"unsub-live\") {\n liveSubs.end(msg.id);\n return;\n }\n if (msg.k === \"admin\") {\n this.handleAdmin(msg, reply, transport);\n return;\n }\n if (ready && server) {\n void server.handleMessage(msg);\n } else {\n buffer.push(msg);\n }\n });\n\n this.clients.add(transport);\n if (this.migrationState) {\n transport.post({ k: \"migration\", state: this.migrationState });\n }\n // Mid-drain it waits for the broadcast, which reaches it too.\n if (this.retirement && this.reloadSent) {\n transport.post({ k: \"reload\", ...this.retirement });\n }\n if (this.options.client) {\n void ensureServer()\n .then(drainBuffer)\n .catch((error) => {\n console.error(\"ReactorHost buffer drain failed\", error);\n });\n }\n\n const dispose = () => {\n server?.stop();\n detach();\n liveSubs.drain();\n this.clients.delete(transport);\n this.disposers.delete(dispose);\n };\n this.disposers.add(dispose);\n return dispose;\n }\n\n connectPort(port: MessagePort): () => void {\n return this.connect(createPortTransport(port));\n }\n\n // Fan out a reactor bus event to every connected tab, fire-and-forget.\n broadcastBusEvent(eventType: number, event: unknown): void {\n for (const transport of this.clients) {\n transport.post({ k: \"bus-event\", eventType, event });\n }\n }\n\n // Tell every connected tab to reload; `workerGen` makes them adopt one fresh worker name.\n broadcastReload(reason: string, workerGen?: string): void {\n for (const transport of this.clients) {\n transport.post({ k: \"reload\", reason, workerGen });\n }\n }\n\n // A reload this worker never recovers from; tabs that connect later get it too.\n // A deploy's reload waits for the drain: the tabs keep the worker alive.\n retireAndReload(reason: string, workerGen: string): void {\n if (this.retirement) {\n return;\n }\n this.retirement = { reason, workerGen };\n const drain = this.options.drainBeforeReload;\n if (!drain || !isFingerprintMismatchReload(reason)) {\n this.sendReload(reason, workerGen);\n return;\n }\n void this.drainThenReload(drain, reason, workerGen);\n }\n\n private async drainThenReload(\n drain: () => Promise<void>,\n reason: string,\n workerGen: string,\n ): Promise<void> {\n try {\n await drain();\n } catch (error) {\n console.error(\"ReactorHost drain before reload failed\", error);\n }\n this.sendReload(reason, workerGen);\n }\n\n private sendReload(reason: string, workerGen: string): void {\n this.reloadSent = true;\n this.broadcastReload(reason, workerGen);\n this.stopRetired(reason);\n }\n\n private stopRetired(reason: string): void {\n this.options.onRetire?.(reason).catch((error: unknown) => {\n console.error(\"ReactorHost retirement cleanup failed\", error);\n });\n }\n\n // Cache + fan out the worker's migration state so tabs drive the banner from it.\n setMigrationState(state: WorkerMigrationState): void {\n this.migrationState = state;\n for (const transport of this.clients) {\n transport.post({ k: \"migration\", state });\n }\n }\n\n get retired(): boolean {\n return this.retirement !== null;\n }\n\n get connectionCount(): number {\n return this.disposers.size;\n }\n\n private handleAdmin(\n message: RpcAdmin,\n reply: IHostResponder,\n transport: IRpcTransport,\n ): void {\n // A retired worker no longer owns the store: send the tab to the one that does.\n if (this.retirement && message.method !== \"info\") {\n if (this.reloadSent) {\n transport.post({\n k: \"reload\",\n reason: RETIRED_WORKER_RELOAD_REASON,\n workerGen: this.retirement.workerGen,\n });\n }\n reply.err(message.id, retiredError());\n return;\n }\n if (message.method === \"restart\") {\n this.options.onAdminRestart?.();\n reply.ok(message.id);\n return;\n }\n if (message.method === \"clearStorage\") {\n void this.handleAdminAsync(\n this.options.onAdminClearStorage,\n message,\n reply,\n );\n return;\n }\n if (message.method === \"migrate\") {\n void this.handleAdminAsync(this.options.onAdminMigrate, message, reply);\n return;\n }\n const info: WorkerInspectorInfo = {\n namespace: this.options.namespace ?? \"\",\n ownerId: this.ownerId,\n bootedAtMs: this.bootedAtMs,\n connectedClients: this.connectionCount,\n appBuildId:\n this.baseline?.appBuildId ?? this.options.appBuildId ?? \"unknown\",\n rpcProtocolVersion:\n this.baseline?.rpcProtocolVersion ?? RPC_PROTOCOL_VERSION,\n featureFlags: this.baseline?.featureFlags ?? \"\",\n };\n reply.ok(message.id, info);\n }\n\n private async handleAdminAsync(\n handler: (() => Promise<void>) | undefined,\n message: RpcAdmin,\n reply: IHostResponder,\n ): Promise<void> {\n await reply.run(message.id, async () => {\n await handler?.();\n });\n }\n\n private resolveClient(construct?: unknown): Promise<IReactorClient> {\n // A retired worker's client may sit on stopped stores.\n if (this.retirement) {\n return Promise.reject(retiredError());\n }\n if (!this.clientPromise) {\n const build = this.options.build;\n if (!build) {\n return Promise.reject(\n new Error(\"ReactorHost has no client or builder\"),\n );\n }\n const pending = build(construct);\n this.clientPromise = pending;\n this.buildFailure = null;\n // A build outliving the retirement holds stores onRetire left to it.\n void pending.then(\n () => {\n // Mid-drain, the reload's own stop comes after.\n if (this.retirement && this.reloadSent) {\n this.stopRetired(this.retirement.reason);\n }\n },\n () => undefined,\n );\n pending.catch((error: unknown) => {\n if (this.clientPromise === pending) {\n this.clientPromise = null;\n this.buildFailure = { error };\n }\n });\n }\n return this.clientPromise;\n }\n\n private async awaitClientReady(): Promise<void> {\n if (this.clientPromise) {\n await this.clientPromise;\n return;\n }\n if (this.buildFailure) {\n throw this.buildFailure.error;\n }\n }\n\n private requireHandler<T>(\n handler: T | undefined,\n message: ClientMessage,\n reply: IHostResponder,\n label: string,\n ): handler is T {\n if (handler) {\n return true;\n }\n reply.errForKind(message, new Error(`ReactorHost has no ${label} handler`));\n return false;\n }\n\n // A mismatch retires the worker for good: every tab reloads onto one gen.\n private async handleHello(\n message: RpcHello,\n transport: IRpcTransport,\n reply: IHostResponder,\n ensureServer: (construct?: unknown) => Promise<void>,\n drainBuffer: () => Promise<void>,\n ): Promise<void> {\n if (this.baseline) {\n if (!versionsCompatible(this.baseline, message.version)) {\n // Salted per instance: the bare gen can be this worker's own name.\n this.retireAndReload(\n mismatchReason(this.baseline, message.version),\n `${workerGenForVersion(message.version)}-${this.ownerId.slice(0, 8)}`,\n );\n reply.ok(message.id, { ok: false });\n return;\n }\n } else {\n this.baseline = message.version;\n }\n await reply.run(message.id, async () => {\n await ensureServer(message.construct);\n if (message.packages && message.packages.length > 0) {\n await this.options.registerPackages?.(message.packages);\n }\n // Packages are registered; replay buffered data messages in order.\n await drainBuffer();\n });\n }\n\n private async handleRegister(\n message: RpcRegisterPackages,\n reply: IHostResponder,\n ): Promise<void> {\n await reply.run(message.id, async () => {\n await this.options.registerPackages?.(message.specs, message.sources);\n });\n }\n\n private async handleUnregister(\n message: RpcUnregisterPackages,\n reply: IHostResponder,\n ): Promise<void> {\n await reply.run(message.id, async () => {\n await this.options.unregisterPackages?.(message.names);\n });\n }\n\n private async handleOp(\n message: RpcSyncOp | RpcDbOp | RpcInspectorOp,\n handler:\n | ((method: string, args: unknown[]) => Promise<unknown>)\n | undefined,\n label: string,\n reply: IHostResponder,\n ): Promise<void> {\n if (!this.requireHandler(handler, message, reply, label)) {\n return;\n }\n await reply.run(\n message.id,\n async () => {\n await this.awaitClientReady();\n return handler(message.method, message.args);\n },\n (value) => value,\n );\n }\n\n /** Closes the moved port on every failure; the sender can no longer close it. */\n private async handleAdoptSyncPeer(\n message: RpcAdoptSyncPeer,\n reply: IHostResponder,\n ): Promise<void> {\n const handler = this.options.onAdoptSyncPeer;\n if (!handler) {\n closeTransferredPort(message);\n reply.errForKind(\n message,\n new Error(\"ReactorHost has no adopt-sync-peer handler\"),\n );\n return;\n }\n await reply.run(message.id, async () => {\n try {\n await this.awaitClientReady();\n await handler(\n {\n peerId: message.peerId,\n channelName: message.channelName,\n collectionIdKey: message.collectionIdKey,\n remoteName: message.remoteName,\n filter: message.filter,\n },\n message.port,\n );\n } catch (error) {\n closeTransferredPort(message);\n throw error;\n }\n });\n }\n\n private async handleRemoveSyncPeer(\n message: RpcRemoveSyncPeer,\n reply: IHostResponder,\n ): Promise<void> {\n const handler = this.options.onRemoveSyncPeer;\n if (!this.requireHandler(handler, message, reply, \"remove-sync-peer\")) {\n return;\n }\n await reply.run(message.id, async () => {\n await this.awaitClientReady();\n await handler({\n peerId: message.peerId,\n channelName: message.channelName,\n remoteName: message.remoteName,\n });\n });\n }\n\n private async handleLiveSubscribe(\n message: RpcLiveSubscribe,\n transport: IRpcTransport,\n reply: IHostResponder,\n liveSubs: SubscriptionStore,\n ): Promise<void> {\n const handler = this.options.onLiveQuery;\n if (!this.requireHandler(handler, message, reply, \"live-query\")) {\n return;\n }\n const placeholder = () => undefined;\n liveSubs.set(message.id, placeholder);\n try {\n await this.awaitClientReady();\n const unsubscribe = await handler(\n message.sql,\n message.params,\n (results) => {\n transport.post({ k: \"event-live\", id: message.id, results });\n },\n );\n // unsub-live raced ahead during the await: tear down, don't leak.\n if (liveSubs.get(message.id) !== placeholder) {\n unsubscribe();\n return;\n }\n liveSubs.set(message.id, unsubscribe);\n } catch (error) {\n if (liveSubs.get(message.id) === placeholder) {\n liveSubs.delete(message.id);\n }\n reply.errForKind(message, error);\n }\n }\n}\n","import type { IDocumentModelLoader } from \"@powerhousedao/reactor\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { rewritePackageSource } from \"@powerhousedao/shared/connect\";\nimport { RegistryClient } from \"../registry/client.js\";\nimport type { WorkerPackageSource } from \"@powerhousedao/reactor/rpc\";\n\nexport type PackageImporter = (url: string) => Promise<Record<string, unknown>>;\n\nexport type WorkerPackageLoaderOptions = {\n cdnUrl: string;\n importPackage: PackageImporter;\n resolvePackages?: (documentType: string) => Promise<string[]>;\n /** Absolute-URL import map for shared deps (worker import maps don't\n * exist, so the source is rewritten to these URLs and blob-imported). */\n sharedImports?: Record<string, string>;\n /** Import a rewritten source string (blob URL). Only called when a\n * rewrite happened; omit to disable shared-deps loading in a worker. */\n importSource?: (source: string) => Promise<Record<string, unknown>>;\n};\n\nexport type PackageLoadFailure = {\n name: string;\n url: string;\n error: unknown;\n};\n\ntype SourceReplacement =\n | { status: \"replaced\"; types: Set<string> }\n | { status: \"stale\" }\n | { status: \"failed\"; failure: PackageLoadFailure };\n\nconst SOURCE_KEY_PREFIX = \"src:\";\n\n// Keys are registry specs (`name`, `name@1.2.3`, `@scope/name@1.2.3`) or\n// source keys (`src:<name>`, see sourceKey).\nfunction packageName(key: string): string {\n if (key.startsWith(SOURCE_KEY_PREFIX)) {\n return key.slice(SOURCE_KEY_PREFIX.length);\n }\n const at = key.lastIndexOf(\"@\");\n return at > 0 ? key.slice(0, at) : key;\n}\n\nfunction moduleKey(module: DocumentModelModule): string {\n return `${module.documentModel.global.id}@${module.version ?? 1}`;\n}\n\nfunction isDocumentModelModule(value: unknown): value is DocumentModelModule {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const candidate = value as {\n reducer?: unknown;\n documentModel?: { global?: { id?: unknown } };\n };\n return (\n typeof candidate.reducer === \"function\" &&\n typeof candidate.documentModel?.global?.id === \"string\"\n );\n}\n\ntype AnyUpgradeManifest = UpgradeManifest<readonly number[]>;\n\nfunction isUpgradeManifest(value: unknown): value is AnyUpgradeManifest {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const candidate = value as { documentType?: unknown; upgrades?: unknown };\n return (\n typeof candidate.documentType === \"string\" &&\n typeof candidate.upgrades === \"object\" &&\n candidate.upgrades !== null\n );\n}\n\n// Models entries export manifests either as a named array export\n// (`upgradeManifests`) or as individual manifest objects; take both.\nfunction manifestsOf(namespace: Record<string, unknown>): AnyUpgradeManifest[] {\n const out: AnyUpgradeManifest[] = [];\n for (const value of Object.values(namespace)) {\n if (isUpgradeManifest(value)) {\n out.push(value);\n continue;\n }\n if (Array.isArray(value)) {\n for (const inner of value) {\n if (isUpgradeManifest(inner)) out.push(inner);\n }\n }\n }\n return out;\n}\n\nexport class WorkerPackageLoader implements IDocumentModelLoader {\n private readonly cdnUrl: string;\n private readonly importPackage: PackageImporter;\n private readonly resolvePackages: (documentType: string) => Promise<string[]>;\n private readonly sharedImports?: Record<string, string>;\n private readonly importSource?: (\n source: string,\n ) => Promise<Record<string, unknown>>;\n // Keyed by `documentType@version`: a type can ship several module versions\n // side by side, and keying by type alone would evict all but the last.\n private readonly modulesByKey = new Map<string, DocumentModelModule>();\n // Keyed by documentType; the registry replaces manifests per type.\n private readonly manifestsByType = new Map<string, AnyUpgradeManifest>();\n // What each loaded source contributed, so a reload can remove it first.\n private readonly keysBySource = new Map<string, Set<string>>();\n private readonly manifestTypesBySource = new Map<string, Set<string>>();\n private readonly loadedSpecs = new Set<string>();\n private readonly failures: PackageLoadFailure[] = [];\n private readonly pendingLoads = new Map<string, Promise<void>>();\n private readonly generationBySource = new Map<string, number>();\n private generation = 0;\n\n constructor(options: WorkerPackageLoaderOptions) {\n this.cdnUrl = options.cdnUrl.replace(/\\/$/, \"\");\n this.importPackage = options.importPackage;\n this.sharedImports = options.sharedImports;\n this.importSource = options.importSource;\n const registryClient = new RegistryClient(options.cdnUrl);\n this.resolvePackages =\n options.resolvePackages ??\n ((documentType) =>\n registryClient.getPackagesByDocumentType(documentType));\n }\n\n async loadPackages(specs: string[]): Promise<DocumentModelModule[]> {\n await Promise.all(\n [...new Set(specs)].map((spec) => this.loadPackage(spec)),\n );\n return this.models;\n }\n\n /** Loads URL-addressed packages (local project packages). Idempotent. */\n async loadSources(sources: WorkerPackageSource[]): Promise<void> {\n await Promise.all(\n sources.map((source) => this.loadFromUrl(sourceKey(source), source.url)),\n );\n }\n\n /**\n * Replaces previously loaded sources with freshly imported ones (a vetra\n * watch rebuild re-sends the same source under a cache-busted URL). Returns\n * every document type touched - removed, re-added, or new - so the caller\n * can replace the registry's version families. A source whose import fails\n * keeps its previous modules and is reported in `failures`; one superseded\n * by a newer reload of the same source contributes nothing.\n */\n async reloadSources(\n sources: WorkerPackageSource[],\n ): Promise<{ types: string[]; failures: PackageLoadFailure[] }> {\n const results = await Promise.all(\n sources.map((source) =>\n this.replaceSource(sourceKey(source), source.url),\n ),\n );\n const types = new Set<string>();\n const failures: PackageLoadFailure[] = [];\n for (const result of results) {\n if (result.status === \"replaced\") {\n for (const type of result.types) types.add(type);\n } else if (result.status === \"failed\") {\n failures.push(result.failure);\n }\n }\n return { types: [...types], failures };\n }\n\n // On a miss, discover the package(s) for the type and import them on demand.\n async load(documentType: string): Promise<DocumentModelModule> {\n const existing = this.latestForType(documentType);\n if (existing) {\n return existing;\n }\n const packageNames = await this.resolvePackages(documentType);\n const failuresBefore = this.failures.length;\n await Promise.all(\n [...new Set(packageNames)].map((name) => this.loadPackage(name)),\n );\n const loaded = this.latestForType(documentType);\n if (loaded) {\n return loaded;\n }\n throw this.notLoadedError(\n documentType,\n packageNames,\n this.failures.slice(failuresBefore),\n );\n }\n\n get models(): DocumentModelModule[] {\n return [...new Set(this.modulesByKey.values())];\n }\n\n get upgradeManifests(): AnyUpgradeManifest[] {\n return [...this.manifestsByType.values()];\n }\n\n get loadFailures(): PackageLoadFailure[] {\n return [...this.failures];\n }\n\n /** The highest registered version for a type, which is what a bare load resolves to. */\n private latestForType(documentType: string): DocumentModelModule | undefined {\n let latest: DocumentModelModule | undefined;\n for (const module of this.modulesByKey.values()) {\n if (module.documentModel.global.id !== documentType) {\n continue;\n }\n if (!latest || (module.version ?? 1) > (latest.version ?? 1)) {\n latest = module;\n }\n }\n return latest;\n }\n\n private notLoadedError(\n documentType: string,\n packageNames: string[],\n failures: PackageLoadFailure[],\n ): Error {\n if (packageNames.length === 0) {\n return new Error(`No package found for document model: ${documentType}`);\n }\n if (failures.length === 0) {\n return new Error(\n `Imported [${packageNames.join(\", \")}] but document model not found: ${documentType}`,\n );\n }\n const cause =\n failures.length === 1\n ? failures[0].error\n : new AggregateError(failures.map((failure) => failure.error));\n return new Error(\n `Failed to import package(s) [${packageNames.join(\", \")}] for document model: ${documentType}`,\n { cause },\n );\n }\n\n private async loadPackage(spec: string): Promise<void> {\n const name = packageName(spec);\n const url = `${this.cdnUrl}/${name}/browser/document-models/index.js`;\n await this.loadFromUrl(spec, url);\n }\n\n // Concurrent loads of one key share an import; a separate generation would\n // mark the earlier one stale and its caller would miss the module.\n private loadFromUrl(key: string, url: string): Promise<void> {\n if (this.loadedSpecs.has(key)) {\n return Promise.resolve();\n }\n let pending = this.pendingLoads.get(key);\n if (!pending) {\n pending = this.replaceSource(key, url)\n .finally(() => this.pendingLoads.delete(key))\n .then(() => undefined);\n this.pendingLoads.set(key, pending);\n }\n return pending;\n }\n\n // Only the newest call per key commits, and a failed import leaves the\n // key's previous modules, manifests and loaded state untouched.\n private async replaceSource(\n key: string,\n url: string,\n ): Promise<SourceReplacement> {\n const generation = ++this.generation;\n this.generationBySource.set(key, generation);\n let namespace: Record<string, unknown>;\n try {\n namespace = await this.importNamespace(url);\n } catch (error) {\n if (this.generationBySource.get(key) !== generation) {\n return { status: \"stale\" };\n }\n const failure = { name: packageName(key), url, error };\n this.failures.push(failure);\n return { status: \"failed\", failure };\n }\n if (this.generationBySource.get(key) !== generation) {\n return { status: \"stale\" };\n }\n const types = new Set<string>();\n for (const removedKey of this.keysBySource.get(key) ?? []) {\n const removed = this.modulesByKey.get(removedKey);\n if (removed) types.add(removed.documentModel.global.id);\n this.modulesByKey.delete(removedKey);\n }\n for (const type of this.manifestTypesBySource.get(key) ?? []) {\n this.manifestsByType.delete(type);\n }\n for (const added of this.registerNamespace(key, namespace)) {\n types.add(added);\n }\n this.loadedSpecs.add(key);\n return { status: \"replaced\", types };\n }\n\n private async importNamespace(url: string): Promise<Record<string, unknown>> {\n // Shared-deps hosts fetch the source so shared specifiers can be\n // rewritten to absolute vendor URLs (import maps don't apply to blob\n // imports). Packages without shared/relative imports still go through\n // the plain importPackage path below.\n const hasSharedImports =\n this.sharedImports !== undefined &&\n Object.keys(this.sharedImports).length > 0;\n const source = hasSharedImports\n ? await (await fetch(url)).text()\n : undefined;\n const rewritten =\n source !== undefined\n ? rewritePackageSource(source, url, this.sharedImports!)\n : source;\n if (rewritten !== undefined && rewritten !== source) {\n if (!this.importSource) {\n throw new Error(\n \"importSource is required to load a package that imports shared deps\",\n );\n }\n return this.importSource(rewritten);\n }\n return this.importPackage(url);\n }\n\n /** Registers a namespace as the key's whole contribution; returns its module types. */\n private registerNamespace(\n key: string,\n namespace: Record<string, unknown>,\n ): Set<string> {\n const keys = new Set<string>();\n const manifestTypes = new Set<string>();\n const types = new Set<string>();\n for (const value of Object.values(namespace)) {\n if (isDocumentModelModule(value)) {\n const k = moduleKey(value);\n this.modulesByKey.set(k, value);\n keys.add(k);\n types.add(value.documentModel.global.id);\n }\n }\n for (const manifest of manifestsOf(namespace)) {\n this.manifestsByType.set(manifest.documentType, manifest);\n manifestTypes.add(manifest.documentType);\n }\n this.keysBySource.set(key, keys);\n this.manifestTypesBySource.set(key, manifestTypes);\n return types;\n }\n}\n\n// Reloads replace by source NAME: a watch rebuild re-sends the same package\n// under a new cache-busted URL, which must hit the same slot.\nfunction sourceKey(source: WorkerPackageSource): string {\n return `${SOURCE_KEY_PREFIX}${source.name}`;\n}\n"],"mappings":";;;;;AAMA,MAAa,yBAAyB;AAEtC,SAAgB,OAAO,SAA0C;CAC/D,OAAO,QAAQ,WAAW,KAAA,CAAS;AACrC;AAOA,SAAgB,UACd,QACA,MACA,YAAoB,wBACR;CACZ,MAAM,QAAQ,QAAgB,OAAkB,CAAC,MAC/C,OAAO,SAAS,QAAQ;EAAE,GAAG;EAAM;EAAI;EAAQ;CAAK,IAAqB,EACvE,UACF,CAAC;CACH,OAAO;EACL;EACA,WAAW,QAAQ,SAAS,OAAO,KAAK,QAAQ,IAAI,CAAC;CACvD;AACF;;;;ACVA,SAAgB,kBACd,QACA,QACA,MACe;CACf,OAAO,OACL,OAAO,SACJ,QAAQ;EACP,GAAG;EACH;EACA,QAAQ,OAAO;EACf,aAAa,OAAO;EACpB,iBAAiB,OAAO;EACxB,YAAY,OAAO;EACnB,QAAQ,OAAO;EACf;CACF,IACA,EAAE,UAAU,CAAC,IAAI,EAAE,CACrB,CACF;AACF;;AAGA,SAAgB,mBACd,QACA,QACe;CACf,OAAO,OACL,OAAO,SAAS,QAAQ;EACtB,GAAG;EACH;EACA,QAAQ,OAAO;EACf,aAAa,OAAO;EACpB,YAAY,OAAO;CACrB,EAAE,CACJ;AACF;;;;ACzCA,SAAgB,sBACd,aACA,UAC4E;CAC5E,OAAO;EACL,iBAAiB,OAAO,QAA6B,SAAsB;GACzE,MAAM,kBACJ,aACA,UACA;IACE,QAAQ,OAAO;IACf,aAAa,OAAO;IACpB,cAAc,oBAAoB,OAAO,eAAe;IACxD,YAAY,OAAO;IACnB,QAAQ,OAAO;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orrelatedSubscriptions","fromErrorInfo","KeyedListeners","Listeners","KeyedListeners","createReactorClientProxy","SubscriptionStore","hostResponder","ReactorHostServer","createPortTransport","RPC_PROTOCOL_VERSION"],"sources":["../../../src/rpc/op-channel.ts","../../../src/rpc/adopt-sync-peer.ts","../../../src/rpc/local-sync-peer-handlers.ts","../../../src/rpc/admin-client.ts","../../../src/rpc/inspector-proxy.ts","../../../src/rpc/inspector-ops.ts","../../../src/rpc/live-query-proxy.ts","../../../src/rpc/relational-db-proxy.ts","../../../src/rpc/sync-manager-proxy.ts","../../../src/rpc/forwarded-events.ts","../../../src/rpc/event-bus-proxy.ts","../../../src/rpc/connect-reactor.ts","../../../src/rpc/reactor-host.ts","../../../src/rpc/worker-package-loader.ts"],"sourcesContent":["import type {\n MessageRouter,\n ClientMessage,\n OpKind,\n} from \"@powerhousedao/reactor/rpc\";\n\nexport const RPC_DEFAULT_TIMEOUT_MS = 30_000;\n\nexport function toVoid(promise: Promise<unknown>): Promise<void> {\n return promise.then(() => undefined);\n}\n\nexport interface IOpChannel {\n call(method: string, args?: unknown[]): Promise<unknown>;\n callVoid(method: string, args?: unknown[]): Promise<void>;\n}\n\nexport function opChannel(\n router: MessageRouter,\n kind: OpKind,\n timeoutMs: number = RPC_DEFAULT_TIMEOUT_MS,\n): IOpChannel {\n const call = (method: string, args: unknown[] = []): Promise<unknown> =>\n router.request((id) => ({ k: kind, id, method, args }) as ClientMessage, {\n timeoutMs,\n });\n return {\n call,\n callVoid: (method, args) => toVoid(call(method, args)),\n };\n}\n","import type { RemoteFilter } from \"@powerhousedao/reactor\";\nimport type { MessageRouter } from \"@powerhousedao/reactor/rpc\";\nimport { toVoid } from \"./op-channel.js\";\n\nexport type AdoptSyncPeerParams = {\n peerId: string;\n channelName: string;\n /** `DriveCollectionId.key`; the class does not survive structured clone. */\n collectionIdKey: string;\n remoteName: string;\n filter: RemoteFilter;\n};\n\nexport type RemoveSyncPeerParams = {\n peerId: string;\n channelName: string;\n remoteName: string;\n};\n\n/** Moves `port` to the host, which adopts the peer as a local remote over it. */\nexport function sendAdoptSyncPeer(\n router: MessageRouter,\n params: AdoptSyncPeerParams,\n port: MessagePort,\n): Promise<void> {\n return toVoid(\n router.request(\n (id) => ({\n k: \"adopt-sync-peer\",\n id,\n peerId: params.peerId,\n channelName: params.channelName,\n collectionIdKey: params.collectionIdKey,\n remoteName: params.remoteName,\n filter: params.filter,\n port,\n }),\n { transfer: [port] },\n ),\n );\n}\n\n/** Removes the peer's remote and closes its port in the host's registry. */\nexport function sendRemoveSyncPeer(\n router: MessageRouter,\n params: RemoveSyncPeerParams,\n): Promise<void> {\n return toVoid(\n router.request((id) => ({\n k: \"remove-sync-peer\",\n id,\n peerId: params.peerId,\n channelName: params.channelName,\n remoteName: params.remoteName,\n })),\n );\n}\n","import {\n collectionIdFromKey,\n messagePortTransport,\n registerLocalPeer,\n removeLocalPeer,\n type LocalChannelPortRegistry,\n type LocalPeerSyncManager,\n} from \"@powerhousedao/reactor\";\nimport type {\n AdoptSyncPeerParams,\n RemoveSyncPeerParams,\n} from \"./adopt-sync-peer.js\";\nimport type { ReactorHostOptions } from \"./reactor-host.js\";\n\n/** The host's adopt/remove handlers over the reactor's local peer registry. */\nexport function localSyncPeerHandlers(\n syncManager: LocalPeerSyncManager,\n registry: LocalChannelPortRegistry,\n): Required<Pick<ReactorHostOptions, \"onAdoptSyncPeer\" | \"onRemoveSyncPeer\">> {\n return {\n onAdoptSyncPeer: async (params: AdoptSyncPeerParams, port: MessagePort) => {\n await registerLocalPeer(\n syncManager,\n registry,\n {\n peerId: params.peerId,\n channelName: params.channelName,\n collectionId: collectionIdFromKey(params.collectionIdKey),\n remoteName: params.remoteName,\n filter: params.filter,\n },\n messagePortTransport(port),\n );\n },\n onRemoveSyncPeer: (params: RemoveSyncPeerParams) =>\n removeLocalPeer(syncManager, registry, params),\n };\n}\n","import {\n Listeners,\n type MessageRouter,\n type WorkerInspectorInfo,\n type WorkerMigrationState,\n} from \"@powerhousedao/reactor/rpc\";\nimport { RPC_DEFAULT_TIMEOUT_MS, toVoid } from \"./op-channel.js\";\n\nexport interface IWorkerAdminClient {\n info(): Promise<WorkerInspectorInfo>;\n restart(): Promise<void>;\n clearStorage(): Promise<void>;\n migrate(): Promise<void>;\n getMigrationState(): WorkerMigrationState;\n subscribeMigration(callback: () => void): () => void;\n}\n\n/** Worker lifecycle channel (info/restart/clearStorage/migrate) over the shared router. */\nexport function createWorkerAdminClient(\n router: MessageRouter,\n): IWorkerAdminClient {\n let migrationState: WorkerMigrationState = { status: \"idle\" };\n const migrationListeners = new Listeners();\n\n router.on(\"migration\", (msg) => {\n migrationState = msg.state;\n migrationListeners.emit();\n });\n\n const send = (\n method: \"info\" | \"restart\" | \"clearStorage\" | \"migrate\",\n ): Promise<unknown> =>\n router.request((id) => ({ k: \"admin\", id, method }), {\n timeoutMs: RPC_DEFAULT_TIMEOUT_MS,\n });\n\n return {\n info: () => send(\"info\") as Promise<WorkerInspectorInfo>,\n restart: () => toVoid(send(\"restart\")),\n clearStorage: () => toVoid(send(\"clearStorage\")),\n migrate: () => toVoid(send(\"migrate\")),\n getMigrationState: () => migrationState,\n subscribeMigration: (callback) => migrationListeners.add(callback),\n };\n}\n","import {\n INSPECTOR_OPS,\n type IInspector,\n type IInspectorAdmin,\n type IReactorDbQuery,\n} from \"@powerhousedao/reactor\";\nimport type { MessageRouter } from \"@powerhousedao/reactor/rpc\";\nimport { opChannel } from \"./op-channel.js\";\n\n/** `queryReactorDb` is the published name of `queryDb`. */\nexport interface IInspectorProxy\n extends IInspector, IInspectorAdmin, IReactorDbQuery {\n queryReactorDb(sql: string, params?: unknown[]): Promise<unknown[]>;\n}\n\n/** Every row of `INSPECTOR_OPS`; the host decides which tiers it serves. */\nexport function createInspectorProxy(router: MessageRouter): IInspectorProxy {\n const ops = opChannel(router, \"inspector-op\");\n const proxy: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const [key, spec] of Object.entries(INSPECTOR_OPS)) {\n proxy[key] = (...args) => ops.call(spec.rpc, args);\n }\n const queryDb = (sql: unknown, params?: unknown) =>\n ops.call(INSPECTOR_OPS.queryDb.rpc, [sql, params ?? []]);\n proxy.queryDb = queryDb;\n proxy.queryReactorDb = queryDb;\n return proxy as unknown as IInspectorProxy;\n}\n","import {\n dispatchTableOp,\n INSPECTOR_OPS,\n methodOf,\n opKeyOf,\n SYNC_INSPECTION_OPS,\n type IInspector,\n type IInspectorAdmin,\n type InspectorAccess,\n type IReactorDbQuery,\n type ISyncAdmin,\n type ISyncInspector,\n} from \"@powerhousedao/reactor\";\n\nexport type InspectorOpTargets = {\n inspector: IInspector & Partial<IInspectorAdmin>;\n dbQuery?: IReactorDbQuery;\n};\n\n/** Host side of `inspector-op`; refuses tiers `access` does not grant. */\nexport function dispatchInspectorOp(\n targets: InspectorOpTargets,\n access: InspectorAccess,\n method: string,\n args: unknown[],\n): Promise<unknown> {\n return dispatchTableOp(\n INSPECTOR_OPS,\n (key) =>\n key === \"queryDb\"\n ? methodOf(targets.dbQuery, key)\n : methodOf(targets.inspector, key),\n access,\n method,\n args,\n );\n}\n\nexport type SyncInspectionOpTargets = {\n inspector?: ISyncInspector;\n admin?: ISyncAdmin;\n};\n\n/** Whether `method` is one of the `sync-op` rows `dispatchSyncInspectionOp` serves. */\nexport function isSyncInspectionOp(method: string): boolean {\n return opKeyOf(SYNC_INSPECTION_OPS, method) !== undefined;\n}\n\n/** Host side of the inspection and repair rows of `sync-op`. */\nexport function dispatchSyncInspectionOp(\n targets: SyncInspectionOpTargets,\n access: InspectorAccess,\n method: string,\n args: unknown[],\n): Promise<unknown> {\n return dispatchTableOp(\n SYNC_INSPECTION_OPS,\n (key) =>\n SYNC_INSPECTION_OPS[key].tier === \"read\"\n ? methodOf(targets.inspector, key)\n : methodOf(targets.admin, key),\n access,\n method,\n args,\n );\n}\n","import {\n fromErrorInfo,\n type MessageRouter,\n createCorrelatedSubscriptions,\n} from \"@powerhousedao/reactor/rpc\";\n\nexport type LiveQueryResultsCallback = (results: unknown) => void;\nexport type LiveQueryErrorCallback = (error: unknown) => void;\n\nexport interface ILiveQueryProxy {\n query(\n sql: string,\n params: unknown[],\n onResults: LiveQueryResultsCallback,\n onError?: LiveQueryErrorCallback,\n ): () => void;\n}\n\ntype LiveSubscriber = {\n onResults: LiveQueryResultsCallback;\n onError?: LiveQueryErrorCallback;\n};\n\nexport function createLiveQueryProxy(router: MessageRouter): ILiveQueryProxy {\n const subs = createCorrelatedSubscriptions<\n LiveSubscriber,\n \"event-live\",\n \"live-err\"\n >(router, {\n idPrefix: \"live\",\n eventKind: \"event-live\",\n errKind: \"live-err\",\n onEvent: (sub, msg) => sub.onResults(msg.results),\n onError: (sub, msg) => sub.onError?.(fromErrorInfo(msg.error)),\n close: (id) => ({ k: \"unsub-live\", id }),\n });\n\n return {\n query(sql, params, onResults, onError) {\n return subs.subscribe({ onResults, onError }, (id) => ({\n k: \"sub-live\",\n id,\n sql,\n params,\n }));\n },\n };\n}\n","import type { PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport { createLiveQueryProxy } from \"./live-query-proxy.js\";\nimport type { MessageRouter } from \"@powerhousedao/reactor/rpc\";\nimport { opChannel } from \"./op-channel.js\";\n\nexport function createRelationalPgliteProxy(\n router: MessageRouter,\n): PGliteWithLive {\n const ops = opChannel(router, \"db-op\");\n const liveProxy = createLiveQueryProxy(router);\n\n const proxy = {\n query: async (sql: string, params?: unknown[]) => {\n const rows = await ops.call(\"query\", [sql, params ?? []]);\n return { rows };\n },\n live: {\n query: (\n sql: string,\n params: unknown[] | null | undefined,\n callback?: (results: unknown) => void,\n ) =>\n new Promise((resolve, reject) => {\n // Settle on the first result/error so a subscribe failure reaches the caller's retry path.\n let settled = false;\n const unsubscribe = liveProxy.query(\n sql,\n params ?? [],\n (results) => {\n if (!settled) {\n settled = true;\n resolve({ unsubscribe });\n }\n callback?.(results);\n },\n (error) => {\n if (!settled) {\n settled = true;\n reject(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n },\n );\n }),\n },\n };\n\n return proxy as unknown as PGliteWithLive;\n}\n","import type { PeerManifest } from \"@powerhousedao/shared/document-model\";\nimport {\n createPeerAgreement,\n DriveCollectionId,\n SYNC_INSPECTION_OPS,\n SyncEventTypes,\n type DeadLetterPage,\n type ISyncAdmin,\n type ISyncInspector,\n type RemoteSyncInspection,\n type SyncInspectionOpKey,\n type ChannelConfig,\n type ConnectionStateChangeCallback,\n type ConnectionStateChangedEvent,\n type ConnectionStateSnapshot,\n type IChannel,\n type IEventBus,\n type IMailbox,\n type IPeerAgreement,\n type PeerAgreementBasis,\n type ISyncManager,\n type Remote,\n type RemoteFilter,\n type RemoteMeta,\n type RemoteOptions,\n type RemotePeer,\n type ShutdownStatus,\n type SyncHold,\n type SyncOperation,\n type SyncStatus,\n type SyncStatusChangeCallback,\n} from \"@powerhousedao/reactor\";\nimport {\n KeyedListeners,\n Listeners,\n type MessageRouter,\n} from \"@powerhousedao/reactor/rpc\";\nimport { opChannel, type IOpChannel } from \"./op-channel.js\";\n\n// Synthetic bus channel id for sync-status deltas (not a reactor IEventBus type).\nexport const SYNC_STATUS_CHANGED_EVENT = 90001;\n\nexport type SyncStatusChangedBusEvent = {\n documentId: string;\n status: SyncStatus;\n};\n\nconst SEED_MAX_ATTEMPTS = 3;\nconst SEED_RETRY_DELAY_MS = 500;\n\n// Wire shapes: DriveCollectionId arrives prototype-less over postMessage.\ntype WireDriveCollectionId = { driveId: string; branch: string };\ntype WireRemoteMeta = {\n id: string;\n name: string;\n collectionId: WireDriveCollectionId;\n channelConfig: ChannelConfig;\n filter: RemoteFilter;\n options: RemoteOptions;\n peer?: RemotePeer;\n};\ntype WireRemote = {\n meta: WireRemoteMeta;\n connectionState: ConnectionStateSnapshot;\n};\n\nconst DEFAULT_SNAPSHOT: ConnectionStateSnapshot = {\n state: \"connecting\",\n failureCount: 0,\n lastSuccessUtcMs: 0,\n lastFailureUtcMs: 0,\n pushBlocked: false,\n pushFailureCount: 0,\n receivingPages: false,\n requiresAuth: false,\n};\n\n// Inert mailbox: a proxy remote carries no live sync operations tab-side.\nclass NoopMailbox implements IMailbox {\n get items(): readonly SyncOperation[] {\n return [];\n }\n get ackOrdinal(): number {\n return 0;\n }\n get latestOrdinal(): number {\n return 0;\n }\n init(): void {}\n advanceOrdinal(): void {}\n get(): undefined {\n return undefined;\n }\n add(): void {}\n remove(): void {}\n onAdded(): void {}\n onRemoved(): void {}\n pause(): void {}\n resume(): void {}\n flush(): void {}\n isPaused(): boolean {\n return false;\n }\n}\n\nconst NOOP_MAILBOX = new NoopMailbox();\n\nfunction rehydrateMeta(wire: WireRemoteMeta): RemoteMeta {\n return {\n id: wire.id,\n name: wire.name,\n collectionId: DriveCollectionId.forDrive(\n wire.collectionId.driveId,\n wire.collectionId.branch,\n ),\n channelConfig: wire.channelConfig,\n filter: wire.filter,\n options: wire.options,\n peer: wire.peer,\n };\n}\n\nfunction channelUrl(meta: RemoteMeta): string | undefined {\n const url = meta.channelConfig.parameters.url;\n return typeof url === \"string\" ? url : undefined;\n}\n\n// Tab-side ISyncManager: cache-backed reads fed by the bus, ops over sync-op RPC.\nexport class SyncManagerProxy\n implements ISyncManager, ISyncInspector, ISyncAdmin\n{\n private readonly ops: IOpChannel;\n private readonly connectionStates = new Map<\n string,\n ConnectionStateSnapshot\n >();\n private readonly connectionListeners = new KeyedListeners<string>();\n private readonly syncStatuses = new Map<string, SyncStatus>();\n private readonly syncStatusListeners = new Listeners<[string, SyncStatus]>();\n private remotes: Remote[] = [];\n private basis: PeerAgreementBasis | undefined;\n private seedPromise: Promise<void> | null = null;\n\n constructor(router: MessageRouter, busProxy: IEventBus) {\n this.ops = opChannel(router, \"sync-op\");\n\n busProxy.subscribe(\n SyncEventTypes.CONNECTION_STATE_CHANGED,\n (_type, event) => {\n const e = event as ConnectionStateChangedEvent;\n this.connectionStates.set(e.remoteName, e.snapshot);\n this.notifyConnection(e.remoteName);\n },\n );\n\n busProxy.subscribe(SYNC_STATUS_CHANGED_EVENT, (_type, event) => {\n const e = event as SyncStatusChangedBusEvent;\n this.syncStatuses.set(e.documentId, e.status);\n this.syncStatusListeners.emit(e.documentId, e.status);\n });\n\n void this.ensureSeeded();\n }\n\n /** Attempts that fail while `isWaiting()` (the worker waits on a store lock) are not counted. */\n async startup({\n isWaiting = () => false,\n }: { isWaiting?: () => boolean } = {}): Promise<void> {\n let failures = 0;\n for (;;) {\n try {\n await this.ensureSeeded();\n return;\n } catch (error) {\n if (!isWaiting()) failures++;\n if (failures >= SEED_MAX_ATTEMPTS) throw error;\n await new Promise((resolve) =>\n setTimeout(resolve, SEED_RETRY_DELAY_MS),\n );\n }\n }\n }\n\n shutdown(): ShutdownStatus {\n return { isShutdown: true, completed: Promise.resolve() };\n }\n\n getByName(name: string): Remote {\n const remote = this.remotes.find((r) => r.meta.name === name);\n if (!remote) {\n throw new Error(`Unknown remote: ${name}`);\n }\n return remote;\n }\n\n getById(id: string): Remote {\n const remote = this.remotes.find((r) => r.meta.id === id);\n if (!remote) {\n throw new Error(`Unknown remote id: ${id}`);\n }\n return remote;\n }\n\n async add(\n name: string,\n collectionId: DriveCollectionId,\n channelConfig: ChannelConfig,\n filter?: RemoteFilter,\n options?: RemoteOptions,\n ): Promise<Remote> {\n await this.callSyncOp(\"add\", [\n name,\n collectionId.key,\n channelConfig,\n filter,\n options,\n ]);\n await this.refreshRemotes();\n return this.getByName(name);\n }\n\n async setPeerManifest(\n id: string,\n manifest: PeerManifest | null,\n ): Promise<void> {\n await this.callSyncOp(\"setPeerManifest\", [id, manifest]);\n await this.refreshRemotes();\n }\n\n /** Fetched once; the worker's flags do not change at runtime. */\n localManifest(): PeerManifest {\n return this.agreementBasis().local;\n }\n\n async listHolds(filter?: {\n remoteName?: string;\n documentId?: string;\n }): Promise<SyncHold[]> {\n return (await this.callSyncOp(\"listHolds\", [filter])) as SyncHold[];\n }\n\n agreement(): IPeerAgreement {\n return createPeerAgreement(\n this.agreementBasis(),\n this.remotes.map((remote) => remote.meta),\n );\n }\n\n private agreementBasis(): PeerAgreementBasis {\n if (!this.basis) {\n throw new Error(\n \"Peer agreement has not been fetched from the worker yet\",\n );\n }\n return this.basis;\n }\n\n async bindRemote(id: string, boundAddress: string): Promise<void> {\n await this.callSyncOp(\"bindRemote\", [id, boundAddress]);\n await this.refreshRemotes();\n }\n\n triggerPull(name: string): void {\n this.callSyncOp(\"triggerPull\", [name]).catch((error: unknown) => {\n console.error(`triggerPull failed for remote \"${name}\":`, error);\n });\n }\n\n async remove(name: string): Promise<void> {\n await this.callSyncOp(\"remove\", [name]);\n await this.refreshRemotes();\n }\n\n list(): Remote[] {\n return [...this.remotes];\n }\n\n /** Re-reads the worker's remotes after a change made outside this proxy. */\n refresh(): Promise<void> {\n return this.refreshRemotes();\n }\n\n waitForSync(): Promise<never> {\n return Promise.reject(\n new Error(\"waitForSync is not supported over the worker RPC boundary\"),\n );\n }\n\n getSyncStatus(documentId: string): SyncStatus | undefined {\n return this.syncStatuses.get(documentId);\n }\n\n onSyncStatusChange(callback: SyncStatusChangeCallback): () => void {\n return this.syncStatusListeners.add(callback);\n }\n\n async inspectRemote(remoteName: string): Promise<RemoteSyncInspection> {\n return (await this.tableOp(\"inspectRemote\", [\n remoteName,\n ])) as RemoteSyncInspection;\n }\n\n async inspectRemotes(): Promise<RemoteSyncInspection[]> {\n return (await this.tableOp(\"inspectRemotes\", [])) as RemoteSyncInspection[];\n }\n\n async listDeadLetters(\n remoteName: string,\n cursor?: string,\n limit?: number,\n ): Promise<DeadLetterPage> {\n return (await this.tableOp(\"listDeadLetters\", [\n remoteName,\n cursor,\n limit,\n ])) as DeadLetterPage;\n }\n\n async resetChannel(remoteName: string): Promise<void> {\n await this.tableOp(\"resetChannel\", [remoteName]);\n }\n\n async requeueDeadLetter(remoteName: string, id: string): Promise<void> {\n await this.tableOp(\"requeueDeadLetter\", [remoteName, id]);\n }\n\n async clearDeadLetter(remoteName: string, id: string): Promise<void> {\n await this.tableOp(\"clearDeadLetter\", [remoteName, id]);\n }\n\n private tableOp(key: SyncInspectionOpKey, args: unknown[]): Promise<unknown> {\n return this.ops.call(SYNC_INSPECTION_OPS[key].rpc, args);\n }\n\n private callSyncOp(method: string, args: unknown[]): Promise<unknown> {\n return this.ops.call(method, args);\n }\n\n private notifyConnection(remoteName?: string): void {\n if (remoteName !== undefined) {\n this.connectionListeners.emit(remoteName);\n return;\n }\n this.connectionListeners.emitAll();\n }\n\n private makeChannel(remoteName: string, url: string | undefined): IChannel {\n const channel: IChannel & { config: { url?: string } } = {\n inbox: NOOP_MAILBOX,\n outbox: NOOP_MAILBOX,\n deadLetter: NOOP_MAILBOX,\n init: () => Promise.resolve(),\n shutdown: () => Promise.resolve(),\n getConnectionState: () =>\n this.connectionStates.get(remoteName) ?? DEFAULT_SNAPSHOT,\n onConnectionStateChange: (callback: ConnectionStateChangeCallback) => {\n const listener = () =>\n callback(this.connectionStates.get(remoteName) ?? DEFAULT_SNAPSHOT);\n return this.connectionListeners.add(remoteName, listener);\n },\n\n triggerPull: () => {\n this.callSyncOp(\"triggerPull\", [remoteName]).catch((error: unknown) => {\n console.error(\n `triggerPull failed for remote \"${remoteName}\":`,\n error,\n );\n });\n },\n notePoll: () => {},\n lastHolderPollUtcMs: () => undefined,\n setLocalManifest: () => {},\n onPeerManifest: () => () => {},\n config: { url },\n };\n return channel;\n }\n\n private async refreshRemotes(): Promise<void> {\n const wire = (await this.callSyncOp(\"list\", [])) as WireRemote[];\n const names = new Set<string>();\n this.remotes = wire.map((w) => {\n const meta = rehydrateMeta(w.meta);\n names.add(meta.name);\n if (!this.connectionStates.has(meta.name)) {\n this.connectionStates.set(meta.name, w.connectionState);\n }\n return { meta, channel: this.makeChannel(meta.name, channelUrl(meta)) };\n });\n for (const name of [...this.connectionStates.keys()]) {\n if (!names.has(name)) {\n this.connectionStates.delete(name);\n }\n }\n this.notifyConnection();\n }\n\n // Shared in-flight seed so the eager kick-off and startup() share one list RPC.\n private ensureSeeded(): Promise<void> {\n if (!this.basis) {\n this.callSyncOp(\"peerAgreementBasis\", [])\n .then((basis) => {\n this.basis = basis as PeerAgreementBasis;\n })\n .catch(() => {});\n }\n if (!this.seedPromise) {\n const pending = this.refreshRemotes();\n this.seedPromise = pending;\n\n pending.catch(() => {\n if (this.seedPromise === pending) {\n this.seedPromise = null;\n }\n });\n }\n return this.seedPromise;\n }\n}\n\nexport function createSyncManagerProxy(\n router: MessageRouter,\n busProxy: IEventBus,\n): ISyncManager {\n return new SyncManagerProxy(router, busProxy);\n}\n","import { ReactorEventTypes, SyncEventTypes } from \"@powerhousedao/reactor\";\nimport { SYNC_STATUS_CHANGED_EVENT } from \"./sync-manager-proxy.js\";\n\nexport const FORWARDED_EVENT_TYPES = [\n SyncEventTypes.SYNC_PENDING,\n SyncEventTypes.SYNC_SUCCEEDED,\n SyncEventTypes.SYNC_FAILED,\n SyncEventTypes.DEAD_LETTER_ADDED,\n SyncEventTypes.CONNECTION_STATE_CHANGED,\n ReactorEventTypes.MODEL_LOADED,\n];\n\nexport const FORWARDED_BUS_EVENT_TYPES: number[] = [\n ...FORWARDED_EVENT_TYPES,\n SYNC_STATUS_CHANGED_EVENT,\n];\n","import type { IEventBus, Unsubscribe } from \"@powerhousedao/reactor\";\nimport { FORWARDED_BUS_EVENT_TYPES } from \"./forwarded-events.js\";\nimport { KeyedListeners, type MessageRouter } from \"@powerhousedao/reactor/rpc\";\n\ntype BusSubscriber = (type: number, event: unknown) => void | Promise<void>;\n\n/** Tab-side IEventBus over bus-event; emit() is unsupported (the worker emits). */\nexport class ReactorEventBusProxy implements IEventBus {\n private readonly forwardedTypes = new Set<number>(FORWARDED_BUS_EVENT_TYPES);\n private readonly subscribers = new KeyedListeners<\n number,\n [number, unknown]\n >();\n\n constructor(router: MessageRouter) {\n router.on(\"bus-event\", (msg) => {\n this.subscribers.emit(msg.eventType, msg.eventType, msg.event);\n });\n }\n\n subscribe<K>(\n type: number,\n subscriber: (type: number, event: K) => void | Promise<void>,\n ): Unsubscribe {\n if (!this.forwardedTypes.has(type)) {\n throw new Error(\n `ReactorEventBusProxy cannot subscribe to event type ${type}: the worker forwards only [${[...this.forwardedTypes].join(\", \")}]`,\n );\n }\n const entry = subscriber as BusSubscriber;\n return this.subscribers.add(\n type,\n entry as (eventType: number, event: unknown) => void,\n );\n }\n\n emit(): Promise<void> {\n return Promise.reject(\n new Error(\n \"EventBus.emit is not supported tab-side; the reactor graph emits in the worker\",\n ),\n );\n }\n}\n\nexport function createReactorEventBusProxy(router: MessageRouter): IEventBus {\n return new ReactorEventBusProxy(router);\n}\n","import type {\n IDocumentModelRegistry,\n IReactorClient,\n} from \"@powerhousedao/reactor\";\nimport {\n createReactorClientProxy,\n type MessageRouter,\n type ReactorIdentity,\n type VersionFingerprint,\n} from \"@powerhousedao/reactor/rpc\";\n\nexport type ReactorHello = {\n version: VersionFingerprint;\n construct?: unknown;\n packages?: string[];\n};\n\nexport function connectReactorClient(\n router: MessageRouter,\n hello: ReactorHello,\n onReload?: (reason: string, workerGen?: string) => void,\n registry?: IDocumentModelRegistry,\n): IReactorClient {\n const client = createReactorClientProxy(router, { onReload, registry });\n router.post({\n k: \"hello\",\n id: \"hello\",\n version: hello.version,\n construct: hello.construct,\n packages: hello.packages,\n });\n return client;\n}\n\n// Push the current renown identity (null on logout) to the worker; re-send on login/logout.\nexport function postReactorIdentity(\n router: MessageRouter,\n user: ReactorIdentity | null,\n): void {\n router.post({ k: \"identity\", user });\n}\n","import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport type {\n AdoptSyncPeerParams,\n RemoveSyncPeerParams,\n} from \"./adopt-sync-peer.js\";\nimport {\n hostResponder,\n type IHostResponder,\n ReactorHostServer,\n SubscriptionStore,\n type ClientMessage,\n type CorrelationId,\n type ReactorIdentity,\n type RpcAdmin,\n type RpcAdoptSyncPeer,\n type RpcDbOp,\n type RpcHello,\n type RpcInspectorOp,\n type RpcLiveSubscribe,\n type RpcRegisterPackages,\n type RpcRemoveSyncPeer,\n type RpcSyncOp,\n type RpcUnregisterPackages,\n type VersionFingerprint,\n type WorkerInspectorInfo,\n type WorkerMigrationState,\n type WorkerPackageSource,\n RPC_PROTOCOL_VERSION,\n createPortTransport,\n type IRpcTransport,\n} from \"@powerhousedao/reactor/rpc\";\n\nfunction isDataMessage(\n msg: ClientMessage,\n): msg is ClientMessage & { id: CorrelationId } {\n return (\n msg.k === \"req\" ||\n msg.k === \"sub\" ||\n msg.k === \"page\" ||\n msg.k === \"sync-op\" ||\n msg.k === \"db-op\" ||\n msg.k === \"inspector-op\" ||\n msg.k === \"adopt-sync-peer\" ||\n msg.k === \"remove-sync-peer\" ||\n msg.k === \"sub-live\"\n );\n}\n\n/** A rejected adopt still owns the port it moved here, so close it. */\nfunction closeTransferredPort(msg: ClientMessage): void {\n if (msg.k === \"adopt-sync-peer\") msg.port.close();\n}\n\nexport type ReactorHostOptions = {\n client?: IReactorClient;\n build?: (construct: unknown) => Promise<IReactorClient>;\n registerPackages?: (\n specs: string[],\n sources?: WorkerPackageSource[],\n ) => Promise<void>;\n unregisterPackages?: (names: string[]) => Promise<void>;\n onIdentity?: (user: ReactorIdentity | null) => void;\n onSyncOp?: (method: string, args: unknown[]) => Promise<unknown>;\n onDbOp?: (method: string, args: unknown[]) => Promise<unknown>;\n onInspectorOp?: (method: string, args: unknown[]) => Promise<unknown>;\n /** See `localSyncPeerHandlers`, which builds both over the reactor's registry. */\n onAdoptSyncPeer?: (\n params: AdoptSyncPeerParams,\n port: MessagePort,\n ) => Promise<void>;\n onRemoveSyncPeer?: (params: RemoveSyncPeerParams) => Promise<void>;\n onLiveQuery?: (\n sql: string,\n params: unknown[],\n onResults: (results: unknown) => void,\n ) => Promise<() => void>;\n // Worker identity + restart for the admin/inspector channel.\n namespace?: string;\n appBuildId?: string;\n ownerId?: string;\n bootedAtMs?: number;\n onAdminRestart?: () => void;\n onAdminClearStorage?: () => Promise<void>;\n onAdminMigrate?: () => Promise<void>;\n /** Stops the reactor and releases its stores once the worker is retired. */\n onRetire?: (reason: string) => Promise<void>;\n /** Bounded; a deploy's reload waits on it while data is already refused. */\n drainBeforeReload?: () => Promise<void>;\n};\n\nfunction versionsCompatible(\n a: VersionFingerprint,\n b: VersionFingerprint,\n): boolean {\n return (\n a.appBuildId === b.appBuildId &&\n a.rpcProtocolVersion === b.rpcProtocolVersion &&\n (a.featureFlags ?? \"\") === (b.featureFlags ?? \"\")\n );\n}\n\n// Deterministic per version so every new-build tab converges on one fresh\n// worker; the flags are in it so a flag-only change lands on a fresh one too.\nfunction workerGenForVersion(version: VersionFingerprint): string {\n const flags = version.featureFlags ?? \"\";\n const suffix = flags === \"\" ? \"\" : `-${hashFlags(flags)}`;\n return `v${version.rpcProtocolVersion}-${version.appBuildId}${suffix}`;\n}\n\nconst VERSION_MISMATCH = \"reactor version mismatch\";\nconst FLAGS_CHANGED = \"reactor enforcement flags changed\";\n\n/** Whether a reload reason comes from a build fingerprint mismatch. */\nexport function isFingerprintMismatchReload(reason: string): boolean {\n return reason === VERSION_MISMATCH || reason.startsWith(FLAGS_CHANGED);\n}\n\n/** Names what differs, so a reload is diagnosable from the tab's console. */\nfunction mismatchReason(\n baseline: VersionFingerprint,\n incoming: VersionFingerprint,\n): string {\n if ((baseline.featureFlags ?? \"\") !== (incoming.featureFlags ?? \"\")) {\n return `${FLAGS_CHANGED} (worker: ${\n baseline.featureFlags || \"none\"\n }, tab: ${incoming.featureFlags || \"none\"})`;\n }\n return VERSION_MISMATCH;\n}\n\n// Worker names end up in devtools and IndexedDB keys, so the flag set is\n// reduced to a short stable token rather than spelled out.\nfunction hashFlags(flags: string): string {\n let hash = 0;\n for (let i = 0; i < flags.length; i++) {\n hash = (hash * 31 + flags.charCodeAt(i)) | 0;\n }\n return (hash >>> 0).toString(36);\n}\n\nexport const RETIRED_WORKER_RELOAD_REASON = \"worker retired\";\n\nfunction retiredError(): Error {\n return new Error(\"This worker was retired; reloading into the current one\");\n}\n\nexport class ReactorHost {\n private readonly options: ReactorHostOptions;\n private readonly disposers = new Set<() => void>();\n private readonly clients = new Set<IRpcTransport>();\n private clientPromise: Promise<IReactorClient> | null = null;\n // Ops after a failed build get its error until a hello rebuilds.\n private buildFailure: { error: unknown } | null = null;\n private baseline: VersionFingerprint | null = null;\n private readonly ownerId: string;\n private readonly bootedAtMs: number;\n private migrationState: WorkerMigrationState | null = null;\n private retirement: { reason: string; workerGen: string } | null = null;\n private reloadSent = false;\n\n constructor(options: ReactorHostOptions) {\n this.options = options;\n this.ownerId = options.ownerId ?? crypto.randomUUID();\n this.bootedAtMs = options.bootedAtMs ?? Date.now();\n if (options.client) {\n this.clientPromise = Promise.resolve(options.client);\n }\n }\n\n connect(transport: IRpcTransport): () => void {\n let server: ReactorHostServer | null = null;\n let ready = false;\n const buffer: ClientMessage[] = [];\n const liveSubs = new SubscriptionStore();\n const reply = hostResponder(transport);\n\n const ensureServer = async (construct?: unknown): Promise<void> => {\n if (server) {\n return;\n }\n const client = await this.resolveClient(construct);\n server = new ReactorHostServer(client, transport);\n };\n\n // Drain only after init (server + package registration) completes, in order.\n // Messages arriving mid-drain stay buffered (ready flips last) so order holds.\n const drainBuffer = async (): Promise<void> => {\n while (buffer.length > 0) {\n const message = buffer.shift()!;\n await server!.handleMessage(message);\n }\n ready = true;\n };\n\n const detach = transport.onMessage((message) => {\n const msg = message as ClientMessage;\n if (msg.k === \"ping\") {\n transport.post({\n k: \"pong\",\n id: msg.id,\n ownerId: this.ownerId,\n bootedAtMs: this.bootedAtMs,\n });\n return;\n }\n if (this.migrationState?.status === \"migrating\" && isDataMessage(msg)) {\n // Route the rejection to the kind's owner (sub -> sub-err, etc.).\n closeTransferredPort(msg);\n reply.errForKind(msg, new Error(\"migration in progress\"));\n return;\n }\n // No reload here: a tab past its poisoned-store budget stays put on purpose.\n if (this.retirement && isDataMessage(msg)) {\n closeTransferredPort(msg);\n reply.errForKind(msg, retiredError());\n return;\n }\n if (msg.k === \"hello\") {\n void this.handleHello(msg, transport, reply, ensureServer, drainBuffer);\n return;\n }\n if (msg.k === \"register-packages\") {\n void this.handleRegister(msg, reply);\n return;\n }\n if (msg.k === \"unregister-packages\") {\n void this.handleUnregister(msg, reply);\n return;\n }\n if (msg.k === \"identity\") {\n this.options.onIdentity?.(msg.user);\n return;\n }\n if (msg.k === \"sync-op\") {\n void this.handleOp(msg, this.options.onSyncOp, \"sync\", reply);\n return;\n }\n if (msg.k === \"db-op\") {\n void this.handleOp(msg, this.options.onDbOp, \"db\", reply);\n return;\n }\n if (msg.k === \"inspector-op\") {\n void this.handleOp(msg, this.options.onInspectorOp, \"inspector\", reply);\n return;\n }\n if (msg.k === \"adopt-sync-peer\") {\n void this.handleAdoptSyncPeer(msg, reply);\n return;\n }\n if (msg.k === \"remove-sync-peer\") {\n void this.handleRemoveSyncPeer(msg, reply);\n return;\n }\n if (msg.k === \"sub-live\") {\n void this.handleLiveSubscribe(msg, transport, reply, liveSubs);\n return;\n }\n if (msg.k === \"unsub-live\") {\n liveSubs.end(msg.id);\n return;\n }\n if (msg.k === \"admin\") {\n this.handleAdmin(msg, reply, transport);\n return;\n }\n if (ready && server) {\n void server.handleMessage(msg);\n } else {\n buffer.push(msg);\n }\n });\n\n this.clients.add(transport);\n if (this.migrationState) {\n transport.post({ k: \"migration\", state: this.migrationState });\n }\n // Mid-drain it waits for the broadcast, which reaches it too.\n if (this.retirement && this.reloadSent) {\n transport.post({ k: \"reload\", ...this.retirement });\n }\n if (this.options.client) {\n void ensureServer()\n .then(drainBuffer)\n .catch((error) => {\n console.error(\"ReactorHost buffer drain failed\", error);\n });\n }\n\n const dispose = () => {\n server?.stop();\n detach();\n liveSubs.drain();\n this.clients.delete(transport);\n this.disposers.delete(dispose);\n };\n this.disposers.add(dispose);\n return dispose;\n }\n\n connectPort(port: MessagePort): () => void {\n return this.connect(createPortTransport(port));\n }\n\n // Fan out a reactor bus event to every connected tab, fire-and-forget.\n broadcastBusEvent(eventType: number, event: unknown): void {\n for (const transport of this.clients) {\n transport.post({ k: \"bus-event\", eventType, event });\n }\n }\n\n // Tell every connected tab to reload; `workerGen` makes them adopt one fresh worker name.\n broadcastReload(reason: string, workerGen?: string): void {\n for (const transport of this.clients) {\n transport.post({ k: \"reload\", reason, workerGen });\n }\n }\n\n // A reload this worker never recovers from; tabs that connect later get it too.\n // A deploy's reload waits for the drain: the tabs keep the worker alive.\n retireAndReload(reason: string, workerGen: string): void {\n if (this.retirement) {\n return;\n }\n this.retirement = { reason, workerGen };\n const drain = this.options.drainBeforeReload;\n if (!drain || !isFingerprintMismatchReload(reason)) {\n this.sendReload(reason, workerGen);\n return;\n }\n void this.drainThenReload(drain, reason, workerGen);\n }\n\n private async drainThenReload(\n drain: () => Promise<void>,\n reason: string,\n workerGen: string,\n ): Promise<void> {\n try {\n await drain();\n } catch (error) {\n console.error(\"ReactorHost drain before reload failed\", error);\n }\n this.sendReload(reason, workerGen);\n }\n\n private sendReload(reason: string, workerGen: string): void {\n this.reloadSent = true;\n this.broadcastReload(reason, workerGen);\n this.stopRetired(reason);\n }\n\n private stopRetired(reason: string): void {\n this.options.onRetire?.(reason).catch((error: unknown) => {\n console.error(\"ReactorHost retirement cleanup failed\", error);\n });\n }\n\n // Cache + fan out the worker's migration state so tabs drive the banner from it.\n setMigrationState(state: WorkerMigrationState): void {\n this.migrationState = state;\n for (const transport of this.clients) {\n transport.post({ k: \"migration\", state });\n }\n }\n\n get retired(): boolean {\n return this.retirement !== null;\n }\n\n get connectionCount(): number {\n return this.disposers.size;\n }\n\n private handleAdmin(\n message: RpcAdmin,\n reply: IHostResponder,\n transport: IRpcTransport,\n ): void {\n // A retired worker no longer owns the store: send the tab to the one that does.\n if (this.retirement && message.method !== \"info\") {\n if (this.reloadSent) {\n transport.post({\n k: \"reload\",\n reason: RETIRED_WORKER_RELOAD_REASON,\n workerGen: this.retirement.workerGen,\n });\n }\n reply.err(message.id, retiredError());\n return;\n }\n if (message.method === \"restart\") {\n this.options.onAdminRestart?.();\n reply.ok(message.id);\n return;\n }\n if (message.method === \"clearStorage\") {\n void this.handleAdminAsync(\n this.options.onAdminClearStorage,\n message,\n reply,\n );\n return;\n }\n if (message.method === \"migrate\") {\n void this.handleAdminAsync(this.options.onAdminMigrate, message, reply);\n return;\n }\n const info: WorkerInspectorInfo = {\n namespace: this.options.namespace ?? \"\",\n ownerId: this.ownerId,\n bootedAtMs: this.bootedAtMs,\n connectedClients: this.connectionCount,\n appBuildId:\n this.baseline?.appBuildId ?? this.options.appBuildId ?? \"unknown\",\n rpcProtocolVersion:\n this.baseline?.rpcProtocolVersion ?? RPC_PROTOCOL_VERSION,\n featureFlags: this.baseline?.featureFlags ?? \"\",\n };\n reply.ok(message.id, info);\n }\n\n private async handleAdminAsync(\n handler: (() => Promise<void>) | undefined,\n message: RpcAdmin,\n reply: IHostResponder,\n ): Promise<void> {\n await reply.run(message.id, async () => {\n await handler?.();\n });\n }\n\n private resolveClient(construct?: unknown): Promise<IReactorClient> {\n // A retired worker's client may sit on stopped stores.\n if (this.retirement) {\n return Promise.reject(retiredError());\n }\n if (!this.clientPromise) {\n const build = this.options.build;\n if (!build) {\n return Promise.reject(\n new Error(\"ReactorHost has no client or builder\"),\n );\n }\n const pending = build(construct);\n this.clientPromise = pending;\n this.buildFailure = null;\n // A build outliving the retirement holds stores onRetire left to it.\n void pending.then(\n () => {\n // Mid-drain, the reload's own stop comes after.\n if (this.retirement && this.reloadSent) {\n this.stopRetired(this.retirement.reason);\n }\n },\n () => undefined,\n );\n pending.catch((error: unknown) => {\n if (this.clientPromise === pending) {\n this.clientPromise = null;\n this.buildFailure = { error };\n }\n });\n }\n return this.clientPromise;\n }\n\n private async awaitClientReady(): Promise<void> {\n if (this.clientPromise) {\n await this.clientPromise;\n return;\n }\n if (this.buildFailure) {\n throw this.buildFailure.error;\n }\n }\n\n private requireHandler<T>(\n handler: T | undefined,\n message: ClientMessage,\n reply: IHostResponder,\n label: string,\n ): handler is T {\n if (handler) {\n return true;\n }\n reply.errForKind(message, new Error(`ReactorHost has no ${label} handler`));\n return false;\n }\n\n // A mismatch retires the worker for good: every tab reloads onto one gen.\n private async handleHello(\n message: RpcHello,\n transport: IRpcTransport,\n reply: IHostResponder,\n ensureServer: (construct?: unknown) => Promise<void>,\n drainBuffer: () => Promise<void>,\n ): Promise<void> {\n if (this.baseline) {\n if (!versionsCompatible(this.baseline, message.version)) {\n // Salted per instance: the bare gen can be this worker's own name.\n this.retireAndReload(\n mismatchReason(this.baseline, message.version),\n `${workerGenForVersion(message.version)}-${this.ownerId.slice(0, 8)}`,\n );\n reply.ok(message.id, { ok: false });\n return;\n }\n } else {\n this.baseline = message.version;\n }\n await reply.run(message.id, async () => {\n await ensureServer(message.construct);\n if (message.packages && message.packages.length > 0) {\n await this.options.registerPackages?.(message.packages);\n }\n // Packages are registered; replay buffered data messages in order.\n await drainBuffer();\n });\n }\n\n private async handleRegister(\n message: RpcRegisterPackages,\n reply: IHostResponder,\n ): Promise<void> {\n await reply.run(message.id, async () => {\n await this.options.registerPackages?.(message.specs, message.sources);\n });\n }\n\n private async handleUnregister(\n message: RpcUnregisterPackages,\n reply: IHostResponder,\n ): Promise<void> {\n await reply.run(message.id, async () => {\n await this.options.unregisterPackages?.(message.names);\n });\n }\n\n private async handleOp(\n message: RpcSyncOp | RpcDbOp | RpcInspectorOp,\n handler:\n | ((method: string, args: unknown[]) => Promise<unknown>)\n | undefined,\n label: string,\n reply: IHostResponder,\n ): Promise<void> {\n if (!this.requireHandler(handler, message, reply, label)) {\n return;\n }\n await reply.run(\n message.id,\n async () => {\n await this.awaitClientReady();\n return handler(message.method, message.args);\n },\n (value) => value,\n );\n }\n\n /** Closes the moved port on every failure; the sender can no longer close it. */\n private async handleAdoptSyncPeer(\n message: RpcAdoptSyncPeer,\n reply: IHostResponder,\n ): Promise<void> {\n const handler = this.options.onAdoptSyncPeer;\n if (!handler) {\n closeTransferredPort(message);\n reply.errForKind(\n message,\n new Error(\"ReactorHost has no adopt-sync-peer handler\"),\n );\n return;\n }\n await reply.run(message.id, async () => {\n try {\n await this.awaitClientReady();\n await handler(\n {\n peerId: message.peerId,\n channelName: message.channelName,\n collectionIdKey: message.collectionIdKey,\n remoteName: message.remoteName,\n filter: message.filter,\n },\n message.port,\n );\n } catch (error) {\n closeTransferredPort(message);\n throw error;\n }\n });\n }\n\n private async handleRemoveSyncPeer(\n message: RpcRemoveSyncPeer,\n reply: IHostResponder,\n ): Promise<void> {\n const handler = this.options.onRemoveSyncPeer;\n if (!this.requireHandler(handler, message, reply, \"remove-sync-peer\")) {\n return;\n }\n await reply.run(message.id, async () => {\n await this.awaitClientReady();\n await handler({\n peerId: message.peerId,\n channelName: message.channelName,\n remoteName: message.remoteName,\n });\n });\n }\n\n private async handleLiveSubscribe(\n message: RpcLiveSubscribe,\n transport: IRpcTransport,\n reply: IHostResponder,\n liveSubs: SubscriptionStore,\n ): Promise<void> {\n const handler = this.options.onLiveQuery;\n if (!this.requireHandler(handler, message, reply, \"live-query\")) {\n return;\n }\n const placeholder = () => undefined;\n liveSubs.set(message.id, placeholder);\n try {\n await this.awaitClientReady();\n const unsubscribe = await handler(\n message.sql,\n message.params,\n (results) => {\n transport.post({ k: \"event-live\", id: message.id, results });\n },\n );\n // unsub-live raced ahead during the await: tear down, don't leak.\n if (liveSubs.get(message.id) !== placeholder) {\n unsubscribe();\n return;\n }\n liveSubs.set(message.id, unsubscribe);\n } catch (error) {\n if (liveSubs.get(message.id) === placeholder) {\n liveSubs.delete(message.id);\n }\n reply.errForKind(message, error);\n }\n }\n}\n","import type { IDocumentModelLoader } from \"@powerhousedao/reactor\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { rewritePackageSource } from \"@powerhousedao/shared/connect\";\nimport { RegistryClient } from \"../registry/client.js\";\nimport type { WorkerPackageSource } from \"@powerhousedao/reactor/rpc\";\n\nexport type PackageImporter = (url: string) => Promise<Record<string, unknown>>;\n\nexport type WorkerPackageLoaderOptions = {\n cdnUrl: string;\n importPackage: PackageImporter;\n resolvePackages?: (documentType: string) => Promise<string[]>;\n /** Absolute-URL import map for shared deps (worker import maps don't\n * exist, so the source is rewritten to these URLs and blob-imported). */\n sharedImports?: Record<string, string>;\n /** Import a rewritten source string (blob URL). Only called when a\n * rewrite happened; omit to disable shared-deps loading in a worker. */\n importSource?: (source: string) => Promise<Record<string, unknown>>;\n};\n\nexport type PackageLoadFailure = {\n name: string;\n url: string;\n error: unknown;\n};\n\ntype SourceReplacement =\n | { status: \"replaced\"; types: Set<string> }\n | { status: \"stale\" }\n | { status: \"failed\"; failure: PackageLoadFailure };\n\nconst SOURCE_KEY_PREFIX = \"src:\";\n\n// Keys are registry specs (`name`, `name@1.2.3`, `@scope/name@1.2.3`) or\n// source keys (`src:<name>`, see sourceKey).\nfunction packageName(key: string): string {\n if (key.startsWith(SOURCE_KEY_PREFIX)) {\n return key.slice(SOURCE_KEY_PREFIX.length);\n }\n const at = key.lastIndexOf(\"@\");\n return at > 0 ? key.slice(0, at) : key;\n}\n\nfunction moduleKey(module: DocumentModelModule): string {\n return `${module.documentModel.global.id}@${module.version ?? 1}`;\n}\n\nfunction isDocumentModelModule(value: unknown): value is DocumentModelModule {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const candidate = value as {\n reducer?: unknown;\n documentModel?: { global?: { id?: unknown } };\n };\n return (\n typeof candidate.reducer === \"function\" &&\n typeof candidate.documentModel?.global?.id === \"string\"\n );\n}\n\ntype AnyUpgradeManifest = UpgradeManifest<readonly number[]>;\n\nfunction isUpgradeManifest(value: unknown): value is AnyUpgradeManifest {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const candidate = value as { documentType?: unknown; upgrades?: unknown };\n return (\n typeof candidate.documentType === \"string\" &&\n typeof candidate.upgrades === \"object\" &&\n candidate.upgrades !== null\n );\n}\n\n// Models entries export manifests either as a named array export\n// (`upgradeManifests`) or as individual manifest objects; take both.\nfunction manifestsOf(namespace: Record<string, unknown>): AnyUpgradeManifest[] {\n const out: AnyUpgradeManifest[] = [];\n for (const value of Object.values(namespace)) {\n if (isUpgradeManifest(value)) {\n out.push(value);\n continue;\n }\n if (Array.isArray(value)) {\n for (const inner of value) {\n if (isUpgradeManifest(inner)) out.push(inner);\n }\n }\n }\n return out;\n}\n\nexport class WorkerPackageLoader implements IDocumentModelLoader {\n private readonly cdnUrl: string;\n private readonly importPackage: PackageImporter;\n private readonly resolvePackages: (documentType: string) => Promise<string[]>;\n private readonly sharedImports?: Record<string, string>;\n private readonly importSource?: (\n source: string,\n ) => Promise<Record<string, unknown>>;\n // Keyed by `documentType@version`: a type can ship several module versions\n // side by side, and keying by type alone would evict all but the last.\n private readonly modulesByKey = new Map<string, DocumentModelModule>();\n // Keyed by documentType; the registry replaces manifests per type.\n private readonly manifestsByType = new Map<string, AnyUpgradeManifest>();\n // What each loaded source contributed, so a reload can remove it first.\n private readonly keysBySource = new Map<string, Set<string>>();\n private readonly manifestTypesBySource = new Map<string, Set<string>>();\n private readonly loadedSpecs = new Set<string>();\n private readonly failures: PackageLoadFailure[] = [];\n private readonly pendingLoads = new Map<string, Promise<void>>();\n private readonly generationBySource = new Map<string, number>();\n private generation = 0;\n\n constructor(options: WorkerPackageLoaderOptions) {\n this.cdnUrl = options.cdnUrl.replace(/\\/$/, \"\");\n this.importPackage = options.importPackage;\n this.sharedImports = options.sharedImports;\n this.importSource = options.importSource;\n const registryClient = new RegistryClient(options.cdnUrl);\n this.resolvePackages =\n options.resolvePackages ??\n ((documentType) =>\n registryClient.getPackagesByDocumentType(documentType));\n }\n\n async loadPackages(specs: string[]): Promise<DocumentModelModule[]> {\n await Promise.all(\n [...new Set(specs)].map((spec) => this.loadPackage(spec)),\n );\n return this.models;\n }\n\n /** Loads URL-addressed packages (local project packages). Idempotent. */\n async loadSources(sources: WorkerPackageSource[]): Promise<void> {\n await Promise.all(\n sources.map((source) => this.loadFromUrl(sourceKey(source), source.url)),\n );\n }\n\n /**\n * Replaces previously loaded sources with freshly imported ones (a vetra\n * watch rebuild re-sends the same source under a cache-busted URL). Returns\n * every document type touched - removed, re-added, or new - so the caller\n * can replace the registry's version families. A source whose import fails\n * keeps its previous modules and is reported in `failures`; one superseded\n * by a newer reload of the same source contributes nothing.\n */\n async reloadSources(\n sources: WorkerPackageSource[],\n ): Promise<{ types: string[]; failures: PackageLoadFailure[] }> {\n const results = await Promise.all(\n sources.map((source) =>\n this.replaceSource(sourceKey(source), source.url),\n ),\n );\n const types = new Set<string>();\n const failures: PackageLoadFailure[] = [];\n for (const result of results) {\n if (result.status === \"replaced\") {\n for (const type of result.types) types.add(type);\n } else if (result.status === \"failed\") {\n failures.push(result.failure);\n }\n }\n return { types: [...types], failures };\n }\n\n // On a miss, discover the package(s) for the type and import them on demand.\n async load(documentType: string): Promise<DocumentModelModule> {\n const existing = this.latestForType(documentType);\n if (existing) {\n return existing;\n }\n const packageNames = await this.resolvePackages(documentType);\n const failuresBefore = this.failures.length;\n await Promise.all(\n [...new Set(packageNames)].map((name) => this.loadPackage(name)),\n );\n const loaded = this.latestForType(documentType);\n if (loaded) {\n return loaded;\n }\n throw this.notLoadedError(\n documentType,\n packageNames,\n this.failures.slice(failuresBefore),\n );\n }\n\n get models(): DocumentModelModule[] {\n return [...new Set(this.modulesByKey.values())];\n }\n\n get upgradeManifests(): AnyUpgradeManifest[] {\n return [...this.manifestsByType.values()];\n }\n\n get loadFailures(): PackageLoadFailure[] {\n return [...this.failures];\n }\n\n /** The highest registered version for a type, which is what a bare load resolves to. */\n private latestForType(documentType: string): DocumentModelModule | undefined {\n let latest: DocumentModelModule | undefined;\n for (const module of this.modulesByKey.values()) {\n if (module.documentModel.global.id !== documentType) {\n continue;\n }\n if (!latest || (module.version ?? 1) > (latest.version ?? 1)) {\n latest = module;\n }\n }\n return latest;\n }\n\n private notLoadedError(\n documentType: string,\n packageNames: string[],\n failures: PackageLoadFailure[],\n ): Error {\n if (packageNames.length === 0) {\n return new Error(`No package found for document model: ${documentType}`);\n }\n if (failures.length === 0) {\n return new Error(\n `Imported [${packageNames.join(\", \")}] but document model not found: ${documentType}`,\n );\n }\n const cause =\n failures.length === 1\n ? failures[0].error\n : new AggregateError(failures.map((failure) => failure.error));\n return new Error(\n `Failed to import package(s) [${packageNames.join(\", \")}] for document model: ${documentType}`,\n { cause },\n );\n }\n\n private async loadPackage(spec: string): Promise<void> {\n const name = packageName(spec);\n const url = `${this.cdnUrl}/${name}/browser/document-models/index.js`;\n await this.loadFromUrl(spec, url);\n }\n\n // Concurrent loads of one key share an import; a separate generation would\n // mark the earlier one stale and its caller would miss the module.\n private loadFromUrl(key: string, url: string): Promise<void> {\n if (this.loadedSpecs.has(key)) {\n return Promise.resolve();\n }\n let pending = this.pendingLoads.get(key);\n if (!pending) {\n pending = this.replaceSource(key, url)\n .finally(() => this.pendingLoads.delete(key))\n .then(() => undefined);\n this.pendingLoads.set(key, pending);\n }\n return pending;\n }\n\n // Only the newest call per key commits, and a failed import leaves the\n // key's previous modules, manifests and loaded state untouched.\n private async replaceSource(\n key: string,\n url: string,\n ): Promise<SourceReplacement> {\n const generation = ++this.generation;\n this.generationBySource.set(key, generation);\n let namespace: Record<string, unknown>;\n try {\n namespace = await this.importNamespace(url);\n } catch (error) {\n if (this.generationBySource.get(key) !== generation) {\n return { status: \"stale\" };\n }\n const failure = { name: packageName(key), url, error };\n this.failures.push(failure);\n return { status: \"failed\", failure };\n }\n if (this.generationBySource.get(key) !== generation) {\n return { status: \"stale\" };\n }\n const types = new Set<string>();\n for (const removedKey of this.keysBySource.get(key) ?? []) {\n const removed = this.modulesByKey.get(removedKey);\n if (removed) types.add(removed.documentModel.global.id);\n this.modulesByKey.delete(removedKey);\n }\n for (const type of this.manifestTypesBySource.get(key) ?? []) {\n this.manifestsByType.delete(type);\n }\n for (const added of this.registerNamespace(key, namespace)) {\n types.add(added);\n }\n this.loadedSpecs.add(key);\n return { status: \"replaced\", types };\n }\n\n private async importNamespace(url: string): Promise<Record<string, unknown>> {\n // Shared-deps hosts fetch the source so shared specifiers can be\n // rewritten to absolute vendor URLs (import maps don't apply to blob\n // imports). Packages without shared/relative imports still go through\n // the plain importPackage path below.\n const hasSharedImports =\n this.sharedImports !== undefined &&\n Object.keys(this.sharedImports).length > 0;\n const source = hasSharedImports\n ? await (await fetch(url)).text()\n : undefined;\n const rewritten =\n source !== undefined\n ? rewritePackageSource(source, url, this.sharedImports!)\n : source;\n if (rewritten !== undefined && rewritten !== source) {\n if (!this.importSource) {\n throw new Error(\n \"importSource is required to load a package that imports shared deps\",\n );\n }\n return this.importSource(rewritten);\n }\n return this.importPackage(url);\n }\n\n /** Registers a namespace as the key's whole contribution; returns its module types. */\n private registerNamespace(\n key: string,\n namespace: Record<string, unknown>,\n ): Set<string> {\n const keys = new Set<string>();\n const manifestTypes = new Set<string>();\n const types = new Set<string>();\n for (const value of Object.values(namespace)) {\n if (isDocumentModelModule(value)) {\n const k = moduleKey(value);\n this.modulesByKey.set(k, value);\n keys.add(k);\n types.add(value.documentModel.global.id);\n }\n }\n for (const manifest of manifestsOf(namespace)) {\n this.manifestsByType.set(manifest.documentType, manifest);\n manifestTypes.add(manifest.documentType);\n }\n this.keysBySource.set(key, keys);\n this.manifestTypesBySource.set(key, manifestTypes);\n return types;\n }\n}\n\n// Reloads replace by source NAME: a watch rebuild re-sends the same package\n// under a new cache-busted URL, which must hit the same slot.\nfunction sourceKey(source: WorkerPackageSource): string {\n return `${SOURCE_KEY_PREFIX}${source.name}`;\n}\n"],"mappings":";;;;;AAMA,MAAa,yBAAyB;AAEtC,SAAgB,OAAO,SAA0C;CAC/D,OAAO,QAAQ,WAAW,KAAA,CAAS;AACrC;AAOA,SAAgB,UACd,QACA,MACA,YAAoB,wBACR;CACZ,MAAM,QAAQ,QAAgB,OAAkB,CAAC,MAC/C,OAAO,SAAS,QAAQ;EAAE,GAAG;EAAM;EAAI;EAAQ;CAAK,IAAqB,EACvE,UACF,CAAC;CACH,OAAO;EACL;EACA,WAAW,QAAQ,SAAS,OAAO,KAAK,QAAQ,IAAI,CAAC;CACvD;AACF;;;;ACVA,SAAgB,kBACd,QACA,QACA,MACe;CACf,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AI,IAAY;EAC7B,MAAM,gCAAgB,IAAI,IAAY;EACtC,MAAM,wBAAQ,IAAI,IAAY;EAC9B,KAAK,MAAM,SAAS,OAAO,OAAO,SAAS,GACzC,IAAI,sBAAsB,KAAK,GAAG;GAChC,MAAM,IAAI,UAAU,KAAK;GACzB,KAAK,aAAa,IAAI,GAAG,KAAK;GAC9B,KAAK,IAAI,CAAC;GACV,MAAM,IAAI,MAAM,cAAc,OAAO,EAAE;EACzC;EAEF,KAAK,MAAM,YAAY,YAAY,SAAS,GAAG;GAC7C,KAAK,gBAAgB,IAAI,SAAS,cAAc,QAAQ;GACxD,cAAc,IAAI,SAAS,YAAY;EACzC;EACA,KAAK,aAAa,IAAI,KAAK,IAAI;EAC/B,KAAK,sBAAsB,IAAI,KAAK,aAAa;EACjD,OAAO;CACT;AACF;AAIA,SAAS,UAAU,QAAqC;CACtD,OAAO,GAAG,oBAAoB,OAAO;AACvC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerhousedao/reactor-browser",
|
|
3
|
-
"version": "6.2.3-dev.
|
|
3
|
+
"version": "6.2.3-dev.55",
|
|
4
4
|
"license": "AGPL-3.0-only",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -64,17 +64,17 @@
|
|
|
64
64
|
"sideEffects": false,
|
|
65
65
|
"dependencies": {
|
|
66
66
|
"@ai-sdk/openai-compatible": "3.0.37",
|
|
67
|
-
"@powerhousedao/analytics-engine-browser": "6.2.3-dev.
|
|
68
|
-
"@powerhousedao/analytics-engine-core": "6.2.3-dev.
|
|
69
|
-
"@powerhousedao/reactor": "6.2.3-dev.
|
|
70
|
-
"@powerhousedao/reactor-attachments": "6.2.3-dev.
|
|
71
|
-
"@powerhousedao/reactor-drive": "6.2.3-dev.
|
|
72
|
-
"@powerhousedao/shared": "6.2.3-dev.
|
|
73
|
-
"@renown/sdk": "6.2.3-dev.
|
|
67
|
+
"@powerhousedao/analytics-engine-browser": "6.2.3-dev.55",
|
|
68
|
+
"@powerhousedao/analytics-engine-core": "6.2.3-dev.55",
|
|
69
|
+
"@powerhousedao/reactor": "6.2.3-dev.55",
|
|
70
|
+
"@powerhousedao/reactor-attachments": "6.2.3-dev.55",
|
|
71
|
+
"@powerhousedao/reactor-drive": "6.2.3-dev.55",
|
|
72
|
+
"@powerhousedao/shared": "6.2.3-dev.55",
|
|
73
|
+
"@renown/sdk": "6.2.3-dev.55",
|
|
74
74
|
"@tanstack/react-query": "^5.49.2",
|
|
75
75
|
"ai": "7.0.83",
|
|
76
76
|
"change-case": "5.4.4",
|
|
77
|
-
"document-model": "6.2.3-dev.
|
|
77
|
+
"document-model": "6.2.3-dev.55",
|
|
78
78
|
"graphql-request": "7.4.0",
|
|
79
79
|
"graphql-ws": "6.0.7",
|
|
80
80
|
"kysely": "0.28.16",
|