@powerhousedao/reactor-browser 6.2.3-dev.45 → 6.2.3-dev.46
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/{attachment-service-Dqu-2kwn.d.ts → attachment-service-CkxtGxj8.d.ts} +2 -2
- package/dist/{attachment-service-Dqu-2kwn.d.ts.map → attachment-service-CkxtGxj8.d.ts.map} +1 -1
- package/dist/{dispatch-t-XkZYGh.js → dispatch-C1VVTn5S.js} +2 -2
- package/dist/{dispatch-t-XkZYGh.js.map → dispatch-C1VVTn5S.js.map} +1 -1
- package/dist/{document-by-id-CQZMsJ9I.js → document-by-id-BRDkvmpn.js} +2 -2
- package/dist/{document-by-id-CQZMsJ9I.js.map → document-by-id-BRDkvmpn.js.map} +1 -1
- package/dist/{document-model-modules-Bfi0VEWy.js → document-model-modules-Drsqa5FM.js} +22 -4
- package/dist/{document-model-modules-Bfi0VEWy.js.map → document-model-modules-Drsqa5FM.js.map} +1 -1
- package/dist/{document-operations-DJxHHfWq.js → document-operations-BGUnt-rW.js} +5 -5
- package/dist/{document-operations-DJxHHfWq.js.map → document-operations-BGUnt-rW.js.map} +1 -1
- package/dist/{global-DsTZXSmU.d.ts → global-BUpRlWcM.d.ts} +8 -1
- package/dist/global-BUpRlWcM.d.ts.map +1 -0
- package/dist/{index-x4XYd5DN.d.ts → index-rWaqlBoo.d.ts} +2 -2
- package/dist/{index-x4XYd5DN.d.ts.map → index-rWaqlBoo.d.ts.map} +1 -1
- package/dist/index.d.ts +14 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -9
- package/dist/{make-ph-event-functions-FzpvQtj6.js → make-ph-event-functions-CdsvEl5t.js} +4 -2
- package/dist/{make-ph-event-functions-FzpvQtj6.js.map → make-ph-event-functions-CdsvEl5t.js.map} +1 -1
- package/dist/{renown-C9pYZRqf.js → renown-CPAeJt5L.js} +2 -2
- package/dist/{renown-C9pYZRqf.js.map → renown-CPAeJt5L.js.map} +1 -1
- package/dist/{renown-Def5iO8k.js → renown-D05wkobG.js} +2 -2
- package/dist/{renown-Def5iO8k.js.map → renown-D05wkobG.js.map} +1 -1
- package/dist/src/ai/index.js +2 -2
- package/dist/src/analytics/index.js +1 -1
- package/dist/src/graphql-client/entry.d.ts +2 -2
- package/dist/src/graphql-client/entry.js +3 -3
- package/dist/src/renown/index.d.ts +1 -1
- package/dist/src/renown/index.js +2 -2
- package/dist/src/rpc/index.d.ts +31 -4
- package/dist/src/rpc/index.d.ts.map +1 -1
- package/dist/src/rpc/index.js +126 -17
- package/dist/src/rpc/index.js.map +1 -1
- package/dist/{switchboard-kKDuDWxY.js → switchboard-2L8zxwUX.js} +3 -3
- package/dist/{switchboard-kKDuDWxY.js.map → switchboard-2L8zxwUX.js.map} +1 -1
- package/package.json +9 -9
- package/dist/global-DsTZXSmU.d.ts.map +0 -1
|
@@ -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/admin-client.ts","../../../src/rpc/inspector-proxy.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 {\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 type { MessageRouter } from \"@powerhousedao/reactor/rpc\";\nimport { opChannel } from \"./op-channel.js\";\n\nexport interface IInspectorProxy {\n getQueueState(): Promise<unknown>;\n pauseQueue(): Promise<void>;\n resumeQueue(): Promise<void>;\n getProcessors(): Promise<unknown>;\n retryProcessor(processorId: string): Promise<void>;\n getCatchUpStatus(): Promise<unknown>;\n sweepCatchUp(): Promise<unknown>;\n validateDocument(documentId: string, branch?: string): Promise<unknown>;\n rebuildKeyframes(documentId: string, branch?: string): Promise<unknown>;\n rebuildSnapshots(documentId: string, branch?: string): Promise<unknown>;\n queryReactorDb(sql: string, params?: unknown[]): Promise<unknown>;\n}\n\nexport function createInspectorProxy(router: MessageRouter): IInspectorProxy {\n const ops = opChannel(router, \"inspector-op\");\n\n return {\n getQueueState: () => ops.call(\"queue.getState\"),\n pauseQueue: () => ops.callVoid(\"queue.pause\"),\n resumeQueue: () => ops.callVoid(\"queue.resume\"),\n getProcessors: () => ops.call(\"processors.getAll\"),\n retryProcessor: (processorId) =>\n ops.callVoid(\"processors.retry\", [processorId]),\n getCatchUpStatus: () => ops.call(\"catchUp.status\"),\n sweepCatchUp: () => ops.call(\"catchUp.sweepNow\"),\n validateDocument: (documentId, branch) =>\n ops.call(\"integrity.validate\", [documentId, branch]),\n rebuildKeyframes: (documentId, branch) =>\n ops.call(\"integrity.rebuildKeyframes\", [documentId, branch]),\n rebuildSnapshots: (documentId, branch) =>\n ops.call(\"integrity.rebuildSnapshots\", [documentId, branch]),\n queryReactorDb: (sql, params) => ops.call(\"db.query\", [sql, params ?? []]),\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 SyncEventTypes,\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 implements ISyncManager {\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 async startup(): Promise<void> {\n let lastError: unknown;\n for (let attempt = 0; attempt < SEED_MAX_ATTEMPTS; attempt++) {\n try {\n await this.ensureSeeded();\n return;\n } catch (error) {\n lastError = error;\n if (attempt < SEED_MAX_ATTEMPTS - 1) {\n await new Promise((resolve) =>\n setTimeout(resolve, SEED_RETRY_DELAY_MS),\n );\n }\n }\n }\n throw lastError;\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 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 {\n hostResponder,\n type IHostResponder,\n ReactorHostServer,\n SubscriptionStore,\n type ClientMessage,\n type CorrelationId,\n type ReactorIdentity,\n type RpcAdmin,\n type RpcDbOp,\n type RpcHello,\n type RpcInspectorOp,\n type RpcLiveSubscribe,\n type RpcRegisterPackages,\n type RpcSyncOp,\n type RpcUnregisterPackages,\n type VersionFingerprint,\n type WorkerInspectorInfo,\n type WorkerMigrationState,\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 === \"sub-live\"\n );\n}\n\nexport type ReactorHostOptions = {\n client?: IReactorClient;\n build?: (construct: unknown) => Promise<IReactorClient>;\n registerPackages?: (specs: string[]) => 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 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};\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\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 `reactor enforcement flags changed (worker: ${\n baseline.featureFlags || \"none\"\n }, tab: ${incoming.featureFlags || \"none\"})`;\n }\n return \"reactor version mismatch\";\n}\n\n// Worker names end up in devtools and IndexedDB keys, so the flag set is\n// folded 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 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\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 reply.errForKind(msg, new Error(\"migration in progress\"));\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 === \"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);\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 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 // 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 connectionCount(): number {\n return this.disposers.size;\n }\n\n private handleAdmin(message: RpcAdmin, reply: IHostResponder): void {\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 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 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 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 transport.post({\n k: \"reload\",\n reason: mismatchReason(this.baseline, message.version),\n workerGen: workerGenForVersion(message.version),\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);\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 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 { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport { rewritePackageSource } from \"@powerhousedao/shared/connect\";\nimport { RegistryClient } from \"../registry/client.js\";\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\nfunction packageName(spec: string): string {\n const at = spec.lastIndexOf(\"@\");\n return at > 0 ? spec.slice(0, at) : spec;\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\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 private readonly loadedSpecs = new Set<string>();\n private readonly failures: PackageLoadFailure[] = [];\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 // 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 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 if (this.loadedSpecs.has(spec)) {\n return;\n }\n const name = packageName(spec);\n const url = `${this.cdnUrl}/${name}/browser/document-models/index.js`;\n try {\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 let namespace: Record<string, unknown>;\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 namespace = await this.importSource(rewritten);\n } else {\n namespace = await this.importPackage(url);\n }\n for (const value of Object.values(namespace)) {\n if (isDocumentModelModule(value)) {\n this.modulesByKey.set(moduleKey(value), value);\n }\n }\n this.loadedSpecs.add(spec);\n } catch (error) {\n this.failures.push({ name, url, error });\n }\n }\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,SAA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AAW,IAChB,SAAS,EAAE,CAAC,QACZ,IAAI,eAAe,SAAS,KAAK,YAAY,QAAQ,KAAK,CAAC;EACjE,OAAO,IAAI,MACT,gCAAgC,aAAa,KAAK,IAAI,EAAE,wBAAwB,gBAChF,EAAE,MAAM,CACV;CACF;CAEA,MAAc,YAAY,MAA6B;EACrD,IAAI,KAAK,YAAY,IAAI,IAAI,GAC3B;EAEF,MAAM,OAAO,YAAY,IAAI;EAC7B,MAAM,MAAM,GAAG,KAAK,OAAO,GAAG,KAAK;EACnC,IAAI;GAQF,MAAM,SAFJ,KAAK,kBAAkB,KAAA,KACvB,OAAO,KAAK,KAAK,aAAa,CAAC,CAAC,SAAS,IAEvC,OAAO,MAAM,MAAM,GAAG,EAAA,CAAG,KAAK,IAC9B,KAAA;GACJ,MAAM,YACJ,WAAW,KAAA,IACP,qBAAqB,QAAQ,KAAK,KAAK,aAAc,IACrD;GACN,IAAI;GACJ,IAAI,cAAc,KAAA,KAAa,cAAc,QAAQ;IACnD,IAAI,CAAC,KAAK,cACR,MAAM,IAAI,MACR,qEACF;IAEF,YAAY,MAAM,KAAK,aAAa,SAAS;GAC/C,OACE,YAAY,MAAM,KAAK,cAAc,GAAG;GAE1C,KAAK,MAAM,SAAS,OAAO,OAAO,SAAS,GACzC,IAAI,sBAAsB,KAAK,GAC7B,KAAK,aAAa,IAAI,UAAU,KAAK,GAAG,KAAK;GAGjD,KAAK,YAAY,IAAI,IAAI;EAC3B,SAAS,OAAO;GACd,KAAK,SAAS,KAAK;IAAE;IAAM;IAAK;GAAM,CAAC;EACzC;CACF;AACF"}
|
|
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/admin-client.ts","../../../src/rpc/inspector-proxy.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 {\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 type { MessageRouter } from \"@powerhousedao/reactor/rpc\";\nimport { opChannel } from \"./op-channel.js\";\n\nexport interface IInspectorProxy {\n getQueueState(): Promise<unknown>;\n pauseQueue(): Promise<void>;\n resumeQueue(): Promise<void>;\n getProcessors(): Promise<unknown>;\n retryProcessor(processorId: string): Promise<void>;\n getCatchUpStatus(): Promise<unknown>;\n sweepCatchUp(): Promise<unknown>;\n validateDocument(documentId: string, branch?: string): Promise<unknown>;\n rebuildKeyframes(documentId: string, branch?: string): Promise<unknown>;\n rebuildSnapshots(documentId: string, branch?: string): Promise<unknown>;\n queryReactorDb(sql: string, params?: unknown[]): Promise<unknown>;\n}\n\nexport function createInspectorProxy(router: MessageRouter): IInspectorProxy {\n const ops = opChannel(router, \"inspector-op\");\n\n return {\n getQueueState: () => ops.call(\"queue.getState\"),\n pauseQueue: () => ops.callVoid(\"queue.pause\"),\n resumeQueue: () => ops.callVoid(\"queue.resume\"),\n getProcessors: () => ops.call(\"processors.getAll\"),\n retryProcessor: (processorId) =>\n ops.callVoid(\"processors.retry\", [processorId]),\n getCatchUpStatus: () => ops.call(\"catchUp.status\"),\n sweepCatchUp: () => ops.call(\"catchUp.sweepNow\"),\n validateDocument: (documentId, branch) =>\n ops.call(\"integrity.validate\", [documentId, branch]),\n rebuildKeyframes: (documentId, branch) =>\n ops.call(\"integrity.rebuildKeyframes\", [documentId, branch]),\n rebuildSnapshots: (documentId, branch) =>\n ops.call(\"integrity.rebuildSnapshots\", [documentId, branch]),\n queryReactorDb: (sql, params) => ops.call(\"db.query\", [sql, params ?? []]),\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 SyncEventTypes,\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 implements ISyncManager {\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 async startup(): Promise<void> {\n let lastError: unknown;\n for (let attempt = 0; attempt < SEED_MAX_ATTEMPTS; attempt++) {\n try {\n await this.ensureSeeded();\n return;\n } catch (error) {\n lastError = error;\n if (attempt < SEED_MAX_ATTEMPTS - 1) {\n await new Promise((resolve) =>\n setTimeout(resolve, SEED_RETRY_DELAY_MS),\n );\n }\n }\n }\n throw lastError;\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 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 {\n hostResponder,\n type IHostResponder,\n ReactorHostServer,\n SubscriptionStore,\n type ClientMessage,\n type CorrelationId,\n type ReactorIdentity,\n type RpcAdmin,\n type RpcDbOp,\n type RpcHello,\n type RpcInspectorOp,\n type RpcLiveSubscribe,\n type RpcRegisterPackages,\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 === \"sub-live\"\n );\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 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};\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\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 `reactor enforcement flags changed (worker: ${\n baseline.featureFlags || \"none\"\n }, tab: ${incoming.featureFlags || \"none\"})`;\n }\n return \"reactor version mismatch\";\n}\n\n// Worker names end up in devtools and IndexedDB keys, so the flag set is\n// folded 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 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\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 reply.errForKind(msg, new Error(\"migration in progress\"));\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 === \"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);\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 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 // 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 connectionCount(): number {\n return this.disposers.size;\n }\n\n private handleAdmin(message: RpcAdmin, reply: IHostResponder): void {\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 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 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 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 transport.post({\n k: \"reload\",\n reason: mismatchReason(this.baseline, message.version),\n workerGen: workerGenForVersion(message.version),\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 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;;;;ACZA,SAAgB,wBACd,QACoB;CACpB,IAAI,iBAAuC,EAAE,QAAQ,OAAO;CAC5D,MAAM,qBAAqB,IAA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;AACF;AAIA,SAAS,UAAU,QAAqC;CACtD,OAAO,GAAG,oBAAoB,OAAO;AACvC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as useDocumentsByIds, t as useDocumentById } from "./document-by-id-
|
|
1
|
+
import { B as ambientRenownTokenProvider, L as DocumentTypeMismatchError, R as NoSelectedDocumentError, m as useSelectedDriveSafe, t as useDocumentModelModuleById, y as useSelectedNodeId } from "./document-model-modules-Drsqa5FM.js";
|
|
2
|
+
import { n as useDocumentsByIds, t as useDocumentById } from "./document-by-id-BRDkvmpn.js";
|
|
3
3
|
import { DriveCollectionId, ModuleNotFoundError } from "@powerhousedao/reactor";
|
|
4
4
|
import { isFileNode } from "@powerhousedao/shared/document-drive";
|
|
5
5
|
import { z } from "zod";
|
|
@@ -320,4 +320,4 @@ function createSwitchboardSchemaTool(deps) {
|
|
|
320
320
|
//#endregion
|
|
321
321
|
export { useFolderNodesInSelectedDrive as _, getBrowserSyncManager as a, isFolderNodeKind as b, useSelectedDocument as c, useSelectedDocumentSafe as d, useDocumentOfType as f, useFileNodesInSelectedDrive as g, useDocumentsInSelectedDrive as h, createSwitchboardSchemaTool as i, useSelectedDocumentId as l, useDocumentTypesInSelectedDrive as m, SWITCHBOARD_INTROSPECTION_QUERY as n, resolveDriveSwitchboard as o, useSelectedNode as p, SWITCHBOARD_SCHEMA_TOOL_NAME as r, summarizeIntrospectionSchema as s, GQL_CHANNEL_SUFFIX as t, useSelectedDocumentOfType as u, useNodesInSelectedDrive as v, sortNodesByName as x, isFileNodeKind as y };
|
|
322
322
|
|
|
323
|
-
//# sourceMappingURL=switchboard-
|
|
323
|
+
//# sourceMappingURL=switchboard-2L8zxwUX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"switchboard-kKDuDWxY.js","names":[],"sources":["../src/utils/nodes.ts","../src/hooks/items-in-selected-drive.ts","../src/hooks/selected-node.ts","../src/hooks/document-of-type.ts","../src/hooks/selected-document.ts","../src/ai/switchboard.ts"],"sourcesContent":["import type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\n\n/** Sorts nodes by name. */\nexport function sortNodesByName<T extends Node>(nodes: T[]) {\n return nodes.toSorted((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Returns whether a node is a file. */\nexport function isFileNodeKind(\n node: Node | null | undefined,\n): node is FileNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FILE\";\n}\n\n/** Returns whether a node is a folder. */\nexport function isFolderNodeKind(\n node: Node | null | undefined,\n): node is FolderNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FOLDER\";\n}\n","import type {\n FileNode,\n FolderNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport type {\n DocumentModelDocument,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { isFileNodeKind, isFolderNodeKind } from \"../utils/nodes.js\";\nimport { useDocumentsByIds } from \"./document-by-id.js\";\nimport { useSelectedDriveSafe } from \"./selected-drive.js\";\n\n/** Returns the nodes in the selected drive. */\nexport function useNodesInSelectedDrive() {\n const [selectedDrive] = useSelectedDriveSafe();\n return selectedDrive?.state.global.nodes;\n}\n\n/** Returns the file nodes in the selected drive. */\nexport function useFileNodesInSelectedDrive(): FileNode[] | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.filter((n) => isFileNodeKind(n));\n}\n\n/** Returns the folder nodes in the selected drive. */\nexport function useFolderNodesInSelectedDrive(): FolderNode[] | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.filter((n) => isFolderNodeKind(n));\n}\n\n/** Returns the documents in the selected drive. */\nexport function useDocumentsInSelectedDrive(): PHDocument[] | undefined {\n const fileNodes = useFileNodesInSelectedDrive();\n const fileNodeIds = fileNodes?.map((node) => node.id);\n return useDocumentsByIds(fileNodeIds);\n}\n\n/** Returns the document types supported by the selected drive, as defined by the document model documents present in the drive */\nexport function useDocumentTypesInSelectedDrive() {\n const documentsInSelectedDrive = useDocumentsInSelectedDrive();\n const documentModelDocumentsInSelectedDrive =\n documentsInSelectedDrive?.filter(isDocumentModelDocument);\n const documentTypesFromDocumentModelDocuments =\n documentModelDocumentsInSelectedDrive?.map((doc) => doc.state.global.id);\n return documentTypesFromDocumentModelDocuments;\n}\n\nfunction isDocumentModelDocument(\n document: PHDocument,\n): document is DocumentModelDocument {\n return document.header.documentType === \"powerhouse/document-model\";\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\nimport { useSelectedNodeId } from \"./set-selected-node.js\";\n\nexport {\n addResetSelectedNodeEventHandler,\n addSelectedNodeIdEventHandler,\n addSetSelectedNodeOnPopStateEventHandler,\n setSelectedNode,\n} from \"./set-selected-node.js\";\n\n/** Returns the selected node. */\nexport function useSelectedNode(): Node | undefined {\n const selectedNodeId = useSelectedNodeId();\n const nodes = useNodesInSelectedDrive();\n return nodes?.find((n) => n.id === selectedNodeId);\n}\n","import { ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { DocumentTypeMismatchError } from \"../errors.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentModelModuleById } from \"./document-model-modules.js\";\n\n/** Returns a document of a specific type, throws an error if the found document has a different type */\nexport function useDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentId: string | null | undefined,\n documentType: string | null | undefined,\n) {\n const [document, dispatch] = useDocumentById(documentId);\n const documentModelModule = useDocumentModelModuleById(documentType);\n\n if (!documentId || !documentType) return [];\n\n if (!document) {\n throw new Error(`Document not found: ${documentId}`);\n }\n if (!documentModelModule) {\n throw new ModuleNotFoundError(documentType);\n }\n\n if (document.header.documentType !== documentType) {\n throw new DocumentTypeMismatchError(\n documentId,\n documentType,\n document.header.documentType,\n );\n }\n\n return [document, dispatch] as [TDocument, DocumentDispatch<TAction>];\n}\n","import type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport { isFileNode } from \"@powerhousedao/shared/document-drive\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { NoSelectedDocumentError } from \"../errors.js\";\nimport type { DispatchFn, UseDispatchResult } from \"./dispatch.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentOfType } from \"./document-of-type.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the selected document id */\nexport function useSelectedDocumentId(): string | undefined {\n const selectedNode = useSelectedNode();\n return selectedNode && isFileNode(selectedNode) ? selectedNode.id : undefined;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocument(): readonly [\n PHDocument,\n DispatchFn<Action>,\n] {\n const selectedDocumentId = useSelectedDocumentId();\n const [document, dispatch] = useDocumentById(selectedDocumentId);\n if (!document) {\n throw new NoSelectedDocumentError();\n }\n return [document, dispatch] as const;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocumentSafe(): UseDispatchResult<\n PHDocument,\n Action\n> {\n const selectedDocumentId = useSelectedDocumentId();\n return useDocumentById(selectedDocumentId);\n}\n\n/** Returns the selected document of a specific type, throws an error if the found document has a different type */\nexport function useSelectedDocumentOfType(\n documentType: null | undefined,\n): never[];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(documentType: string): [TDocument, DocumentDispatch<TAction>];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentType: string | null | undefined,\n): never[] | [TDocument, DocumentDispatch<TAction>] {\n const documentId = useSelectedDocumentId();\n\n if (!documentType) {\n return [];\n }\n if (!documentId) {\n throw new NoSelectedDocumentError();\n }\n return useDocumentOfType<TDocument, TAction>(documentId, documentType);\n}\n","import { DriveCollectionId, type ISyncManager } from \"@powerhousedao/reactor\";\nimport { z } from \"zod\";\nimport { ambientRenownTokenProvider } from \"../graphql-client/auth.js\";\nimport type { AiToolDescriptor } from \"./types.js\";\n\n/**\n * The switchboard serving a remote drive: the base URL the browser talks to\n * and its GraphQL supergraph endpoint.\n */\nexport interface DriveSwitchboard {\n /** Switchboard base URL (e.g. `http://localhost:4001`). */\n switchboardUrl: string;\n /** GraphQL supergraph endpoint (`<base>/graphql`). */\n graphqlUrl: string;\n}\n\n/**\n * Reads the tab-side sync manager from the browser global. Returns\n * `undefined` in non-browser environments or before the reactor client\n * module is initialized.\n */\nexport function getBrowserSyncManager(): ISyncManager | undefined {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n return window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n}\n\n/** Suffix of the per-drive GraphQL channel endpoint the switchboard serves. */\nexport const GQL_CHANNEL_SUFFIX = \"/graphql/r\";\n\n/**\n * Resolves the switchboard that serves a drive, if any.\n *\n * Every remote drive stores its switchboard's exact GraphQL channel\n * endpoint in its sync remote — `channelConfig = { type: \"gql\",\n * parameters: { url: \"<origin>/graphql/r\" } }` — and the switchboard base\n * is that URL minus the `/graphql/r` suffix. Deriving it per drive (rather\n * than from a global setting) is what keeps multi-switchboard deployments\n * correct. Drives that are not synced to a remote switchboard (local\n * drives, other channel types, unexpected shapes) return `undefined`.\n */\nexport function resolveDriveSwitchboard(\n driveId: string | undefined,\n syncManager?: ISyncManager,\n): DriveSwitchboard | undefined {\n const manager = syncManager ?? getBrowserSyncManager();\n if (!driveId || !manager) {\n return undefined;\n }\n const collectionId = DriveCollectionId.forDrive(driveId);\n const remote = manager\n .list()\n .find((r) => r.meta.collectionId.equals(collectionId));\n if (!remote) {\n return undefined;\n }\n const { channelConfig } = remote.meta;\n if (channelConfig.type !== \"gql\") {\n return undefined;\n }\n const url = channelConfig.parameters.url;\n if (typeof url !== \"string\" || !url.endsWith(GQL_CHANNEL_SUFFIX)) {\n return undefined;\n }\n const switchboardUrl = url.slice(0, -GQL_CHANNEL_SUFFIX.length);\n return { switchboardUrl, graphqlUrl: `${switchboardUrl}/graphql` };\n}\n\n/** A bounded introspected GraphQL type reference (see the query below). */\ntype IntrospectedTypeRef = {\n kind: string;\n name: string | null;\n ofType?: IntrospectedTypeRef | null;\n};\n\ntype IntrospectedField = {\n name: string;\n description: string | null;\n args: Array<{ name: string; type: IntrospectedTypeRef }>;\n type: IntrospectedTypeRef;\n};\n\ntype IntrospectedRootType = {\n fields: IntrospectedField[] | null;\n} | null;\n\ntype IntrospectedSchema = {\n queryType?: IntrospectedRootType;\n mutationType?: IntrospectedRootType;\n};\n\n/**\n * Introspection over the switchboard supergraph's root query and mutation\n * fields. Types are requested with three levels of `ofType` nesting so\n * that common shapes like `[X!]!` (LIST(NON_NULL(LIST(X)))) render fully.\n */\nexport const SWITCHBOARD_INTROSPECTION_QUERY: string = /* GraphQL */ `\n query SwitchboardIntrospection {\n __schema {\n queryType {\n fields {\n name\n description\n args {\n name\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n mutationType {\n fields {\n name\n description\n args {\n name\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n`;\n\n/**\n * Renders an introspected type reference as a GraphQL type string.\n * Recursion is bounded by the `ofType` nesting of the query, so it always\n * terminates.\n */\nfunction renderTypeRef(type: IntrospectedTypeRef | null | undefined): string {\n if (!type) {\n return \"Unknown\";\n }\n switch (type.kind) {\n case \"NON_NULL\":\n return `${renderTypeRef(type.ofType)}!`;\n case \"LIST\":\n return `[${renderTypeRef(type.ofType)}]`;\n default:\n return type.name ?? \"Unknown\";\n }\n}\n\n/** One root query or mutation field, reduced to a prompt-friendly line. */\nexport type SchemaFieldSummary = {\n name: string;\n description?: string;\n args: string;\n returns: string;\n};\n\n/** Cap on the number of fields reported per root type. */\nconst MAX_FIELDS_PER_ROOT = 200;\n\nfunction summarizeFields(fields: IntrospectedField[] | null | undefined): {\n fields: SchemaFieldSummary[];\n truncated: boolean;\n} {\n const list = fields ?? [];\n return {\n fields: list.slice(0, MAX_FIELDS_PER_ROOT).map((field) => ({\n name: field.name,\n ...(field.description ? { description: field.description } : {}),\n args: field.args\n .map((arg) => `${arg.name}: ${renderTypeRef(arg.type)}`)\n .join(\", \"),\n returns: renderTypeRef(field.type),\n })),\n truncated: list.length > MAX_FIELDS_PER_ROOT,\n };\n}\n\n/**\n * Reduces a GraphQL `__schema` introspection payload (the `data.__schema`\n * object) to a compact summary of its root query and mutation fields.\n * Accepts `unknown` because the payload arrives over the wire.\n */\nexport function summarizeIntrospectionSchema(schema: unknown): {\n queries: SchemaFieldSummary[];\n mutations: SchemaFieldSummary[];\n truncated: boolean;\n} {\n const introspection = (schema ?? {}) as IntrospectedSchema;\n const queries = summarizeFields(introspection.queryType?.fields);\n const mutations = summarizeFields(introspection.mutationType?.fields);\n return {\n queries: queries.fields,\n mutations: mutations.fields,\n truncated: queries.truncated || mutations.truncated,\n };\n}\n\nexport const SWITCHBOARD_SCHEMA_TOOL_NAME = \"getSwitchboardSchema\";\n\n/** Test seams for {@link createSwitchboardSchemaTool}. */\nexport interface SwitchboardToolDeps {\n getSyncManager?: () => ISyncManager | undefined;\n getSelectedDriveId?: () => string | undefined;\n tokenProvider?: () => Promise<string | undefined>;\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n}\n\n/**\n * Creates the read-only `getSwitchboardSchema` tool: it introspects the\n * GraphQL supergraph of the switchboard serving a drive and returns a\n * summary of its root queries and mutations. It reads the schema only and\n * never modifies data.\n */\nexport function createSwitchboardSchemaTool(\n deps?: SwitchboardToolDeps,\n): AiToolDescriptor {\n const getSyncManager = deps?.getSyncManager ?? getBrowserSyncManager;\n const getSelectedDriveId =\n deps?.getSelectedDriveId ??\n ((): string | undefined =>\n typeof window === \"undefined\" ? undefined : window.ph?.selectedDriveId);\n const tokenProvider = deps?.tokenProvider ?? ambientRenownTokenProvider;\n const fetchImpl = deps?.fetchImpl ?? fetch;\n const timeoutMs = deps?.timeoutMs ?? 10_000;\n\n return {\n name: SWITCHBOARD_SCHEMA_TOOL_NAME,\n description:\n \"Introspect the GraphQL endpoint of the switchboard serving a drive and list the queries and mutations it exposes (reactor operations, document-model read models, package subgraphs). Read-only: it reads the schema only and never modifies data. Omit driveId to introspect the currently selected drive.\",\n inputSchema: {\n driveId: z\n .string()\n .describe(\n \"Drive to introspect. Omit to use the currently selected drive.\",\n )\n .optional(),\n },\n annotations: { readOnlyHint: true },\n callback: async (input: { driveId?: string } | undefined) => {\n const driveId = input?.driveId ?? getSelectedDriveId();\n const sb = resolveDriveSwitchboard(driveId, getSyncManager());\n if (!sb) {\n throw new Error(\n driveId\n ? `Drive \"${driveId}\" has no switchboard: it is not synced to a remote switchboard.`\n : \"No drive is currently selected and no driveId was given.\",\n );\n }\n\n const token = await tokenProvider();\n let response: Response;\n try {\n response = await fetchImpl(sb.graphqlUrl, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: JSON.stringify({ query: SWITCHBOARD_INTROSPECTION_QUERY }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} is not reachable: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error },\n );\n }\n\n if (response.status === 401 || response.status === 403) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} refused the request (HTTP ${response.status}). Sign in to the switchboard (Renown) and try again.`,\n );\n }\n if (!response.ok) {\n throw new Error(\n `Switchboard introspection failed: HTTP ${response.status} ${response.statusText} from ${sb.graphqlUrl}`,\n );\n }\n\n const body = (await response.json()) as {\n errors?: Array<{ message?: string }>;\n data?: { __schema?: unknown } | null;\n } | null;\n const schemaErrors = body?.errors;\n if (schemaErrors && schemaErrors.length > 0) {\n throw new Error(\n schemaErrors.map((e) => e.message ?? \"unknown error\").join(\"; \"),\n );\n }\n const schema = body?.data?.__schema as\n | IntrospectedSchema\n | null\n | undefined;\n if (!schema?.queryType) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} did not return a GraphQL schema.`,\n );\n }\n\n const summary = summarizeIntrospectionSchema(schema);\n return {\n switchboardUrl: sb.switchboardUrl,\n graphqlUrl: sb.graphqlUrl,\n ...summary,\n };\n },\n };\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,gBAAgC,OAAY;CAC1D,OAAO,MAAM,UAAU,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,CAAC;AAC9D;;AAGA,SAAgB,eACd,MACkB;CAClB,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KAAK,KAAK,YAAY,MAAM;AACrC;;AAGA,SAAgB,iBACd,MACoB;CACpB,IAAI,CAAC,MAAM,OAAO;CAClB,OAAO,KAAK,KAAK,YAAY,MAAM;AACrC;;;;ACZA,SAAgB,0BAA0B;CACxC,MAAM,CAAC,iBAAiB,qBAAqB;CAC7C,OAAO,eAAe,MAAM,OAAO;AACrC;;AAGA,SAAgB,8BAAsD;CAEpE,OADc,wBACH,CAAC,EAAE,QAAQ,MAAM,eAAe,CAAC,CAAC;AAC/C;;AAGA,SAAgB,gCAA0D;CAExE,OADc,wBACH,CAAC,EAAE,QAAQ,MAAM,iBAAiB,CAAC,CAAC;AACjD;;AAGA,SAAgB,8BAAwD;CAEtE,MAAM,cADY,4BACU,CAAC,EAAE,KAAK,SAAS,KAAK,EAAE;CACpD,OAAO,kBAAkB,WAAW;AACtC;;AAGA,SAAgB,kCAAkC;CAMhD,QALiC,4BAER,CAAC,EAAE,OAAO,uBAAuB,EAAA,EAEjB,KAAK,QAAQ,IAAI,MAAM,OAAO,EAAE;AAE3E;AAEA,SAAS,wBACP,UACmC;CACnC,OAAO,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,GAAG,WAAW,qBAC9B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAEvD,EAAE,OAAO,MAAM,CACjB;GACF;GAEA,IAAI,SAAS,WAAW,OAAO,SAAS,WAAW,KACjD,MAAM,IAAI,MACR,kBAAkB,GAAG,WAAW,6BAA6B,SAAS,OAAO,sDAC/E;GAEF,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MACR,0CAA0C,SAAS,OAAO,GAAG,SAAS,WAAW,QAAQ,GAAG,YAC9F;GAGF,MAAM,OAAQ,MAAM,SAAS,KAAK;GAIlC,MAAM,eAAe,MAAM;GAC3B,IAAI,gBAAgB,aAAa,SAAS,GACxC,MAAM,IAAI,MACR,aAAa,KAAK,MAAM,EAAE,WAAW,eAAe,CAAC,CAAC,KAAK,IAAI,CACjE;GAEF,MAAM,SAAS,MAAM,MAAM;GAI3B,IAAI,CAAC,QAAQ,WACX,MAAM,IAAI,MACR,kBAAkB,GAAG,WAAW,kCAClC;GAGF,MAAM,UAAU,6BAA6B,MAAM;GACnD,OAAO;IACL,gBAAgB,GAAG;IACnB,YAAY,GAAG;IACf,GAAG;GACL;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"switchboard-2L8zxwUX.js","names":[],"sources":["../src/utils/nodes.ts","../src/hooks/items-in-selected-drive.ts","../src/hooks/selected-node.ts","../src/hooks/document-of-type.ts","../src/hooks/selected-document.ts","../src/ai/switchboard.ts"],"sourcesContent":["import type {\n FileNode,\n FolderNode,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\n\n/** Sorts nodes by name. */\nexport function sortNodesByName<T extends Node>(nodes: T[]) {\n return nodes.toSorted((a, b) => a.name.localeCompare(b.name));\n}\n\n/** Returns whether a node is a file. */\nexport function isFileNodeKind(\n node: Node | null | undefined,\n): node is FileNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FILE\";\n}\n\n/** Returns whether a node is a folder. */\nexport function isFolderNodeKind(\n node: Node | null | undefined,\n): node is FolderNode {\n if (!node) return false;\n return node.kind.toUpperCase() === \"FOLDER\";\n}\n","import type {\n FileNode,\n FolderNode,\n} from \"@powerhousedao/shared/document-drive\";\nimport type {\n DocumentModelDocument,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport { isFileNodeKind, isFolderNodeKind } from \"../utils/nodes.js\";\nimport { useDocumentsByIds } from \"./document-by-id.js\";\nimport { useSelectedDriveSafe } from \"./selected-drive.js\";\n\n/** Returns the nodes in the selected drive. */\nexport function useNodesInSelectedDrive() {\n const [selectedDrive] = useSelectedDriveSafe();\n return selectedDrive?.state.global.nodes;\n}\n\n/** Returns the file nodes in the selected drive. */\nexport function useFileNodesInSelectedDrive(): FileNode[] | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.filter((n) => isFileNodeKind(n));\n}\n\n/** Returns the folder nodes in the selected drive. */\nexport function useFolderNodesInSelectedDrive(): FolderNode[] | undefined {\n const nodes = useNodesInSelectedDrive();\n return nodes?.filter((n) => isFolderNodeKind(n));\n}\n\n/** Returns the documents in the selected drive. */\nexport function useDocumentsInSelectedDrive(): PHDocument[] | undefined {\n const fileNodes = useFileNodesInSelectedDrive();\n const fileNodeIds = fileNodes?.map((node) => node.id);\n return useDocumentsByIds(fileNodeIds);\n}\n\n/** Returns the document types supported by the selected drive, as defined by the document model documents present in the drive */\nexport function useDocumentTypesInSelectedDrive() {\n const documentsInSelectedDrive = useDocumentsInSelectedDrive();\n const documentModelDocumentsInSelectedDrive =\n documentsInSelectedDrive?.filter(isDocumentModelDocument);\n const documentTypesFromDocumentModelDocuments =\n documentModelDocumentsInSelectedDrive?.map((doc) => doc.state.global.id);\n return documentTypesFromDocumentModelDocuments;\n}\n\nfunction isDocumentModelDocument(\n document: PHDocument,\n): document is DocumentModelDocument {\n return document.header.documentType === \"powerhouse/document-model\";\n}\n","import type { Node } from \"@powerhousedao/shared/document-drive\";\nimport { useNodesInSelectedDrive } from \"./items-in-selected-drive.js\";\nimport { useSelectedNodeId } from \"./set-selected-node.js\";\n\nexport {\n addResetSelectedNodeEventHandler,\n addSelectedNodeIdEventHandler,\n addSetSelectedNodeOnPopStateEventHandler,\n setSelectedNode,\n} from \"./set-selected-node.js\";\n\n/** Returns the selected node. */\nexport function useSelectedNode(): Node | undefined {\n const selectedNodeId = useSelectedNodeId();\n const nodes = useNodesInSelectedDrive();\n return nodes?.find((n) => n.id === selectedNodeId);\n}\n","import { ModuleNotFoundError } from \"@powerhousedao/reactor\";\nimport type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { DocumentTypeMismatchError } from \"../errors.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentModelModuleById } from \"./document-model-modules.js\";\n\n/** Returns a document of a specific type, throws an error if the found document has a different type */\nexport function useDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentId: string | null | undefined,\n documentType: string | null | undefined,\n) {\n const [document, dispatch] = useDocumentById(documentId);\n const documentModelModule = useDocumentModelModuleById(documentType);\n\n if (!documentId || !documentType) return [];\n\n if (!document) {\n throw new Error(`Document not found: ${documentId}`);\n }\n if (!documentModelModule) {\n throw new ModuleNotFoundError(documentType);\n }\n\n if (document.header.documentType !== documentType) {\n throw new DocumentTypeMismatchError(\n documentId,\n documentType,\n document.header.documentType,\n );\n }\n\n return [document, dispatch] as [TDocument, DocumentDispatch<TAction>];\n}\n","import type { DocumentDispatch } from \"@powerhousedao/reactor-browser\";\nimport { isFileNode } from \"@powerhousedao/shared/document-drive\";\nimport type { Action, PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { NoSelectedDocumentError } from \"../errors.js\";\nimport type { DispatchFn, UseDispatchResult } from \"./dispatch.js\";\nimport { useDocumentById } from \"./document-by-id.js\";\nimport { useDocumentOfType } from \"./document-of-type.js\";\nimport { useSelectedNode } from \"./selected-node.js\";\n\n/** Returns the selected document id */\nexport function useSelectedDocumentId(): string | undefined {\n const selectedNode = useSelectedNode();\n return selectedNode && isFileNode(selectedNode) ? selectedNode.id : undefined;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocument(): readonly [\n PHDocument,\n DispatchFn<Action>,\n] {\n const selectedDocumentId = useSelectedDocumentId();\n const [document, dispatch] = useDocumentById(selectedDocumentId);\n if (!document) {\n throw new NoSelectedDocumentError();\n }\n return [document, dispatch] as const;\n}\n\n/** Returns the selected document. */\nexport function useSelectedDocumentSafe(): UseDispatchResult<\n PHDocument,\n Action\n> {\n const selectedDocumentId = useSelectedDocumentId();\n return useDocumentById(selectedDocumentId);\n}\n\n/** Returns the selected document of a specific type, throws an error if the found document has a different type */\nexport function useSelectedDocumentOfType(\n documentType: null | undefined,\n): never[];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(documentType: string): [TDocument, DocumentDispatch<TAction>];\nexport function useSelectedDocumentOfType<\n TDocument extends PHDocument,\n TAction extends Action,\n>(\n documentType: string | null | undefined,\n): never[] | [TDocument, DocumentDispatch<TAction>] {\n const documentId = useSelectedDocumentId();\n\n if (!documentType) {\n return [];\n }\n if (!documentId) {\n throw new NoSelectedDocumentError();\n }\n return useDocumentOfType<TDocument, TAction>(documentId, documentType);\n}\n","import { DriveCollectionId, type ISyncManager } from \"@powerhousedao/reactor\";\nimport { z } from \"zod\";\nimport { ambientRenownTokenProvider } from \"../graphql-client/auth.js\";\nimport type { AiToolDescriptor } from \"./types.js\";\n\n/**\n * The switchboard serving a remote drive: the base URL the browser talks to\n * and its GraphQL supergraph endpoint.\n */\nexport interface DriveSwitchboard {\n /** Switchboard base URL (e.g. `http://localhost:4001`). */\n switchboardUrl: string;\n /** GraphQL supergraph endpoint (`<base>/graphql`). */\n graphqlUrl: string;\n}\n\n/**\n * Reads the tab-side sync manager from the browser global. Returns\n * `undefined` in non-browser environments or before the reactor client\n * module is initialized.\n */\nexport function getBrowserSyncManager(): ISyncManager | undefined {\n if (typeof window === \"undefined\") {\n return undefined;\n }\n return window.ph?.reactorClientModule?.reactorModule?.syncModule?.syncManager;\n}\n\n/** Suffix of the per-drive GraphQL channel endpoint the switchboard serves. */\nexport const GQL_CHANNEL_SUFFIX = \"/graphql/r\";\n\n/**\n * Resolves the switchboard that serves a drive, if any.\n *\n * Every remote drive stores its switchboard's exact GraphQL channel\n * endpoint in its sync remote — `channelConfig = { type: \"gql\",\n * parameters: { url: \"<origin>/graphql/r\" } }` — and the switchboard base\n * is that URL minus the `/graphql/r` suffix. Deriving it per drive (rather\n * than from a global setting) is what keeps multi-switchboard deployments\n * correct. Drives that are not synced to a remote switchboard (local\n * drives, other channel types, unexpected shapes) return `undefined`.\n */\nexport function resolveDriveSwitchboard(\n driveId: string | undefined,\n syncManager?: ISyncManager,\n): DriveSwitchboard | undefined {\n const manager = syncManager ?? getBrowserSyncManager();\n if (!driveId || !manager) {\n return undefined;\n }\n const collectionId = DriveCollectionId.forDrive(driveId);\n const remote = manager\n .list()\n .find((r) => r.meta.collectionId.equals(collectionId));\n if (!remote) {\n return undefined;\n }\n const { channelConfig } = remote.meta;\n if (channelConfig.type !== \"gql\") {\n return undefined;\n }\n const url = channelConfig.parameters.url;\n if (typeof url !== \"string\" || !url.endsWith(GQL_CHANNEL_SUFFIX)) {\n return undefined;\n }\n const switchboardUrl = url.slice(0, -GQL_CHANNEL_SUFFIX.length);\n return { switchboardUrl, graphqlUrl: `${switchboardUrl}/graphql` };\n}\n\n/** A bounded introspected GraphQL type reference (see the query below). */\ntype IntrospectedTypeRef = {\n kind: string;\n name: string | null;\n ofType?: IntrospectedTypeRef | null;\n};\n\ntype IntrospectedField = {\n name: string;\n description: string | null;\n args: Array<{ name: string; type: IntrospectedTypeRef }>;\n type: IntrospectedTypeRef;\n};\n\ntype IntrospectedRootType = {\n fields: IntrospectedField[] | null;\n} | null;\n\ntype IntrospectedSchema = {\n queryType?: IntrospectedRootType;\n mutationType?: IntrospectedRootType;\n};\n\n/**\n * Introspection over the switchboard supergraph's root query and mutation\n * fields. Types are requested with three levels of `ofType` nesting so\n * that common shapes like `[X!]!` (LIST(NON_NULL(LIST(X)))) render fully.\n */\nexport const SWITCHBOARD_INTROSPECTION_QUERY: string = /* GraphQL */ `\n query SwitchboardIntrospection {\n __schema {\n queryType {\n fields {\n name\n description\n args {\n name\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n mutationType {\n fields {\n name\n description\n args {\n name\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n`;\n\n/**\n * Renders an introspected type reference as a GraphQL type string.\n * Recursion is bounded by the `ofType` nesting of the query, so it always\n * terminates.\n */\nfunction renderTypeRef(type: IntrospectedTypeRef | null | undefined): string {\n if (!type) {\n return \"Unknown\";\n }\n switch (type.kind) {\n case \"NON_NULL\":\n return `${renderTypeRef(type.ofType)}!`;\n case \"LIST\":\n return `[${renderTypeRef(type.ofType)}]`;\n default:\n return type.name ?? \"Unknown\";\n }\n}\n\n/** One root query or mutation field, reduced to a prompt-friendly line. */\nexport type SchemaFieldSummary = {\n name: string;\n description?: string;\n args: string;\n returns: string;\n};\n\n/** Cap on the number of fields reported per root type. */\nconst MAX_FIELDS_PER_ROOT = 200;\n\nfunction summarizeFields(fields: IntrospectedField[] | null | undefined): {\n fields: SchemaFieldSummary[];\n truncated: boolean;\n} {\n const list = fields ?? [];\n return {\n fields: list.slice(0, MAX_FIELDS_PER_ROOT).map((field) => ({\n name: field.name,\n ...(field.description ? { description: field.description } : {}),\n args: field.args\n .map((arg) => `${arg.name}: ${renderTypeRef(arg.type)}`)\n .join(\", \"),\n returns: renderTypeRef(field.type),\n })),\n truncated: list.length > MAX_FIELDS_PER_ROOT,\n };\n}\n\n/**\n * Reduces a GraphQL `__schema` introspection payload (the `data.__schema`\n * object) to a compact summary of its root query and mutation fields.\n * Accepts `unknown` because the payload arrives over the wire.\n */\nexport function summarizeIntrospectionSchema(schema: unknown): {\n queries: SchemaFieldSummary[];\n mutations: SchemaFieldSummary[];\n truncated: boolean;\n} {\n const introspection = (schema ?? {}) as IntrospectedSchema;\n const queries = summarizeFields(introspection.queryType?.fields);\n const mutations = summarizeFields(introspection.mutationType?.fields);\n return {\n queries: queries.fields,\n mutations: mutations.fields,\n truncated: queries.truncated || mutations.truncated,\n };\n}\n\nexport const SWITCHBOARD_SCHEMA_TOOL_NAME = \"getSwitchboardSchema\";\n\n/** Test seams for {@link createSwitchboardSchemaTool}. */\nexport interface SwitchboardToolDeps {\n getSyncManager?: () => ISyncManager | undefined;\n getSelectedDriveId?: () => string | undefined;\n tokenProvider?: () => Promise<string | undefined>;\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n}\n\n/**\n * Creates the read-only `getSwitchboardSchema` tool: it introspects the\n * GraphQL supergraph of the switchboard serving a drive and returns a\n * summary of its root queries and mutations. It reads the schema only and\n * never modifies data.\n */\nexport function createSwitchboardSchemaTool(\n deps?: SwitchboardToolDeps,\n): AiToolDescriptor {\n const getSyncManager = deps?.getSyncManager ?? getBrowserSyncManager;\n const getSelectedDriveId =\n deps?.getSelectedDriveId ??\n ((): string | undefined =>\n typeof window === \"undefined\" ? undefined : window.ph?.selectedDriveId);\n const tokenProvider = deps?.tokenProvider ?? ambientRenownTokenProvider;\n const fetchImpl = deps?.fetchImpl ?? fetch;\n const timeoutMs = deps?.timeoutMs ?? 10_000;\n\n return {\n name: SWITCHBOARD_SCHEMA_TOOL_NAME,\n description:\n \"Introspect the GraphQL endpoint of the switchboard serving a drive and list the queries and mutations it exposes (reactor operations, document-model read models, package subgraphs). Read-only: it reads the schema only and never modifies data. Omit driveId to introspect the currently selected drive.\",\n inputSchema: {\n driveId: z\n .string()\n .describe(\n \"Drive to introspect. Omit to use the currently selected drive.\",\n )\n .optional(),\n },\n annotations: { readOnlyHint: true },\n callback: async (input: { driveId?: string } | undefined) => {\n const driveId = input?.driveId ?? getSelectedDriveId();\n const sb = resolveDriveSwitchboard(driveId, getSyncManager());\n if (!sb) {\n throw new Error(\n driveId\n ? `Drive \"${driveId}\" has no switchboard: it is not synced to a remote switchboard.`\n : \"No drive is currently selected and no driveId was given.\",\n );\n }\n\n const token = await tokenProvider();\n let response: Response;\n try {\n response = await fetchImpl(sb.graphqlUrl, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: JSON.stringify({ query: SWITCHBOARD_INTROSPECTION_QUERY }),\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} is not reachable: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error },\n );\n }\n\n if (response.status === 401 || response.status === 403) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} refused the request (HTTP ${response.status}). Sign in to the switchboard (Renown) and try again.`,\n );\n }\n if (!response.ok) {\n throw new Error(\n `Switchboard introspection failed: HTTP ${response.status} ${response.statusText} from ${sb.graphqlUrl}`,\n );\n }\n\n const body = (await response.json()) as {\n errors?: Array<{ message?: string }>;\n data?: { __schema?: unknown } | null;\n } | null;\n const schemaErrors = body?.errors;\n if (schemaErrors && schemaErrors.length > 0) {\n throw new Error(\n schemaErrors.map((e) => e.message ?? \"unknown error\").join(\"; \"),\n );\n }\n const schema = body?.data?.__schema as\n | IntrospectedSchema\n | null\n | undefined;\n if (!schema?.queryType) {\n throw new Error(\n `Switchboard at ${sb.graphqlUrl} did not return a GraphQL schema.`,\n );\n }\n\n const summary = summarizeIntrospectionSchema(schema);\n return {\n switchboardUrl: sb.switchboardUrl,\n graphqlUrl: sb.graphqlUrl,\n ...summary,\n };\n },\n };\n}\n"],"mappings":";;;;;;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eAAe,MAAM;GAC3B,IAAI,gBAAgB,aAAa,SAAS,GACxC,MAAM,IAAI,MACR,aAAa,KAAK,MAAM,EAAE,WAAW,eAAe,CAAC,CAAC,KAAK,IAAI,CACjE;GAEF,MAAM,SAAS,MAAM,MAAM;GAI3B,IAAI,CAAC,QAAQ,WACX,MAAM,IAAI,MACR,kBAAkB,GAAG,WAAW,kCAClC;GAGF,MAAM,UAAU,6BAA6B,MAAM;GACnD,OAAO;IACL,gBAAgB,GAAG;IACnB,YAAY,GAAG;IACf,GAAG;GACL;EACF;CACF;AACF"}
|
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.46",
|
|
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.46",
|
|
68
|
+
"@powerhousedao/analytics-engine-core": "6.2.3-dev.46",
|
|
69
|
+
"@powerhousedao/reactor": "6.2.3-dev.46",
|
|
70
|
+
"@powerhousedao/reactor-attachments": "6.2.3-dev.46",
|
|
71
|
+
"@powerhousedao/reactor-drive": "6.2.3-dev.46",
|
|
72
|
+
"@powerhousedao/shared": "6.2.3-dev.46",
|
|
73
|
+
"@renown/sdk": "6.2.3-dev.46",
|
|
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.46",
|
|
78
78
|
"graphql-request": "7.4.0",
|
|
79
79
|
"graphql-ws": "6.0.7",
|
|
80
80
|
"kysely": "0.28.16",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"global-DsTZXSmU.d.ts","names":[],"sources":["../src/types/documents.ts","../src/types/reactor-browser-client.ts","../src/types/config.ts","../src/types/modals.ts","../src/types/package-discovery.ts","../src/types/timeline.ts","../src/types/toast.ts","../src/types/vetra.ts","../src/hooks/node-drag-and-drop.ts","../src/types/global.ts"],"mappings":";;;;;;;;;;;;KAOY,iBAAiB,gBAAgB,WAC3C,iBACI,UACA,YACA,iBACA,8BAEJ,YAAY,QAAQ,kBACpB,aAAa,QAAQ;KAGX,iBAAiB,KAAK,QAAQ,KAAK,aAAa;KAEhD,iBAAiB,KAAK,QAAQ;EACxC;EACA,OAAO;;KAGG,gBAAgB,KAAK,QAAQ;EACvC;EACA;;KAGU,aAAa;EAEnB;;EAEA;EAAqB,OAAO;;EAC5B;EAAoB;;;KAGd;EACV;EACA;;UAGe;EACf,IAAI,YAAY,oBAAoB,QAAQ;EAC5C,SAAS,eAAe,oBAAoB,QAAQ;EACpD,UAAU,uBAAuB;;EAEjC,iBAAiB,aAAa;;;KAIpB;;EAEV;;EAEA,qBAAqB;;EAErB;;EAEA;;;;;;;UAQe;;EAEf,mBAAmB,oBAAoB,gBAAgB;;EAEvD,eAAe,oBAAoB,eAAe;;EAElD,mBAAmB,oBAAoB;;EAEvC,qBAAqB;;EAErB,oBAAoB,oBAAoB;;;;;;;;;;;;;;;;;UC/DzB,8BAA8B,KAC7C;;;KCdU,iBAA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