loro-repo 0.18.0 → 0.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -653,6 +653,7 @@ var StreamsTransportAdapter = class {
|
|
|
653
653
|
snapshotCodec: this.options.snapshotCodec,
|
|
654
654
|
snapshotUpload: this.options.snapshotUpload,
|
|
655
655
|
reconnectConfig: this.options.reconnectConfig,
|
|
656
|
+
shardUrls: this.options.shardUrls,
|
|
656
657
|
beforeRemoteCursorSave: onPersistMeta ? async () => {
|
|
657
658
|
await onPersistMeta(flock);
|
|
658
659
|
} : void 0
|
|
@@ -704,6 +705,7 @@ var StreamsTransportAdapter = class {
|
|
|
704
705
|
snapshotCodec: this.options.snapshotCodec,
|
|
705
706
|
snapshotUpload: this.options.snapshotUpload,
|
|
706
707
|
reconnectConfig: this.options.reconnectConfig,
|
|
708
|
+
shardUrls: this.options.shardUrls,
|
|
707
709
|
beforeRemoteCursorSave: onPersistDoc ? async () => {
|
|
708
710
|
await onPersistDoc(docId, doc);
|
|
709
711
|
} : void 0
|
|
@@ -746,6 +748,7 @@ var StreamsTransportAdapter = class {
|
|
|
746
748
|
snapshotCodec: this.options.snapshotCodec,
|
|
747
749
|
snapshotUpload: this.options.snapshotUpload,
|
|
748
750
|
reconnectConfig: this.options.reconnectConfig,
|
|
751
|
+
shardUrls: this.options.shardUrls,
|
|
749
752
|
beforeRemoteCursorSave: onPersistFlockDoc ? async () => {
|
|
750
753
|
await onPersistFlockDoc(flockDocId, flock);
|
|
751
754
|
} : void 0
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streams.cjs","names":["createDebugLogger","InMemoryRemoteCursorStore","rejoinAttempts: Promise<unknown>[]","detachStatusBridge: (() => void) | undefined","joinPromise!: Promise<StreamsTransportSubscription>","streamUrl","session: MetaSession","StreamsCrdt","streamId","session: DocSession","session: FlockDocSession"],"sources":["../../src/transport/streams.ts"],"sourcesContent":["import { LoroDoc } from \"loro-crdt\";\nimport type { Flock } from \"@loro-dev/flock-wasm\";\nimport {\n StreamsCrdt,\n InMemoryRemoteCursorStore,\n createStreamUrl,\n type RemoteCursorStore,\n type SnapshotUploadOptions,\n type SnapshotCodec,\n type StreamsAuthProvider,\n type TransportSubscription as StreamsTransportSubscription,\n type TransportRoomStatus as StreamsRoomStatus,\n type TransportError as StreamsTransportError,\n type JsonObject as StreamsJsonObject,\n} from \"@loro-dev/streams-crdt\";\nimport { createLoroDocAdapter } from \"@loro-dev/streams-crdt/loro\";\nimport { createFlockAdapter } from \"@loro-dev/streams-crdt/flock\";\nimport { createDebugLogger } from \"../internal/debug\";\n\nimport type {\n TransportAdapter,\n TransportJoinParams,\n TransportSubscription,\n TransportSyncResult,\n TransportRoomStatus,\n TransportConnectionStatus,\n} from \"../types\";\n\nconst debug = createDebugLogger(\"transport:streams\");\n\n/**\n * Patches `flock.exportJson` so that an empty `from` version-vector (`{}`)\n * is treated as \"export everything\" (i.e. no `from` constraint).\n *\n * **Root cause:** `encodeVersionVectorForFfi({})` in flock-wasm produces an\n * empty object instead of `undefined`. The WASM layer then treats that as\n * \"everything is up-to-date\" and returns `{}` (no entries).\n *\n * The fix removes the `from` key from the options object entirely so that\n * `exportJson` falls through to a full-export code path. We cannot simply\n * set `from: undefined` because `isExportOptions` checks for the *presence*\n * of the key, causing `exportJsonWithHooks` (async) to be called in a sync\n * context.\n *\n * This can be removed once flock-wasm normalises empty version-vectors.\n */\nfunction patchFlockExportJson(flock: Flock): Flock {\n const orig = flock.exportJson.bind(flock);\n (flock as any).exportJson = (\n arg?: Record<string, unknown>,\n pruneTombstonesBefore?: number,\n ) => {\n if (arg && typeof arg === \"object\" && \"from\" in arg) {\n const from = arg.from;\n if (\n from != null &&\n typeof from === \"object\" &&\n Object.keys(from as object).length === 0\n ) {\n // Strip the `from` key so the call degrades to a full export.\n const { from: _from, ...rest } = arg;\n if (Object.keys(rest).length === 0) {\n return orig();\n }\n return orig(rest as any, pruneTombstonesBefore!);\n }\n }\n return arg === undefined\n ? orig()\n : orig(arg as any, pruneTombstonesBefore!);\n };\n return flock;\n}\n\nexport interface StreamsTransportOptions {\n /** Durable Streams bucket identifier. */\n readonly bucketId: string;\n /** Stream ID for metadata. Defaults to `\"repo-meta\"`. */\n readonly metaStreamId?: string;\n /** Maps a docId to a stream ID. Defaults to the docId itself. */\n readonly docStreamId?: (docId: string) => string;\n /** Maps a Flock doc id to a stream ID. Defaults to `flock:${flockDocId}`. */\n readonly flockDocStreamId?: (flockDocId: string) => string;\n /** Auth provider passed to each `StreamsCrdt` instance. */\n readonly auth: StreamsAuthProvider;\n /** Cursor store for checkpoint persistence. Defaults to `InMemoryRemoteCursorStore`. */\n readonly remoteCursorStore?: RemoteCursorStore;\n /** Auto-create streams on first join/sync. Defaults to `true`. */\n readonly createStreamIfMissing?: boolean;\n /**\n * Called inside `beforeRemoteCursorSave` for document streams.\n * Use this to persist the LoroDoc state via your StorageAdapter before the cursor advances.\n */\n readonly onPersistDoc?: (docId: string, doc: LoroDoc) => Promise<void>;\n /**\n * Called inside `beforeRemoteCursorSave` for Flock document streams.\n */\n readonly onPersistFlockDoc?: (flockDocId: string, flock: Flock) => Promise<void>;\n /**\n * Called inside `beforeRemoteCursorSave` for the metadata stream.\n * Use this to persist the Flock state via your StorageAdapter before the cursor advances.\n */\n readonly onPersistMeta?: (flock: Flock) => Promise<void>;\n /** Optional snapshot upload configuration forwarded to `StreamsCrdt`. */\n readonly snapshotUpload?: SnapshotUploadOptions;\n /** Optional snapshot codec configuration forwarded to `StreamsCrdt`. */\n readonly snapshotCodec?: SnapshotCodec;\n /**\n * Retention duration passed to streams-crdt when a Flock document stream is\n * created. Return `undefined` for persistent streams.\n */\n readonly flockDocStreamTtlMs?:\n | number\n | ((flockDocId: string) => number | undefined);\n /** Optional reconnect configuration forwarded to `StreamsCrdt`. */\n readonly reconnectConfig?: Partial<{\n readonly delays: readonly number[];\n readonly jitterFraction: number;\n readonly maxAttempts: number;\n readonly connectTimeoutMs: number;\n readonly pollTimeoutMs: number;\n }>;\n /** Optional base URL for `createStreamUrl`. */\n readonly baseUrl?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Internal session types\n// ---------------------------------------------------------------------------\n\ntype StreamsSessionBase = {\n stream: StreamsCrdt<StreamsJsonObject>;\n subscription?: StreamsTransportSubscription;\n joinPromise?: Promise<StreamsTransportSubscription>;\n lastJoinError?: Error;\n closed: boolean;\n refCount: number;\n statusEmitter: StatusEmitter;\n};\n\ntype MetaSession = StreamsSessionBase & {\n flock: Flock;\n};\n\ntype DocSession = StreamsSessionBase & {\n doc: LoroDoc;\n docId: string;\n};\n\ntype FlockDocSession = StreamsSessionBase & {\n flock: Flock;\n flockDocId: string;\n};\n\ntype CreateRoomSubscriptionOptions<S extends StreamsSessionBase> = {\n readonly rawSessionPromise: Promise<S>;\n readonly initialStatus: TransportRoomStatus;\n readonly retain: (session: S) => void;\n readonly release: (session: S) => void;\n readonly teardownUnretained: (session: S) => void;\n readonly waitForFirstSync: (session: S) => Promise<void>;\n readonly getActiveSubscription: (\n session: S,\n ) => Promise<StreamsTransportSubscription>;\n readonly rejoin: (session: S) => Promise<void>;\n};\n\ntype JoinSessionOptions<S extends StreamsSessionBase> = {\n readonly isCurrent: (session: S) => boolean;\n readonly createJoinError: (error?: StreamsTransportError) => Error;\n};\n\ntype StatusEmitter = {\n status: TransportRoomStatus;\n listeners: Set<(status: TransportRoomStatus) => void>;\n};\n\nfunction createStatusEmitter(\n initial: TransportRoomStatus = \"connecting\",\n): StatusEmitter {\n return { status: initial, listeners: new Set() };\n}\n\nfunction emitStatus(emitter: StatusEmitter, status: TransportRoomStatus): void {\n emitter.status = status;\n for (const cb of Array.from(emitter.listeners)) {\n try {\n cb(status);\n } catch (error) {\n debug(\"status listener error\", error);\n }\n }\n}\n\nfunction subscribeStatus(\n emitter: StatusEmitter,\n listener: (status: TransportRoomStatus) => void,\n): () => void {\n emitter.listeners.add(listener);\n try {\n listener(emitter.status);\n } catch (error) {\n debug(\"status listener error\", error);\n }\n return () => {\n emitter.listeners.delete(listener);\n };\n}\n\nfunction createSubscriptionClosedError(): Error {\n return new Error(\"subscription closed\");\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction createMetaJoinError(error?: StreamsTransportError): Error {\n return new Error(`Failed to join meta room: ${error?.code ?? \"unknown\"}`);\n}\n\nfunction createDocJoinError(\n docId: string,\n error?: StreamsTransportError,\n): Error {\n return new Error(\n `Failed to join doc room ${docId}: ${error?.code ?? \"unknown\"}`,\n );\n}\n\nfunction createFlockDocJoinError(\n flockDocId: string,\n error?: StreamsTransportError,\n): Error {\n return new Error(\n `Failed to join Flock doc room ${flockDocId}: ${error?.code ?? \"unknown\"}`,\n );\n}\n\nfunction mapStreamsStatus(\n status: StreamsRoomStatus | \"connecting\",\n): TransportRoomStatus {\n switch (status) {\n case \"joined\":\n return \"joined\";\n case \"reconnecting\":\n return \"reconnecting\";\n case \"error\":\n return \"error\";\n case \"connecting\":\n return \"connecting\";\n case \"disconnected\":\n default:\n return \"disconnected\";\n }\n}\n\nfunction mapConnectionStatus(\n status: TransportRoomStatus,\n): TransportConnectionStatus {\n switch (status) {\n case \"connecting\":\n return \"connecting\";\n case \"disconnected\":\n return \"disconnected\";\n case \"joined\":\n return \"connected\";\n case \"error\":\n return \"disconnected\";\n case \"reconnecting\":\n return \"connecting\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// StreamsTransportAdapter\n// ---------------------------------------------------------------------------\n\n/**\n * {@link TransportAdapter} implementation backed by `@loro-dev/streams-crdt`.\n *\n * Uses Durable Streams (HTTP long-poll) for syncing metadata and documents.\n * Ephemeral rooms are not supported.\n */\nexport class StreamsTransportAdapter implements TransportAdapter {\n private readonly options: StreamsTransportOptions;\n private readonly remoteCursorStore: RemoteCursorStore;\n private metaSession?: MetaSession;\n private readonly docSessions = new Map<string, DocSession>();\n private readonly flockDocSessions = new Map<string, FlockDocSession>();\n private connectionStatus: TransportConnectionStatus = \"disconnected\";\n private readonly connectionStatusListeners = new Set<\n (status: TransportConnectionStatus) => void\n >();\n\n constructor(options: StreamsTransportOptions) {\n this.options = options;\n this.remoteCursorStore =\n options.remoteCursorStore ?? new InMemoryRemoteCursorStore();\n }\n\n // -------------------------------------------------------------------------\n // Connection lifecycle\n // -------------------------------------------------------------------------\n\n async connect(): Promise<void> {\n debug(\"connect requested\");\n this.setConnectionStatus(\"connected\");\n }\n\n async close(): Promise<void> {\n debug(\"close requested\");\n\n // Close all doc streams\n for (const [docId, session] of this.docSessions) {\n debug(\"closing doc session\", { docId });\n await this.teardownDocSession(docId, session);\n }\n this.docSessions.clear();\n\n for (const [flockDocId, session] of this.flockDocSessions) {\n debug(\"closing flock doc session\", { flockDocId });\n await this.teardownFlockDocSession(flockDocId, session);\n }\n this.flockDocSessions.clear();\n\n // Close meta stream\n if (this.metaSession) {\n debug(\"closing meta session\");\n await this.teardownMetaSession(this.metaSession);\n this.metaSession = undefined;\n }\n\n this.setConnectionStatus(\"disconnected\");\n debug(\"close completed\");\n }\n\n isConnected(): boolean {\n return this.connectionStatus === \"connected\";\n }\n\n getStatus(): TransportConnectionStatus {\n return this.connectionStatus;\n }\n\n onStatusChange(\n listener: (status: TransportConnectionStatus) => void,\n ): () => void {\n this.connectionStatusListeners.add(listener);\n return () => {\n this.connectionStatusListeners.delete(listener);\n };\n }\n\n getLatency(): number | undefined {\n return undefined;\n }\n\n onLatency(_listener: (latencyMs: number) => void): () => void {\n return () => {};\n }\n\n async reconnect(): Promise<void> {\n debug(\"reconnect requested\");\n this.setConnectionStatus(\"connected\");\n const rejoinAttempts: Promise<unknown>[] = [];\n\n // Re-join disconnected meta session\n if (this.metaSession && !this.metaSession.closed) {\n if (this.metaSession.subscription) {\n const status = this.metaSession.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin meta session\", { status });\n this.metaSession.stream.rejoin();\n }\n } else if (this.metaSession.refCount > 0) {\n debug(\"retry incomplete meta session\");\n rejoinAttempts.push(this.joinMetaSession(this.metaSession));\n }\n }\n\n // Re-join disconnected doc sessions\n for (const [docId, session] of this.docSessions) {\n if (session.closed) continue;\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin doc session\", { docId, status });\n session.stream.rejoin();\n }\n } else if (session.refCount > 0) {\n debug(\"retry incomplete doc session\", { docId });\n rejoinAttempts.push(this.joinDocSession(session));\n }\n }\n\n for (const [flockDocId, session] of this.flockDocSessions) {\n if (session.closed) continue;\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin flock doc session\", { flockDocId, status });\n session.stream.rejoin();\n }\n } else if (session.refCount > 0) {\n debug(\"retry incomplete flock doc session\", { flockDocId });\n rejoinAttempts.push(this.joinFlockDocSession(session));\n }\n }\n\n await Promise.all(rejoinAttempts);\n }\n\n // -------------------------------------------------------------------------\n // Metadata sync / join\n // -------------------------------------------------------------------------\n\n async syncMeta(\n flock: Flock,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncMeta requested\");\n try {\n const session = await this.ensureMetaSession(flock);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncMeta failed\", result.error);\n return { ok: false };\n }\n debug(\"syncMeta completed\");\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncMeta error\", error);\n return { ok: false };\n }\n }\n\n joinMetaRoom(\n flock: Flock,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinMetaRoom requested\");\n\n const existing = this.metaSession;\n const rawSessionPromise = this.ensureMetaSession(flock, params?.auth);\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.flock === flock\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"meta session refCount incremented\", {\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseMetaSession(session),\n teardownUnretained: (session) => {\n if (session.refCount === 0 && this.metaSession === session) {\n void this.teardownMetaSession(session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForMetaFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveMetaSubscription(session),\n rejoin: (session) => this.rejoinMetaSession(session),\n });\n }\n\n // -------------------------------------------------------------------------\n // Document sync / join\n // -------------------------------------------------------------------------\n\n async syncDoc(\n docId: string,\n doc: LoroDoc,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncDoc requested\", { docId });\n try {\n const session = await this.ensureDocSession(docId, doc);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncDoc failed\", { docId, error: result.error });\n return { ok: false };\n }\n debug(\"syncDoc completed\", { docId });\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncDoc error\", { docId, error });\n return { ok: false };\n }\n }\n\n joinDocRoom(\n docId: string,\n doc: LoroDoc,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinDocRoom requested\", { docId });\n\n const existing = this.docSessions.get(docId);\n const rawSessionPromise = this.ensureDocSession(docId, doc, params?.auth);\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.doc === doc\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"doc session refCount incremented\", {\n docId,\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseDocSession(docId, session),\n teardownUnretained: (session) => {\n if (\n session.refCount === 0 &&\n this.docSessions.get(docId) === session\n ) {\n void this.teardownDocSession(docId, session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForDocFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveDocSubscription(session),\n rejoin: (session) => this.rejoinDocSession(session),\n });\n }\n\n async syncFlockDoc(\n flockDocId: string,\n flock: Flock,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncFlockDoc requested\", { flockDocId });\n try {\n const session = await this.ensureFlockDocSession(flockDocId, flock);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncFlockDoc failed\", { flockDocId, error: result.error });\n return { ok: false };\n }\n debug(\"syncFlockDoc completed\", { flockDocId });\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncFlockDoc error\", { flockDocId, error });\n return { ok: false };\n }\n }\n\n joinFlockDocRoom(\n flockDocId: string,\n flock: Flock,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinFlockDocRoom requested\", { flockDocId });\n\n const existing = this.flockDocSessions.get(flockDocId);\n const rawSessionPromise = this.ensureFlockDocSession(\n flockDocId,\n flock,\n params?.auth,\n );\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.flock === flock\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"flock doc session refCount incremented\", {\n flockDocId,\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseFlockDocSession(flockDocId, session),\n teardownUnretained: (session) => {\n if (\n session.refCount === 0 &&\n this.flockDocSessions.get(flockDocId) === session\n ) {\n void this.teardownFlockDocSession(flockDocId, session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForFlockDocFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveFlockDocSubscription(session),\n rejoin: (session) => this.rejoinFlockDocSession(session),\n });\n }\n\n async forgetFlockDoc(flockDocId: string): Promise<void> {\n debug(\"forgetFlockDoc requested\", { flockDocId });\n const session = this.flockDocSessions.get(flockDocId);\n if (session) {\n await this.teardownFlockDocSession(flockDocId, session);\n }\n await this.remoteCursorStore.delete?.(\n this.getFlockDocStreamUrl(flockDocId),\n );\n }\n\n // -------------------------------------------------------------------------\n // Ephemeral (not supported)\n // -------------------------------------------------------------------------\n\n joinEphemeralRoom(\n _roomId: string,\n ): TransportSubscription & { store: import(\"loro-crdt\").EphemeralStore } {\n throw new Error(\"StreamsTransportAdapter does not support ephemeral rooms\");\n }\n\n private createRoomSubscription<S extends StreamsSessionBase>({\n rawSessionPromise,\n initialStatus,\n retain,\n release,\n teardownUnretained,\n waitForFirstSync,\n getActiveSubscription,\n rejoin,\n }: CreateRoomSubscriptionOptions<S>): TransportSubscription {\n const statusProxy = createStatusEmitter(initialStatus);\n let unsubscribed = false;\n let retained = false;\n let detachStatusBridge: (() => void) | undefined;\n\n const sessionPromise = rawSessionPromise\n .then((session) => {\n const forwardStatus = (status: TransportRoomStatus) => {\n emitStatus(statusProxy, status);\n };\n session.statusEmitter.listeners.add(forwardStatus);\n detachStatusBridge = () => {\n session.statusEmitter.listeners.delete(forwardStatus);\n };\n emitStatus(statusProxy, session.statusEmitter.status);\n\n if (unsubscribed || session.closed) {\n detachStatusBridge();\n detachStatusBridge = undefined;\n throw createSubscriptionClosedError();\n }\n\n retain(session);\n retained = true;\n return session;\n })\n .catch((error) => {\n emitStatus(statusProxy, \"error\");\n throw error;\n });\n\n const requireActiveSession = async (): Promise<S> => {\n const session = await sessionPromise;\n if (unsubscribed || session.closed || !retained) {\n throw createSubscriptionClosedError();\n }\n return session;\n };\n\n void sessionPromise\n .then((session) => waitForFirstSync(session))\n .catch(() => {});\n\n return {\n unsubscribe: () => {\n if (unsubscribed) return;\n unsubscribed = true;\n detachStatusBridge?.();\n detachStatusBridge = undefined;\n void rawSessionPromise\n .then((session) => {\n if (retained) {\n release(session);\n } else {\n teardownUnretained(session);\n }\n })\n .catch(() => {});\n },\n get firstSyncedWithRemote() {\n return requireActiveSession().then((session) =>\n waitForFirstSync(session),\n );\n },\n waitUntilSynced: async () => {\n const session = await requireActiveSession();\n const activeSubscription = await getActiveSubscription(session);\n await activeSubscription.waitUntilSynced();\n },\n rejoin: async () => {\n const session = await requireActiveSession();\n await rejoin(session);\n },\n get status(): TransportRoomStatus {\n return statusProxy.status;\n },\n onStatusChange: (listener) => subscribeStatus(statusProxy, listener),\n };\n }\n\n // -------------------------------------------------------------------------\n // Internal: session management\n // -------------------------------------------------------------------------\n\n private resolveAuth(joinAuth?: Uint8Array): StreamsAuthProvider {\n if (joinAuth && joinAuth.length > 0) {\n const token = new TextDecoder().decode(joinAuth);\n return () => token;\n }\n return this.options.auth;\n }\n\n private joinMetaSession(\n session: MetaSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) => this.metaSession === candidate,\n createJoinError: createMetaJoinError,\n });\n }\n\n private joinDocSession(\n session: DocSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) =>\n this.docSessions.get(candidate.docId) === candidate,\n createJoinError: (error) => createDocJoinError(session.docId, error),\n });\n }\n\n private joinFlockDocSession(\n session: FlockDocSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) =>\n this.flockDocSessions.get(candidate.flockDocId) === candidate,\n createJoinError: (error) =>\n createFlockDocJoinError(session.flockDocId, error),\n });\n }\n\n private joinSession<S extends StreamsSessionBase>(\n session: S,\n options: JoinSessionOptions<S>,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n\n let joinPromise!: Promise<StreamsTransportSubscription>;\n joinPromise = (async () => {\n await Promise.resolve();\n try {\n if (session.closed || !options.isCurrent(session)) {\n throw createSubscriptionClosedError();\n }\n\n // Signal transport-level connectivity before the join/sync begins,\n // so consumers can observe a meaningful syncing state while the\n // initial bootstrap is in progress.\n emitStatus(session.statusEmitter, \"connecting\");\n this.setConnectionStatus(\"connected\");\n\n const joinParams = {\n onStatusChange: (status: StreamsRoomStatus | \"connecting\") => {\n const s = mapStreamsStatus(status);\n emitStatus(session.statusEmitter, s);\n this.setConnectionStatus(mapConnectionStatus(s));\n },\n };\n const joinResult = await session.stream.join(joinParams);\n if (!joinResult.ok) {\n if (joinResult.error.retryable) {\n const retainedJoin = await session.stream.join(joinParams);\n if (retainedJoin.ok) {\n return this.retainJoinedSubscription(\n session,\n retainedJoin.value,\n options,\n );\n }\n }\n throw options.createJoinError(joinResult.error);\n }\n\n return this.retainJoinedSubscription(\n session,\n joinResult.value,\n options,\n );\n } catch (error) {\n const normalized = toError(error);\n session.subscription = undefined;\n session.lastJoinError = normalized;\n emitStatus(session.statusEmitter, \"error\");\n this.setConnectionStatus(\"disconnected\");\n throw normalized;\n } finally {\n if (session.joinPromise === joinPromise) {\n session.joinPromise = undefined;\n }\n }\n })();\n session.joinPromise = joinPromise;\n return joinPromise;\n }\n\n private retainJoinedSubscription<S extends StreamsSessionBase>(\n session: S,\n subscription: StreamsTransportSubscription,\n options: JoinSessionOptions<S>,\n ): StreamsTransportSubscription {\n if (session.closed || !options.isCurrent(session)) {\n subscription.unsubscribe();\n throw createSubscriptionClosedError();\n }\n\n session.subscription = subscription;\n session.lastJoinError = undefined;\n const status = mapStreamsStatus(subscription.status);\n emitStatus(session.statusEmitter, status);\n this.setConnectionStatus(mapConnectionStatus(status));\n return subscription;\n }\n\n private getActiveMetaSubscription(\n session: MetaSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ?? new Error(\"meta room is not joined\"),\n );\n }\n\n private async waitForMetaFirstSync(session: MetaSession): Promise<void> {\n const subscription = await this.joinMetaSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createMetaJoinError(subscription.lastError);\n }\n throw error;\n }\n }\n\n private getActiveDocSubscription(\n session: DocSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ?? new Error(`doc room ${session.docId} is not joined`),\n );\n }\n\n private async waitForDocFirstSync(session: DocSession): Promise<void> {\n const subscription = await this.joinDocSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createDocJoinError(session.docId, subscription.lastError);\n }\n throw error;\n }\n }\n\n private getActiveFlockDocSubscription(\n session: FlockDocSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ??\n new Error(`flock doc room ${session.flockDocId} is not joined`),\n );\n }\n\n private async waitForFlockDocFirstSync(\n session: FlockDocSession,\n ): Promise<void> {\n const subscription = await this.joinFlockDocSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createFlockDocJoinError(session.flockDocId, subscription.lastError);\n }\n throw error;\n }\n }\n\n private async rejoinMetaSession(session: MetaSession): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin meta session\", { status });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinMetaSession(session);\n }\n\n private async rejoinDocSession(session: DocSession): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin doc session\", { docId: session.docId, status });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinDocSession(session);\n }\n\n private async rejoinFlockDocSession(\n session: FlockDocSession,\n ): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin flock doc session\", {\n flockDocId: session.flockDocId,\n status,\n });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinFlockDocSession(session);\n }\n\n private releaseMetaSession(session: MetaSession): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"meta session refCount decremented\", {\n refCount: session.refCount,\n });\n if (session.refCount === 0 && this.metaSession === session) {\n debug(\"tearing down meta session (refCount=0)\");\n void this.teardownMetaSession(session).catch(() => {});\n }\n }\n\n private releaseDocSession(docId: string, session: DocSession): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"doc session refCount decremented\", {\n docId,\n refCount: session.refCount,\n });\n if (session.refCount === 0 && this.docSessions.get(docId) === session) {\n debug(\"tearing down doc session (refCount=0)\", { docId });\n void this.teardownDocSession(docId, session).catch(() => {});\n }\n }\n\n private releaseFlockDocSession(\n flockDocId: string,\n session: FlockDocSession,\n ): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"flock doc session refCount decremented\", {\n flockDocId,\n refCount: session.refCount,\n });\n if (\n session.refCount === 0 &&\n this.flockDocSessions.get(flockDocId) === session\n ) {\n debug(\"tearing down flock doc session (refCount=0)\", { flockDocId });\n void this.teardownFlockDocSession(flockDocId, session).catch(() => {});\n }\n }\n\n private async teardownMetaSession(session: MetaSession): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.metaSession === session) {\n this.metaSession = undefined;\n }\n }\n\n private async teardownDocSession(\n docId: string,\n session: DocSession,\n ): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.docSessions.get(docId) === session) {\n this.docSessions.delete(docId);\n }\n }\n\n private async teardownFlockDocSession(\n flockDocId: string,\n session: FlockDocSession,\n ): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.flockDocSessions.get(flockDocId) === session) {\n this.flockDocSessions.delete(flockDocId);\n }\n }\n\n private async ensureMetaSession(\n flock: Flock,\n joinAuth?: Uint8Array,\n ): Promise<MetaSession> {\n if (this.metaSession && this.metaSession.flock === flock) {\n debug(\"reusing meta session\");\n return this.metaSession;\n }\n\n // Tear down previous session if flock instance changed\n if (this.metaSession) {\n debug(\"tearing down previous meta session (flock mismatch)\");\n await this.teardownMetaSession(this.metaSession);\n\n // Delete stale cursor so the new session bootstraps from scratch.\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId: this.options.metaStreamId ?? \"repo-meta\",\n baseUrl: this.options.baseUrl,\n });\n await this.remoteCursorStore.delete?.(streamUrl);\n }\n\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId: this.options.metaStreamId ?? \"repo-meta\",\n baseUrl: this.options.baseUrl,\n });\n debug(\"creating meta StreamsCrdt\", { streamUrl });\n\n const adapter = createFlockAdapter(patchFlockExportJson(flock));\n const { onPersistMeta } = this.options;\n const stream = new StreamsCrdt({\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n beforeRemoteCursorSave: onPersistMeta\n ? async () => {\n await onPersistMeta(flock);\n }\n : undefined,\n });\n\n const session: MetaSession = {\n stream,\n flock,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.metaSession = session;\n return session;\n }\n\n private async ensureDocSession(\n docId: string,\n doc: LoroDoc,\n joinAuth?: Uint8Array,\n ): Promise<DocSession> {\n const existing = this.docSessions.get(docId);\n if (existing && existing.doc === doc) {\n debug(\"reusing doc session\", { docId });\n return existing;\n }\n\n // Tear down previous session if doc instance changed\n if (existing) {\n debug(\"tearing down previous doc session (doc mismatch)\", { docId });\n await this.teardownDocSession(docId, existing);\n\n // Delete stale cursor so the new session bootstraps from scratch.\n // Without this, the cursor would tell StreamsCrdt to resume from a later\n // offset while the new doc is empty, creating a data hole.\n const streamId = this.options.docStreamId?.(docId) ?? docId;\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n await this.remoteCursorStore.delete?.(streamUrl);\n }\n\n const streamId = this.options.docStreamId?.(docId) ?? docId;\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n debug(\"creating doc StreamsCrdt\", { docId, streamUrl });\n\n const adapter = createLoroDocAdapter(doc);\n const { onPersistDoc } = this.options;\n const stream = new StreamsCrdt({\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n beforeRemoteCursorSave: onPersistDoc\n ? async () => {\n await onPersistDoc(docId, doc);\n }\n : undefined,\n });\n\n const session: DocSession = {\n stream,\n doc,\n docId,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.docSessions.set(docId, session);\n return session;\n }\n\n private async ensureFlockDocSession(\n flockDocId: string,\n flock: Flock,\n joinAuth?: Uint8Array,\n ): Promise<FlockDocSession> {\n const existing = this.flockDocSessions.get(flockDocId);\n if (existing && existing.flock === flock) {\n debug(\"reusing flock doc session\", { flockDocId });\n return existing;\n }\n\n if (existing) {\n debug(\"tearing down previous flock doc session (flock mismatch)\", {\n flockDocId,\n });\n await this.teardownFlockDocSession(flockDocId, existing);\n await this.remoteCursorStore.delete?.(\n this.getFlockDocStreamUrl(flockDocId),\n );\n }\n\n const streamUrl = this.getFlockDocStreamUrl(flockDocId);\n debug(\"creating flock doc StreamsCrdt\", { flockDocId, streamUrl });\n\n const adapter = createFlockAdapter(patchFlockExportJson(flock));\n const { onPersistFlockDoc } = this.options;\n const streamOptions = {\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n streamTtlSeconds: this.resolveFlockDocStreamTtlSeconds(flockDocId),\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n beforeRemoteCursorSave: onPersistFlockDoc\n ? async () => {\n await onPersistFlockDoc(flockDocId, flock);\n }\n : undefined,\n };\n const stream = new StreamsCrdt(streamOptions);\n\n const session: FlockDocSession = {\n stream,\n flock,\n flockDocId,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.flockDocSessions.set(flockDocId, session);\n return session;\n }\n\n private getFlockDocStreamUrl(flockDocId: string): string {\n const streamId = this.options.flockDocStreamId?.(flockDocId) ??\n `flock:${flockDocId}`;\n return createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n }\n\n private resolveFlockDocStreamTtlSeconds(\n flockDocId: string,\n ): number | undefined {\n const configured = this.options.flockDocStreamTtlMs;\n const ttlMs =\n typeof configured === \"function\"\n ? configured(flockDocId)\n : configured;\n if (\n typeof ttlMs !== \"number\" ||\n !Number.isFinite(ttlMs) ||\n ttlMs < 0\n ) {\n return undefined;\n }\n return ttlMs === 0 ? 0 : Math.ceil(ttlMs / 1_000);\n }\n\n // -------------------------------------------------------------------------\n // Internal: connection status\n // -------------------------------------------------------------------------\n\n private setConnectionStatus(status: TransportConnectionStatus): void {\n if (this.connectionStatus === status) return;\n this.connectionStatus = status;\n for (const listener of Array.from(this.connectionStatusListeners)) {\n try {\n listener(status);\n } catch (error) {\n debug(\"connection status listener error\", error);\n }\n }\n }\n}\n\nexport type { Transport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sB,KAAK;EAmBnC,MAAMG,UAA2B;GAC/B,QAHa,IAAIH,oCAhBG;IACpB;IACA;IACA,MAAM,KAAK,YAAY,SAAS;IAChC,mBAAmB,KAAK;IACxB,uBAAuB,KAAK,QAAQ,yBAAyB;IAC7D,kBAAkB,KAAK,gCAAgC,WAAW;IAClE,eAAe,KAAK,QAAQ;IAC5B,gBAAgB,KAAK,QAAQ;IAC7B,iBAAiB,KAAK,QAAQ;IAC9B,wBAAwB,oBACpB,YAAY;AACV,WAAM,kBAAkB,YAAY,MAAM;QAE5C;IACL,CAC4C;GAI3C;GACA;GACA,QAAQ;GACR,UAAU;GACV,eAAe,oBAAoB,aAAa;GACjD;AACD,OAAK,iBAAiB,IAAI,YAAY,QAAQ;AAC9C,SAAO;;CAGT,AAAQ,qBAAqB,YAA4B;EACvD,MAAM,WAAW,KAAK,QAAQ,mBAAmB,WAAW,IAC1D,SAAS;AACX,sDAAuB;GACrB,UAAU,KAAK,QAAQ;GACvB;GACA,SAAS,KAAK,QAAQ;GACvB,CAAC;;CAGJ,AAAQ,gCACN,YACoB;EACpB,MAAM,aAAa,KAAK,QAAQ;EAChC,MAAM,QACJ,OAAO,eAAe,aAClB,WAAW,WAAW,GACtB;AACN,MACE,OAAO,UAAU,YACjB,CAAC,OAAO,SAAS,MAAM,IACvB,QAAQ,EAER;AAEF,SAAO,UAAU,IAAI,IAAI,KAAK,KAAK,QAAQ,IAAM;;CAOnD,AAAQ,oBAAoB,QAAyC;AACnE,MAAI,KAAK,qBAAqB,OAAQ;AACtC,OAAK,mBAAmB;AACxB,OAAK,MAAM,YAAY,MAAM,KAAK,KAAK,0BAA0B,CAC/D,KAAI;AACF,YAAS,OAAO;WACT,OAAO;AACd,SAAM,oCAAoC,MAAM"}
|
|
1
|
+
{"version":3,"file":"streams.cjs","names":["createDebugLogger","InMemoryRemoteCursorStore","rejoinAttempts: Promise<unknown>[]","detachStatusBridge: (() => void) | undefined","joinPromise!: Promise<StreamsTransportSubscription>","streamUrl","session: MetaSession","StreamsCrdt","streamId","session: DocSession","session: FlockDocSession"],"sources":["../../src/transport/streams.ts"],"sourcesContent":["import { LoroDoc } from \"loro-crdt\";\nimport type { Flock } from \"@loro-dev/flock-wasm\";\nimport {\n StreamsCrdt,\n InMemoryRemoteCursorStore,\n createStreamUrl,\n type RemoteCursorStore,\n type SnapshotUploadOptions,\n type SnapshotCodec,\n type StreamsCrdtShardUrlsOptions,\n type StreamsAuthProvider,\n type TransportSubscription as StreamsTransportSubscription,\n type TransportRoomStatus as StreamsRoomStatus,\n type TransportError as StreamsTransportError,\n type JsonObject as StreamsJsonObject,\n} from \"@loro-dev/streams-crdt\";\nimport { createLoroDocAdapter } from \"@loro-dev/streams-crdt/loro\";\nimport { createFlockAdapter } from \"@loro-dev/streams-crdt/flock\";\nimport { createDebugLogger } from \"../internal/debug\";\n\nimport type {\n TransportAdapter,\n TransportJoinParams,\n TransportSubscription,\n TransportSyncResult,\n TransportRoomStatus,\n TransportConnectionStatus,\n} from \"../types\";\n\nconst debug = createDebugLogger(\"transport:streams\");\n\n/**\n * Patches `flock.exportJson` so that an empty `from` version-vector (`{}`)\n * is treated as \"export everything\" (i.e. no `from` constraint).\n *\n * **Root cause:** `encodeVersionVectorForFfi({})` in flock-wasm produces an\n * empty object instead of `undefined`. The WASM layer then treats that as\n * \"everything is up-to-date\" and returns `{}` (no entries).\n *\n * The fix removes the `from` key from the options object entirely so that\n * `exportJson` falls through to a full-export code path. We cannot simply\n * set `from: undefined` because `isExportOptions` checks for the *presence*\n * of the key, causing `exportJsonWithHooks` (async) to be called in a sync\n * context.\n *\n * This can be removed once flock-wasm normalises empty version-vectors.\n */\nfunction patchFlockExportJson(flock: Flock): Flock {\n const orig = flock.exportJson.bind(flock);\n (flock as any).exportJson = (\n arg?: Record<string, unknown>,\n pruneTombstonesBefore?: number,\n ) => {\n if (arg && typeof arg === \"object\" && \"from\" in arg) {\n const from = arg.from;\n if (\n from != null &&\n typeof from === \"object\" &&\n Object.keys(from as object).length === 0\n ) {\n // Strip the `from` key so the call degrades to a full export.\n const { from: _from, ...rest } = arg;\n if (Object.keys(rest).length === 0) {\n return orig();\n }\n return orig(rest as any, pruneTombstonesBefore!);\n }\n }\n return arg === undefined\n ? orig()\n : orig(arg as any, pruneTombstonesBefore!);\n };\n return flock;\n}\n\nexport interface StreamsTransportOptions {\n /** Durable Streams bucket identifier. */\n readonly bucketId: string;\n /** Stream ID for metadata. Defaults to `\"repo-meta\"`. */\n readonly metaStreamId?: string;\n /** Maps a docId to a stream ID. Defaults to the docId itself. */\n readonly docStreamId?: (docId: string) => string;\n /** Maps a Flock doc id to a stream ID. Defaults to `flock:${flockDocId}`. */\n readonly flockDocStreamId?: (flockDocId: string) => string;\n /** Auth provider passed to each `StreamsCrdt` instance. */\n readonly auth: StreamsAuthProvider;\n /** Cursor store for checkpoint persistence. Defaults to `InMemoryRemoteCursorStore`. */\n readonly remoteCursorStore?: RemoteCursorStore;\n /** Auto-create streams on first join/sync. Defaults to `true`. */\n readonly createStreamIfMissing?: boolean;\n /**\n * Called inside `beforeRemoteCursorSave` for document streams.\n * Use this to persist the LoroDoc state via your StorageAdapter before the cursor advances.\n */\n readonly onPersistDoc?: (docId: string, doc: LoroDoc) => Promise<void>;\n /**\n * Called inside `beforeRemoteCursorSave` for Flock document streams.\n */\n readonly onPersistFlockDoc?: (flockDocId: string, flock: Flock) => Promise<void>;\n /**\n * Called inside `beforeRemoteCursorSave` for the metadata stream.\n * Use this to persist the Flock state via your StorageAdapter before the cursor advances.\n */\n readonly onPersistMeta?: (flock: Flock) => Promise<void>;\n /** Optional snapshot upload configuration forwarded to `StreamsCrdt`. */\n readonly snapshotUpload?: SnapshotUploadOptions;\n /** Optional snapshot codec configuration forwarded to `StreamsCrdt`. */\n readonly snapshotCodec?: SnapshotCodec;\n /**\n * Retention duration passed to streams-crdt when a Flock document stream is\n * created. Return `undefined` for persistent streams.\n */\n readonly flockDocStreamTtlMs?:\n | number\n | ((flockDocId: string) => number | undefined);\n /** Optional reconnect configuration forwarded to `StreamsCrdt`. */\n readonly reconnectConfig?: Partial<{\n readonly delays: readonly number[];\n readonly jitterFraction: number;\n readonly maxAttempts: number;\n readonly connectTimeoutMs: number;\n readonly pollTimeoutMs: number;\n }>;\n /** Optional base URL for `createStreamUrl`. */\n readonly baseUrl?: string;\n /** Optional request shard origin pools forwarded to `StreamsCrdt`. */\n readonly shardUrls?: StreamsCrdtShardUrlsOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Internal session types\n// ---------------------------------------------------------------------------\n\ntype StreamsSessionBase = {\n stream: StreamsCrdt<StreamsJsonObject>;\n subscription?: StreamsTransportSubscription;\n joinPromise?: Promise<StreamsTransportSubscription>;\n lastJoinError?: Error;\n closed: boolean;\n refCount: number;\n statusEmitter: StatusEmitter;\n};\n\ntype MetaSession = StreamsSessionBase & {\n flock: Flock;\n};\n\ntype DocSession = StreamsSessionBase & {\n doc: LoroDoc;\n docId: string;\n};\n\ntype FlockDocSession = StreamsSessionBase & {\n flock: Flock;\n flockDocId: string;\n};\n\ntype CreateRoomSubscriptionOptions<S extends StreamsSessionBase> = {\n readonly rawSessionPromise: Promise<S>;\n readonly initialStatus: TransportRoomStatus;\n readonly retain: (session: S) => void;\n readonly release: (session: S) => void;\n readonly teardownUnretained: (session: S) => void;\n readonly waitForFirstSync: (session: S) => Promise<void>;\n readonly getActiveSubscription: (\n session: S,\n ) => Promise<StreamsTransportSubscription>;\n readonly rejoin: (session: S) => Promise<void>;\n};\n\ntype JoinSessionOptions<S extends StreamsSessionBase> = {\n readonly isCurrent: (session: S) => boolean;\n readonly createJoinError: (error?: StreamsTransportError) => Error;\n};\n\ntype StatusEmitter = {\n status: TransportRoomStatus;\n listeners: Set<(status: TransportRoomStatus) => void>;\n};\n\nfunction createStatusEmitter(\n initial: TransportRoomStatus = \"connecting\",\n): StatusEmitter {\n return { status: initial, listeners: new Set() };\n}\n\nfunction emitStatus(emitter: StatusEmitter, status: TransportRoomStatus): void {\n emitter.status = status;\n for (const cb of Array.from(emitter.listeners)) {\n try {\n cb(status);\n } catch (error) {\n debug(\"status listener error\", error);\n }\n }\n}\n\nfunction subscribeStatus(\n emitter: StatusEmitter,\n listener: (status: TransportRoomStatus) => void,\n): () => void {\n emitter.listeners.add(listener);\n try {\n listener(emitter.status);\n } catch (error) {\n debug(\"status listener error\", error);\n }\n return () => {\n emitter.listeners.delete(listener);\n };\n}\n\nfunction createSubscriptionClosedError(): Error {\n return new Error(\"subscription closed\");\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction createMetaJoinError(error?: StreamsTransportError): Error {\n return new Error(`Failed to join meta room: ${error?.code ?? \"unknown\"}`);\n}\n\nfunction createDocJoinError(\n docId: string,\n error?: StreamsTransportError,\n): Error {\n return new Error(\n `Failed to join doc room ${docId}: ${error?.code ?? \"unknown\"}`,\n );\n}\n\nfunction createFlockDocJoinError(\n flockDocId: string,\n error?: StreamsTransportError,\n): Error {\n return new Error(\n `Failed to join Flock doc room ${flockDocId}: ${error?.code ?? \"unknown\"}`,\n );\n}\n\nfunction mapStreamsStatus(\n status: StreamsRoomStatus | \"connecting\",\n): TransportRoomStatus {\n switch (status) {\n case \"joined\":\n return \"joined\";\n case \"reconnecting\":\n return \"reconnecting\";\n case \"error\":\n return \"error\";\n case \"connecting\":\n return \"connecting\";\n case \"disconnected\":\n default:\n return \"disconnected\";\n }\n}\n\nfunction mapConnectionStatus(\n status: TransportRoomStatus,\n): TransportConnectionStatus {\n switch (status) {\n case \"connecting\":\n return \"connecting\";\n case \"disconnected\":\n return \"disconnected\";\n case \"joined\":\n return \"connected\";\n case \"error\":\n return \"disconnected\";\n case \"reconnecting\":\n return \"connecting\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// StreamsTransportAdapter\n// ---------------------------------------------------------------------------\n\n/**\n * {@link TransportAdapter} implementation backed by `@loro-dev/streams-crdt`.\n *\n * Uses Durable Streams (HTTP long-poll) for syncing metadata and documents.\n * Ephemeral rooms are not supported.\n */\nexport class StreamsTransportAdapter implements TransportAdapter {\n private readonly options: StreamsTransportOptions;\n private readonly remoteCursorStore: RemoteCursorStore;\n private metaSession?: MetaSession;\n private readonly docSessions = new Map<string, DocSession>();\n private readonly flockDocSessions = new Map<string, FlockDocSession>();\n private connectionStatus: TransportConnectionStatus = \"disconnected\";\n private readonly connectionStatusListeners = new Set<\n (status: TransportConnectionStatus) => void\n >();\n\n constructor(options: StreamsTransportOptions) {\n this.options = options;\n this.remoteCursorStore =\n options.remoteCursorStore ?? new InMemoryRemoteCursorStore();\n }\n\n // -------------------------------------------------------------------------\n // Connection lifecycle\n // -------------------------------------------------------------------------\n\n async connect(): Promise<void> {\n debug(\"connect requested\");\n this.setConnectionStatus(\"connected\");\n }\n\n async close(): Promise<void> {\n debug(\"close requested\");\n\n // Close all doc streams\n for (const [docId, session] of this.docSessions) {\n debug(\"closing doc session\", { docId });\n await this.teardownDocSession(docId, session);\n }\n this.docSessions.clear();\n\n for (const [flockDocId, session] of this.flockDocSessions) {\n debug(\"closing flock doc session\", { flockDocId });\n await this.teardownFlockDocSession(flockDocId, session);\n }\n this.flockDocSessions.clear();\n\n // Close meta stream\n if (this.metaSession) {\n debug(\"closing meta session\");\n await this.teardownMetaSession(this.metaSession);\n this.metaSession = undefined;\n }\n\n this.setConnectionStatus(\"disconnected\");\n debug(\"close completed\");\n }\n\n isConnected(): boolean {\n return this.connectionStatus === \"connected\";\n }\n\n getStatus(): TransportConnectionStatus {\n return this.connectionStatus;\n }\n\n onStatusChange(\n listener: (status: TransportConnectionStatus) => void,\n ): () => void {\n this.connectionStatusListeners.add(listener);\n return () => {\n this.connectionStatusListeners.delete(listener);\n };\n }\n\n getLatency(): number | undefined {\n return undefined;\n }\n\n onLatency(_listener: (latencyMs: number) => void): () => void {\n return () => {};\n }\n\n async reconnect(): Promise<void> {\n debug(\"reconnect requested\");\n this.setConnectionStatus(\"connected\");\n const rejoinAttempts: Promise<unknown>[] = [];\n\n // Re-join disconnected meta session\n if (this.metaSession && !this.metaSession.closed) {\n if (this.metaSession.subscription) {\n const status = this.metaSession.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin meta session\", { status });\n this.metaSession.stream.rejoin();\n }\n } else if (this.metaSession.refCount > 0) {\n debug(\"retry incomplete meta session\");\n rejoinAttempts.push(this.joinMetaSession(this.metaSession));\n }\n }\n\n // Re-join disconnected doc sessions\n for (const [docId, session] of this.docSessions) {\n if (session.closed) continue;\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin doc session\", { docId, status });\n session.stream.rejoin();\n }\n } else if (session.refCount > 0) {\n debug(\"retry incomplete doc session\", { docId });\n rejoinAttempts.push(this.joinDocSession(session));\n }\n }\n\n for (const [flockDocId, session] of this.flockDocSessions) {\n if (session.closed) continue;\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin flock doc session\", { flockDocId, status });\n session.stream.rejoin();\n }\n } else if (session.refCount > 0) {\n debug(\"retry incomplete flock doc session\", { flockDocId });\n rejoinAttempts.push(this.joinFlockDocSession(session));\n }\n }\n\n await Promise.all(rejoinAttempts);\n }\n\n // -------------------------------------------------------------------------\n // Metadata sync / join\n // -------------------------------------------------------------------------\n\n async syncMeta(\n flock: Flock,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncMeta requested\");\n try {\n const session = await this.ensureMetaSession(flock);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncMeta failed\", result.error);\n return { ok: false };\n }\n debug(\"syncMeta completed\");\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncMeta error\", error);\n return { ok: false };\n }\n }\n\n joinMetaRoom(\n flock: Flock,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinMetaRoom requested\");\n\n const existing = this.metaSession;\n const rawSessionPromise = this.ensureMetaSession(flock, params?.auth);\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.flock === flock\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"meta session refCount incremented\", {\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseMetaSession(session),\n teardownUnretained: (session) => {\n if (session.refCount === 0 && this.metaSession === session) {\n void this.teardownMetaSession(session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForMetaFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveMetaSubscription(session),\n rejoin: (session) => this.rejoinMetaSession(session),\n });\n }\n\n // -------------------------------------------------------------------------\n // Document sync / join\n // -------------------------------------------------------------------------\n\n async syncDoc(\n docId: string,\n doc: LoroDoc,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncDoc requested\", { docId });\n try {\n const session = await this.ensureDocSession(docId, doc);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncDoc failed\", { docId, error: result.error });\n return { ok: false };\n }\n debug(\"syncDoc completed\", { docId });\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncDoc error\", { docId, error });\n return { ok: false };\n }\n }\n\n joinDocRoom(\n docId: string,\n doc: LoroDoc,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinDocRoom requested\", { docId });\n\n const existing = this.docSessions.get(docId);\n const rawSessionPromise = this.ensureDocSession(docId, doc, params?.auth);\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.doc === doc\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"doc session refCount incremented\", {\n docId,\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseDocSession(docId, session),\n teardownUnretained: (session) => {\n if (\n session.refCount === 0 &&\n this.docSessions.get(docId) === session\n ) {\n void this.teardownDocSession(docId, session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForDocFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveDocSubscription(session),\n rejoin: (session) => this.rejoinDocSession(session),\n });\n }\n\n async syncFlockDoc(\n flockDocId: string,\n flock: Flock,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncFlockDoc requested\", { flockDocId });\n try {\n const session = await this.ensureFlockDocSession(flockDocId, flock);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncFlockDoc failed\", { flockDocId, error: result.error });\n return { ok: false };\n }\n debug(\"syncFlockDoc completed\", { flockDocId });\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncFlockDoc error\", { flockDocId, error });\n return { ok: false };\n }\n }\n\n joinFlockDocRoom(\n flockDocId: string,\n flock: Flock,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinFlockDocRoom requested\", { flockDocId });\n\n const existing = this.flockDocSessions.get(flockDocId);\n const rawSessionPromise = this.ensureFlockDocSession(\n flockDocId,\n flock,\n params?.auth,\n );\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.flock === flock\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"flock doc session refCount incremented\", {\n flockDocId,\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseFlockDocSession(flockDocId, session),\n teardownUnretained: (session) => {\n if (\n session.refCount === 0 &&\n this.flockDocSessions.get(flockDocId) === session\n ) {\n void this.teardownFlockDocSession(flockDocId, session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForFlockDocFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveFlockDocSubscription(session),\n rejoin: (session) => this.rejoinFlockDocSession(session),\n });\n }\n\n async forgetFlockDoc(flockDocId: string): Promise<void> {\n debug(\"forgetFlockDoc requested\", { flockDocId });\n const session = this.flockDocSessions.get(flockDocId);\n if (session) {\n await this.teardownFlockDocSession(flockDocId, session);\n }\n await this.remoteCursorStore.delete?.(\n this.getFlockDocStreamUrl(flockDocId),\n );\n }\n\n // -------------------------------------------------------------------------\n // Ephemeral (not supported)\n // -------------------------------------------------------------------------\n\n joinEphemeralRoom(\n _roomId: string,\n ): TransportSubscription & { store: import(\"loro-crdt\").EphemeralStore } {\n throw new Error(\"StreamsTransportAdapter does not support ephemeral rooms\");\n }\n\n private createRoomSubscription<S extends StreamsSessionBase>({\n rawSessionPromise,\n initialStatus,\n retain,\n release,\n teardownUnretained,\n waitForFirstSync,\n getActiveSubscription,\n rejoin,\n }: CreateRoomSubscriptionOptions<S>): TransportSubscription {\n const statusProxy = createStatusEmitter(initialStatus);\n let unsubscribed = false;\n let retained = false;\n let detachStatusBridge: (() => void) | undefined;\n\n const sessionPromise = rawSessionPromise\n .then((session) => {\n const forwardStatus = (status: TransportRoomStatus) => {\n emitStatus(statusProxy, status);\n };\n session.statusEmitter.listeners.add(forwardStatus);\n detachStatusBridge = () => {\n session.statusEmitter.listeners.delete(forwardStatus);\n };\n emitStatus(statusProxy, session.statusEmitter.status);\n\n if (unsubscribed || session.closed) {\n detachStatusBridge();\n detachStatusBridge = undefined;\n throw createSubscriptionClosedError();\n }\n\n retain(session);\n retained = true;\n return session;\n })\n .catch((error) => {\n emitStatus(statusProxy, \"error\");\n throw error;\n });\n\n const requireActiveSession = async (): Promise<S> => {\n const session = await sessionPromise;\n if (unsubscribed || session.closed || !retained) {\n throw createSubscriptionClosedError();\n }\n return session;\n };\n\n void sessionPromise\n .then((session) => waitForFirstSync(session))\n .catch(() => {});\n\n return {\n unsubscribe: () => {\n if (unsubscribed) return;\n unsubscribed = true;\n detachStatusBridge?.();\n detachStatusBridge = undefined;\n void rawSessionPromise\n .then((session) => {\n if (retained) {\n release(session);\n } else {\n teardownUnretained(session);\n }\n })\n .catch(() => {});\n },\n get firstSyncedWithRemote() {\n return requireActiveSession().then((session) =>\n waitForFirstSync(session),\n );\n },\n waitUntilSynced: async () => {\n const session = await requireActiveSession();\n const activeSubscription = await getActiveSubscription(session);\n await activeSubscription.waitUntilSynced();\n },\n rejoin: async () => {\n const session = await requireActiveSession();\n await rejoin(session);\n },\n get status(): TransportRoomStatus {\n return statusProxy.status;\n },\n onStatusChange: (listener) => subscribeStatus(statusProxy, listener),\n };\n }\n\n // -------------------------------------------------------------------------\n // Internal: session management\n // -------------------------------------------------------------------------\n\n private resolveAuth(joinAuth?: Uint8Array): StreamsAuthProvider {\n if (joinAuth && joinAuth.length > 0) {\n const token = new TextDecoder().decode(joinAuth);\n return () => token;\n }\n return this.options.auth;\n }\n\n private joinMetaSession(\n session: MetaSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) => this.metaSession === candidate,\n createJoinError: createMetaJoinError,\n });\n }\n\n private joinDocSession(\n session: DocSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) =>\n this.docSessions.get(candidate.docId) === candidate,\n createJoinError: (error) => createDocJoinError(session.docId, error),\n });\n }\n\n private joinFlockDocSession(\n session: FlockDocSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) =>\n this.flockDocSessions.get(candidate.flockDocId) === candidate,\n createJoinError: (error) =>\n createFlockDocJoinError(session.flockDocId, error),\n });\n }\n\n private joinSession<S extends StreamsSessionBase>(\n session: S,\n options: JoinSessionOptions<S>,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n\n let joinPromise!: Promise<StreamsTransportSubscription>;\n joinPromise = (async () => {\n await Promise.resolve();\n try {\n if (session.closed || !options.isCurrent(session)) {\n throw createSubscriptionClosedError();\n }\n\n // Signal transport-level connectivity before the join/sync begins,\n // so consumers can observe a meaningful syncing state while the\n // initial bootstrap is in progress.\n emitStatus(session.statusEmitter, \"connecting\");\n this.setConnectionStatus(\"connected\");\n\n const joinParams = {\n onStatusChange: (status: StreamsRoomStatus | \"connecting\") => {\n const s = mapStreamsStatus(status);\n emitStatus(session.statusEmitter, s);\n this.setConnectionStatus(mapConnectionStatus(s));\n },\n };\n const joinResult = await session.stream.join(joinParams);\n if (!joinResult.ok) {\n if (joinResult.error.retryable) {\n const retainedJoin = await session.stream.join(joinParams);\n if (retainedJoin.ok) {\n return this.retainJoinedSubscription(\n session,\n retainedJoin.value,\n options,\n );\n }\n }\n throw options.createJoinError(joinResult.error);\n }\n\n return this.retainJoinedSubscription(\n session,\n joinResult.value,\n options,\n );\n } catch (error) {\n const normalized = toError(error);\n session.subscription = undefined;\n session.lastJoinError = normalized;\n emitStatus(session.statusEmitter, \"error\");\n this.setConnectionStatus(\"disconnected\");\n throw normalized;\n } finally {\n if (session.joinPromise === joinPromise) {\n session.joinPromise = undefined;\n }\n }\n })();\n session.joinPromise = joinPromise;\n return joinPromise;\n }\n\n private retainJoinedSubscription<S extends StreamsSessionBase>(\n session: S,\n subscription: StreamsTransportSubscription,\n options: JoinSessionOptions<S>,\n ): StreamsTransportSubscription {\n if (session.closed || !options.isCurrent(session)) {\n subscription.unsubscribe();\n throw createSubscriptionClosedError();\n }\n\n session.subscription = subscription;\n session.lastJoinError = undefined;\n const status = mapStreamsStatus(subscription.status);\n emitStatus(session.statusEmitter, status);\n this.setConnectionStatus(mapConnectionStatus(status));\n return subscription;\n }\n\n private getActiveMetaSubscription(\n session: MetaSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ?? new Error(\"meta room is not joined\"),\n );\n }\n\n private async waitForMetaFirstSync(session: MetaSession): Promise<void> {\n const subscription = await this.joinMetaSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createMetaJoinError(subscription.lastError);\n }\n throw error;\n }\n }\n\n private getActiveDocSubscription(\n session: DocSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ?? new Error(`doc room ${session.docId} is not joined`),\n );\n }\n\n private async waitForDocFirstSync(session: DocSession): Promise<void> {\n const subscription = await this.joinDocSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createDocJoinError(session.docId, subscription.lastError);\n }\n throw error;\n }\n }\n\n private getActiveFlockDocSubscription(\n session: FlockDocSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ??\n new Error(`flock doc room ${session.flockDocId} is not joined`),\n );\n }\n\n private async waitForFlockDocFirstSync(\n session: FlockDocSession,\n ): Promise<void> {\n const subscription = await this.joinFlockDocSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createFlockDocJoinError(session.flockDocId, subscription.lastError);\n }\n throw error;\n }\n }\n\n private async rejoinMetaSession(session: MetaSession): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin meta session\", { status });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinMetaSession(session);\n }\n\n private async rejoinDocSession(session: DocSession): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin doc session\", { docId: session.docId, status });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinDocSession(session);\n }\n\n private async rejoinFlockDocSession(\n session: FlockDocSession,\n ): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin flock doc session\", {\n flockDocId: session.flockDocId,\n status,\n });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinFlockDocSession(session);\n }\n\n private releaseMetaSession(session: MetaSession): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"meta session refCount decremented\", {\n refCount: session.refCount,\n });\n if (session.refCount === 0 && this.metaSession === session) {\n debug(\"tearing down meta session (refCount=0)\");\n void this.teardownMetaSession(session).catch(() => {});\n }\n }\n\n private releaseDocSession(docId: string, session: DocSession): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"doc session refCount decremented\", {\n docId,\n refCount: session.refCount,\n });\n if (session.refCount === 0 && this.docSessions.get(docId) === session) {\n debug(\"tearing down doc session (refCount=0)\", { docId });\n void this.teardownDocSession(docId, session).catch(() => {});\n }\n }\n\n private releaseFlockDocSession(\n flockDocId: string,\n session: FlockDocSession,\n ): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"flock doc session refCount decremented\", {\n flockDocId,\n refCount: session.refCount,\n });\n if (\n session.refCount === 0 &&\n this.flockDocSessions.get(flockDocId) === session\n ) {\n debug(\"tearing down flock doc session (refCount=0)\", { flockDocId });\n void this.teardownFlockDocSession(flockDocId, session).catch(() => {});\n }\n }\n\n private async teardownMetaSession(session: MetaSession): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.metaSession === session) {\n this.metaSession = undefined;\n }\n }\n\n private async teardownDocSession(\n docId: string,\n session: DocSession,\n ): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.docSessions.get(docId) === session) {\n this.docSessions.delete(docId);\n }\n }\n\n private async teardownFlockDocSession(\n flockDocId: string,\n session: FlockDocSession,\n ): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.flockDocSessions.get(flockDocId) === session) {\n this.flockDocSessions.delete(flockDocId);\n }\n }\n\n private async ensureMetaSession(\n flock: Flock,\n joinAuth?: Uint8Array,\n ): Promise<MetaSession> {\n if (this.metaSession && this.metaSession.flock === flock) {\n debug(\"reusing meta session\");\n return this.metaSession;\n }\n\n // Tear down previous session if flock instance changed\n if (this.metaSession) {\n debug(\"tearing down previous meta session (flock mismatch)\");\n await this.teardownMetaSession(this.metaSession);\n\n // Delete stale cursor so the new session bootstraps from scratch.\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId: this.options.metaStreamId ?? \"repo-meta\",\n baseUrl: this.options.baseUrl,\n });\n await this.remoteCursorStore.delete?.(streamUrl);\n }\n\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId: this.options.metaStreamId ?? \"repo-meta\",\n baseUrl: this.options.baseUrl,\n });\n debug(\"creating meta StreamsCrdt\", { streamUrl });\n\n const adapter = createFlockAdapter(patchFlockExportJson(flock));\n const { onPersistMeta } = this.options;\n const stream = new StreamsCrdt({\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n shardUrls: this.options.shardUrls,\n beforeRemoteCursorSave: onPersistMeta\n ? async () => {\n await onPersistMeta(flock);\n }\n : undefined,\n });\n\n const session: MetaSession = {\n stream,\n flock,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.metaSession = session;\n return session;\n }\n\n private async ensureDocSession(\n docId: string,\n doc: LoroDoc,\n joinAuth?: Uint8Array,\n ): Promise<DocSession> {\n const existing = this.docSessions.get(docId);\n if (existing && existing.doc === doc) {\n debug(\"reusing doc session\", { docId });\n return existing;\n }\n\n // Tear down previous session if doc instance changed\n if (existing) {\n debug(\"tearing down previous doc session (doc mismatch)\", { docId });\n await this.teardownDocSession(docId, existing);\n\n // Delete stale cursor so the new session bootstraps from scratch.\n // Without this, the cursor would tell StreamsCrdt to resume from a later\n // offset while the new doc is empty, creating a data hole.\n const streamId = this.options.docStreamId?.(docId) ?? docId;\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n await this.remoteCursorStore.delete?.(streamUrl);\n }\n\n const streamId = this.options.docStreamId?.(docId) ?? docId;\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n debug(\"creating doc StreamsCrdt\", { docId, streamUrl });\n\n const adapter = createLoroDocAdapter(doc);\n const { onPersistDoc } = this.options;\n const stream = new StreamsCrdt({\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n shardUrls: this.options.shardUrls,\n beforeRemoteCursorSave: onPersistDoc\n ? async () => {\n await onPersistDoc(docId, doc);\n }\n : undefined,\n });\n\n const session: DocSession = {\n stream,\n doc,\n docId,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.docSessions.set(docId, session);\n return session;\n }\n\n private async ensureFlockDocSession(\n flockDocId: string,\n flock: Flock,\n joinAuth?: Uint8Array,\n ): Promise<FlockDocSession> {\n const existing = this.flockDocSessions.get(flockDocId);\n if (existing && existing.flock === flock) {\n debug(\"reusing flock doc session\", { flockDocId });\n return existing;\n }\n\n if (existing) {\n debug(\"tearing down previous flock doc session (flock mismatch)\", {\n flockDocId,\n });\n await this.teardownFlockDocSession(flockDocId, existing);\n await this.remoteCursorStore.delete?.(\n this.getFlockDocStreamUrl(flockDocId),\n );\n }\n\n const streamUrl = this.getFlockDocStreamUrl(flockDocId);\n debug(\"creating flock doc StreamsCrdt\", { flockDocId, streamUrl });\n\n const adapter = createFlockAdapter(patchFlockExportJson(flock));\n const { onPersistFlockDoc } = this.options;\n const streamOptions = {\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n streamTtlSeconds: this.resolveFlockDocStreamTtlSeconds(flockDocId),\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n shardUrls: this.options.shardUrls,\n beforeRemoteCursorSave: onPersistFlockDoc\n ? async () => {\n await onPersistFlockDoc(flockDocId, flock);\n }\n : undefined,\n };\n const stream = new StreamsCrdt(streamOptions);\n\n const session: FlockDocSession = {\n stream,\n flock,\n flockDocId,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.flockDocSessions.set(flockDocId, session);\n return session;\n }\n\n private getFlockDocStreamUrl(flockDocId: string): string {\n const streamId = this.options.flockDocStreamId?.(flockDocId) ??\n `flock:${flockDocId}`;\n return createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n }\n\n private resolveFlockDocStreamTtlSeconds(\n flockDocId: string,\n ): number | undefined {\n const configured = this.options.flockDocStreamTtlMs;\n const ttlMs =\n typeof configured === \"function\"\n ? configured(flockDocId)\n : configured;\n if (\n typeof ttlMs !== \"number\" ||\n !Number.isFinite(ttlMs) ||\n ttlMs < 0\n ) {\n return undefined;\n }\n return ttlMs === 0 ? 0 : Math.ceil(ttlMs / 1_000);\n }\n\n // -------------------------------------------------------------------------\n // Internal: connection status\n // -------------------------------------------------------------------------\n\n private setConnectionStatus(status: TransportConnectionStatus): void {\n if (this.connectionStatus === status) return;\n this.connectionStatus = status;\n for (const listener of Array.from(this.connectionStatusListeners)) {\n try {\n listener(status);\n } catch (error) {\n debug(\"connection status listener error\", error);\n }\n }\n }\n}\n\nexport type { TransportJoinParams, TransportSubscription, TransportSyncResult };\n"],"mappings":";;;;;;;;;;AA6BA,MAAM,QAAQA,gCAAkB,oBAAoB;;;;;;;;;;;;;;;;;AAkBpD,SAAS,qBAAqB,OAAqB;CACjD,MAAM,OAAO,MAAM,WAAW,KAAK,MAAM;AACzC,CAAC,MAAc,cACb,KACA,0BACG;AACH,MAAI,OAAO,OAAO,QAAQ,YAAY,UAAU,KAAK;GACnD,MAAM,OAAO,IAAI;AACjB,OACE,QAAQ,QACR,OAAO,SAAS,YAChB,OAAO,KAAK,KAAe,CAAC,WAAW,GACvC;IAEA,MAAM,EAAE,MAAM,MAAO,GAAG,SAAS;AACjC,QAAI,OAAO,KAAK,KAAK,CAAC,WAAW,EAC/B,QAAO,MAAM;AAEf,WAAO,KAAK,MAAa,sBAAuB;;;AAGpD,SAAO,QAAQ,SACX,MAAM,GACN,KAAK,KAAY,sBAAuB;;AAE9C,QAAO;;AA4GT,SAAS,oBACP,UAA+B,cAChB;AACf,QAAO;EAAE,QAAQ;EAAS,2BAAW,IAAI,KAAK;EAAE;;AAGlD,SAAS,WAAW,SAAwB,QAAmC;AAC7E,SAAQ,SAAS;AACjB,MAAK,MAAM,MAAM,MAAM,KAAK,QAAQ,UAAU,CAC5C,KAAI;AACF,KAAG,OAAO;UACH,OAAO;AACd,QAAM,yBAAyB,MAAM;;;AAK3C,SAAS,gBACP,SACA,UACY;AACZ,SAAQ,UAAU,IAAI,SAAS;AAC/B,KAAI;AACF,WAAS,QAAQ,OAAO;UACjB,OAAO;AACd,QAAM,yBAAyB,MAAM;;A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,oBAAoB,QAAyC;AACnE,MAAI,KAAK,qBAAqB,OAAQ;AACtC,OAAK,mBAAmB;AACxB,OAAK,MAAM,YAAY,MAAM,KAAK,KAAK,0BAA0B,CAC/D,KAAI;AACF,YAAS,OAAO;WACT,OAAO;AACd,SAAM,oCAAoC,MAAM"}
|
|
@@ -2,7 +2,7 @@ import { D as TransportJoinParams, E as TransportConnectionStatus, T as Transpor
|
|
|
2
2
|
import { Flock } from "@loro-dev/flock-wasm";
|
|
3
3
|
import * as loro_crdt0 from "loro-crdt";
|
|
4
4
|
import { LoroDoc } from "loro-crdt";
|
|
5
|
-
import { RemoteCursorStore, SnapshotCodec, SnapshotUploadOptions, StreamsAuthProvider } from "@loro-dev/streams-crdt";
|
|
5
|
+
import { RemoteCursorStore, SnapshotCodec, SnapshotUploadOptions, StreamsAuthProvider, StreamsCrdtShardUrlsOptions } from "@loro-dev/streams-crdt";
|
|
6
6
|
|
|
7
7
|
//#region src/transport/streams.d.ts
|
|
8
8
|
interface StreamsTransportOptions {
|
|
@@ -53,6 +53,8 @@ interface StreamsTransportOptions {
|
|
|
53
53
|
}>;
|
|
54
54
|
/** Optional base URL for `createStreamUrl`. */
|
|
55
55
|
readonly baseUrl?: string;
|
|
56
|
+
/** Optional request shard origin pools forwarded to `StreamsCrdt`. */
|
|
57
|
+
readonly shardUrls?: StreamsCrdtShardUrlsOptions;
|
|
56
58
|
}
|
|
57
59
|
/**
|
|
58
60
|
* {@link TransportAdapter} implementation backed by `@loro-dev/streams-crdt`.
|
|
@@ -2,7 +2,7 @@ import { D as TransportJoinParams, E as TransportConnectionStatus, T as Transpor
|
|
|
2
2
|
import { Flock } from "@loro-dev/flock-wasm";
|
|
3
3
|
import * as loro_crdt0 from "loro-crdt";
|
|
4
4
|
import { LoroDoc } from "loro-crdt";
|
|
5
|
-
import { RemoteCursorStore, SnapshotCodec, SnapshotUploadOptions, StreamsAuthProvider } from "@loro-dev/streams-crdt";
|
|
5
|
+
import { RemoteCursorStore, SnapshotCodec, SnapshotUploadOptions, StreamsAuthProvider, StreamsCrdtShardUrlsOptions } from "@loro-dev/streams-crdt";
|
|
6
6
|
|
|
7
7
|
//#region src/transport/streams.d.ts
|
|
8
8
|
interface StreamsTransportOptions {
|
|
@@ -53,6 +53,8 @@ interface StreamsTransportOptions {
|
|
|
53
53
|
}>;
|
|
54
54
|
/** Optional base URL for `createStreamUrl`. */
|
|
55
55
|
readonly baseUrl?: string;
|
|
56
|
+
/** Optional request shard origin pools forwarded to `StreamsCrdt`. */
|
|
57
|
+
readonly shardUrls?: StreamsCrdtShardUrlsOptions;
|
|
56
58
|
}
|
|
57
59
|
/**
|
|
58
60
|
* {@link TransportAdapter} implementation backed by `@loro-dev/streams-crdt`.
|
|
@@ -649,6 +649,7 @@ var StreamsTransportAdapter = class {
|
|
|
649
649
|
snapshotCodec: this.options.snapshotCodec,
|
|
650
650
|
snapshotUpload: this.options.snapshotUpload,
|
|
651
651
|
reconnectConfig: this.options.reconnectConfig,
|
|
652
|
+
shardUrls: this.options.shardUrls,
|
|
652
653
|
beforeRemoteCursorSave: onPersistMeta ? async () => {
|
|
653
654
|
await onPersistMeta(flock);
|
|
654
655
|
} : void 0
|
|
@@ -700,6 +701,7 @@ var StreamsTransportAdapter = class {
|
|
|
700
701
|
snapshotCodec: this.options.snapshotCodec,
|
|
701
702
|
snapshotUpload: this.options.snapshotUpload,
|
|
702
703
|
reconnectConfig: this.options.reconnectConfig,
|
|
704
|
+
shardUrls: this.options.shardUrls,
|
|
703
705
|
beforeRemoteCursorSave: onPersistDoc ? async () => {
|
|
704
706
|
await onPersistDoc(docId, doc);
|
|
705
707
|
} : void 0
|
|
@@ -742,6 +744,7 @@ var StreamsTransportAdapter = class {
|
|
|
742
744
|
snapshotCodec: this.options.snapshotCodec,
|
|
743
745
|
snapshotUpload: this.options.snapshotUpload,
|
|
744
746
|
reconnectConfig: this.options.reconnectConfig,
|
|
747
|
+
shardUrls: this.options.shardUrls,
|
|
745
748
|
beforeRemoteCursorSave: onPersistFlockDoc ? async () => {
|
|
746
749
|
await onPersistFlockDoc(flockDocId, flock);
|
|
747
750
|
} : void 0
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streams.js","names":["rejoinAttempts: Promise<unknown>[]","detachStatusBridge: (() => void) | undefined","joinPromise!: Promise<StreamsTransportSubscription>","streamUrl","session: MetaSession","streamId","session: DocSession","session: FlockDocSession"],"sources":["../../src/transport/streams.ts"],"sourcesContent":["import { LoroDoc } from \"loro-crdt\";\nimport type { Flock } from \"@loro-dev/flock-wasm\";\nimport {\n StreamsCrdt,\n InMemoryRemoteCursorStore,\n createStreamUrl,\n type RemoteCursorStore,\n type SnapshotUploadOptions,\n type SnapshotCodec,\n type StreamsAuthProvider,\n type TransportSubscription as StreamsTransportSubscription,\n type TransportRoomStatus as StreamsRoomStatus,\n type TransportError as StreamsTransportError,\n type JsonObject as StreamsJsonObject,\n} from \"@loro-dev/streams-crdt\";\nimport { createLoroDocAdapter } from \"@loro-dev/streams-crdt/loro\";\nimport { createFlockAdapter } from \"@loro-dev/streams-crdt/flock\";\nimport { createDebugLogger } from \"../internal/debug\";\n\nimport type {\n TransportAdapter,\n TransportJoinParams,\n TransportSubscription,\n TransportSyncResult,\n TransportRoomStatus,\n TransportConnectionStatus,\n} from \"../types\";\n\nconst debug = createDebugLogger(\"transport:streams\");\n\n/**\n * Patches `flock.exportJson` so that an empty `from` version-vector (`{}`)\n * is treated as \"export everything\" (i.e. no `from` constraint).\n *\n * **Root cause:** `encodeVersionVectorForFfi({})` in flock-wasm produces an\n * empty object instead of `undefined`. The WASM layer then treats that as\n * \"everything is up-to-date\" and returns `{}` (no entries).\n *\n * The fix removes the `from` key from the options object entirely so that\n * `exportJson` falls through to a full-export code path. We cannot simply\n * set `from: undefined` because `isExportOptions` checks for the *presence*\n * of the key, causing `exportJsonWithHooks` (async) to be called in a sync\n * context.\n *\n * This can be removed once flock-wasm normalises empty version-vectors.\n */\nfunction patchFlockExportJson(flock: Flock): Flock {\n const orig = flock.exportJson.bind(flock);\n (flock as any).exportJson = (\n arg?: Record<string, unknown>,\n pruneTombstonesBefore?: number,\n ) => {\n if (arg && typeof arg === \"object\" && \"from\" in arg) {\n const from = arg.from;\n if (\n from != null &&\n typeof from === \"object\" &&\n Object.keys(from as object).length === 0\n ) {\n // Strip the `from` key so the call degrades to a full export.\n const { from: _from, ...rest } = arg;\n if (Object.keys(rest).length === 0) {\n return orig();\n }\n return orig(rest as any, pruneTombstonesBefore!);\n }\n }\n return arg === undefined\n ? orig()\n : orig(arg as any, pruneTombstonesBefore!);\n };\n return flock;\n}\n\nexport interface StreamsTransportOptions {\n /** Durable Streams bucket identifier. */\n readonly bucketId: string;\n /** Stream ID for metadata. Defaults to `\"repo-meta\"`. */\n readonly metaStreamId?: string;\n /** Maps a docId to a stream ID. Defaults to the docId itself. */\n readonly docStreamId?: (docId: string) => string;\n /** Maps a Flock doc id to a stream ID. Defaults to `flock:${flockDocId}`. */\n readonly flockDocStreamId?: (flockDocId: string) => string;\n /** Auth provider passed to each `StreamsCrdt` instance. */\n readonly auth: StreamsAuthProvider;\n /** Cursor store for checkpoint persistence. Defaults to `InMemoryRemoteCursorStore`. */\n readonly remoteCursorStore?: RemoteCursorStore;\n /** Auto-create streams on first join/sync. Defaults to `true`. */\n readonly createStreamIfMissing?: boolean;\n /**\n * Called inside `beforeRemoteCursorSave` for document streams.\n * Use this to persist the LoroDoc state via your StorageAdapter before the cursor advances.\n */\n readonly onPersistDoc?: (docId: string, doc: LoroDoc) => Promise<void>;\n /**\n * Called inside `beforeRemoteCursorSave` for Flock document streams.\n */\n readonly onPersistFlockDoc?: (flockDocId: string, flock: Flock) => Promise<void>;\n /**\n * Called inside `beforeRemoteCursorSave` for the metadata stream.\n * Use this to persist the Flock state via your StorageAdapter before the cursor advances.\n */\n readonly onPersistMeta?: (flock: Flock) => Promise<void>;\n /** Optional snapshot upload configuration forwarded to `StreamsCrdt`. */\n readonly snapshotUpload?: SnapshotUploadOptions;\n /** Optional snapshot codec configuration forwarded to `StreamsCrdt`. */\n readonly snapshotCodec?: SnapshotCodec;\n /**\n * Retention duration passed to streams-crdt when a Flock document stream is\n * created. Return `undefined` for persistent streams.\n */\n readonly flockDocStreamTtlMs?:\n | number\n | ((flockDocId: string) => number | undefined);\n /** Optional reconnect configuration forwarded to `StreamsCrdt`. */\n readonly reconnectConfig?: Partial<{\n readonly delays: readonly number[];\n readonly jitterFraction: number;\n readonly maxAttempts: number;\n readonly connectTimeoutMs: number;\n readonly pollTimeoutMs: number;\n }>;\n /** Optional base URL for `createStreamUrl`. */\n readonly baseUrl?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Internal session types\n// ---------------------------------------------------------------------------\n\ntype StreamsSessionBase = {\n stream: StreamsCrdt<StreamsJsonObject>;\n subscription?: StreamsTransportSubscription;\n joinPromise?: Promise<StreamsTransportSubscription>;\n lastJoinError?: Error;\n closed: boolean;\n refCount: number;\n statusEmitter: StatusEmitter;\n};\n\ntype MetaSession = StreamsSessionBase & {\n flock: Flock;\n};\n\ntype DocSession = StreamsSessionBase & {\n doc: LoroDoc;\n docId: string;\n};\n\ntype FlockDocSession = StreamsSessionBase & {\n flock: Flock;\n flockDocId: string;\n};\n\ntype CreateRoomSubscriptionOptions<S extends StreamsSessionBase> = {\n readonly rawSessionPromise: Promise<S>;\n readonly initialStatus: TransportRoomStatus;\n readonly retain: (session: S) => void;\n readonly release: (session: S) => void;\n readonly teardownUnretained: (session: S) => void;\n readonly waitForFirstSync: (session: S) => Promise<void>;\n readonly getActiveSubscription: (\n session: S,\n ) => Promise<StreamsTransportSubscription>;\n readonly rejoin: (session: S) => Promise<void>;\n};\n\ntype JoinSessionOptions<S extends StreamsSessionBase> = {\n readonly isCurrent: (session: S) => boolean;\n readonly createJoinError: (error?: StreamsTransportError) => Error;\n};\n\ntype StatusEmitter = {\n status: TransportRoomStatus;\n listeners: Set<(status: TransportRoomStatus) => void>;\n};\n\nfunction createStatusEmitter(\n initial: TransportRoomStatus = \"connecting\",\n): StatusEmitter {\n return { status: initial, listeners: new Set() };\n}\n\nfunction emitStatus(emitter: StatusEmitter, status: TransportRoomStatus): void {\n emitter.status = status;\n for (const cb of Array.from(emitter.listeners)) {\n try {\n cb(status);\n } catch (error) {\n debug(\"status listener error\", error);\n }\n }\n}\n\nfunction subscribeStatus(\n emitter: StatusEmitter,\n listener: (status: TransportRoomStatus) => void,\n): () => void {\n emitter.listeners.add(listener);\n try {\n listener(emitter.status);\n } catch (error) {\n debug(\"status listener error\", error);\n }\n return () => {\n emitter.listeners.delete(listener);\n };\n}\n\nfunction createSubscriptionClosedError(): Error {\n return new Error(\"subscription closed\");\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction createMetaJoinError(error?: StreamsTransportError): Error {\n return new Error(`Failed to join meta room: ${error?.code ?? \"unknown\"}`);\n}\n\nfunction createDocJoinError(\n docId: string,\n error?: StreamsTransportError,\n): Error {\n return new Error(\n `Failed to join doc room ${docId}: ${error?.code ?? \"unknown\"}`,\n );\n}\n\nfunction createFlockDocJoinError(\n flockDocId: string,\n error?: StreamsTransportError,\n): Error {\n return new Error(\n `Failed to join Flock doc room ${flockDocId}: ${error?.code ?? \"unknown\"}`,\n );\n}\n\nfunction mapStreamsStatus(\n status: StreamsRoomStatus | \"connecting\",\n): TransportRoomStatus {\n switch (status) {\n case \"joined\":\n return \"joined\";\n case \"reconnecting\":\n return \"reconnecting\";\n case \"error\":\n return \"error\";\n case \"connecting\":\n return \"connecting\";\n case \"disconnected\":\n default:\n return \"disconnected\";\n }\n}\n\nfunction mapConnectionStatus(\n status: TransportRoomStatus,\n): TransportConnectionStatus {\n switch (status) {\n case \"connecting\":\n return \"connecting\";\n case \"disconnected\":\n return \"disconnected\";\n case \"joined\":\n return \"connected\";\n case \"error\":\n return \"disconnected\";\n case \"reconnecting\":\n return \"connecting\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// StreamsTransportAdapter\n// ---------------------------------------------------------------------------\n\n/**\n * {@link TransportAdapter} implementation backed by `@loro-dev/streams-crdt`.\n *\n * Uses Durable Streams (HTTP long-poll) for syncing metadata and documents.\n * Ephemeral rooms are not supported.\n */\nexport class StreamsTransportAdapter implements TransportAdapter {\n private readonly options: StreamsTransportOptions;\n private readonly remoteCursorStore: RemoteCursorStore;\n private metaSession?: MetaSession;\n private readonly docSessions = new Map<string, DocSession>();\n private readonly flockDocSessions = new Map<string, FlockDocSession>();\n private connectionStatus: TransportConnectionStatus = \"disconnected\";\n private readonly connectionStatusListeners = new Set<\n (status: TransportConnectionStatus) => void\n >();\n\n constructor(options: StreamsTransportOptions) {\n this.options = options;\n this.remoteCursorStore =\n options.remoteCursorStore ?? new InMemoryRemoteCursorStore();\n }\n\n // -------------------------------------------------------------------------\n // Connection lifecycle\n // -------------------------------------------------------------------------\n\n async connect(): Promise<void> {\n debug(\"connect requested\");\n this.setConnectionStatus(\"connected\");\n }\n\n async close(): Promise<void> {\n debug(\"close requested\");\n\n // Close all doc streams\n for (const [docId, session] of this.docSessions) {\n debug(\"closing doc session\", { docId });\n await this.teardownDocSession(docId, session);\n }\n this.docSessions.clear();\n\n for (const [flockDocId, session] of this.flockDocSessions) {\n debug(\"closing flock doc session\", { flockDocId });\n await this.teardownFlockDocSession(flockDocId, session);\n }\n this.flockDocSessions.clear();\n\n // Close meta stream\n if (this.metaSession) {\n debug(\"closing meta session\");\n await this.teardownMetaSession(this.metaSession);\n this.metaSession = undefined;\n }\n\n this.setConnectionStatus(\"disconnected\");\n debug(\"close completed\");\n }\n\n isConnected(): boolean {\n return this.connectionStatus === \"connected\";\n }\n\n getStatus(): TransportConnectionStatus {\n return this.connectionStatus;\n }\n\n onStatusChange(\n listener: (status: TransportConnectionStatus) => void,\n ): () => void {\n this.connectionStatusListeners.add(listener);\n return () => {\n this.connectionStatusListeners.delete(listener);\n };\n }\n\n getLatency(): number | undefined {\n return undefined;\n }\n\n onLatency(_listener: (latencyMs: number) => void): () => void {\n return () => {};\n }\n\n async reconnect(): Promise<void> {\n debug(\"reconnect requested\");\n this.setConnectionStatus(\"connected\");\n const rejoinAttempts: Promise<unknown>[] = [];\n\n // Re-join disconnected meta session\n if (this.metaSession && !this.metaSession.closed) {\n if (this.metaSession.subscription) {\n const status = this.metaSession.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin meta session\", { status });\n this.metaSession.stream.rejoin();\n }\n } else if (this.metaSession.refCount > 0) {\n debug(\"retry incomplete meta session\");\n rejoinAttempts.push(this.joinMetaSession(this.metaSession));\n }\n }\n\n // Re-join disconnected doc sessions\n for (const [docId, session] of this.docSessions) {\n if (session.closed) continue;\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin doc session\", { docId, status });\n session.stream.rejoin();\n }\n } else if (session.refCount > 0) {\n debug(\"retry incomplete doc session\", { docId });\n rejoinAttempts.push(this.joinDocSession(session));\n }\n }\n\n for (const [flockDocId, session] of this.flockDocSessions) {\n if (session.closed) continue;\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin flock doc session\", { flockDocId, status });\n session.stream.rejoin();\n }\n } else if (session.refCount > 0) {\n debug(\"retry incomplete flock doc session\", { flockDocId });\n rejoinAttempts.push(this.joinFlockDocSession(session));\n }\n }\n\n await Promise.all(rejoinAttempts);\n }\n\n // -------------------------------------------------------------------------\n // Metadata sync / join\n // -------------------------------------------------------------------------\n\n async syncMeta(\n flock: Flock,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncMeta requested\");\n try {\n const session = await this.ensureMetaSession(flock);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncMeta failed\", result.error);\n return { ok: false };\n }\n debug(\"syncMeta completed\");\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncMeta error\", error);\n return { ok: false };\n }\n }\n\n joinMetaRoom(\n flock: Flock,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinMetaRoom requested\");\n\n const existing = this.metaSession;\n const rawSessionPromise = this.ensureMetaSession(flock, params?.auth);\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.flock === flock\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"meta session refCount incremented\", {\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseMetaSession(session),\n teardownUnretained: (session) => {\n if (session.refCount === 0 && this.metaSession === session) {\n void this.teardownMetaSession(session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForMetaFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveMetaSubscription(session),\n rejoin: (session) => this.rejoinMetaSession(session),\n });\n }\n\n // -------------------------------------------------------------------------\n // Document sync / join\n // -------------------------------------------------------------------------\n\n async syncDoc(\n docId: string,\n doc: LoroDoc,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncDoc requested\", { docId });\n try {\n const session = await this.ensureDocSession(docId, doc);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncDoc failed\", { docId, error: result.error });\n return { ok: false };\n }\n debug(\"syncDoc completed\", { docId });\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncDoc error\", { docId, error });\n return { ok: false };\n }\n }\n\n joinDocRoom(\n docId: string,\n doc: LoroDoc,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinDocRoom requested\", { docId });\n\n const existing = this.docSessions.get(docId);\n const rawSessionPromise = this.ensureDocSession(docId, doc, params?.auth);\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.doc === doc\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"doc session refCount incremented\", {\n docId,\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseDocSession(docId, session),\n teardownUnretained: (session) => {\n if (\n session.refCount === 0 &&\n this.docSessions.get(docId) === session\n ) {\n void this.teardownDocSession(docId, session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForDocFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveDocSubscription(session),\n rejoin: (session) => this.rejoinDocSession(session),\n });\n }\n\n async syncFlockDoc(\n flockDocId: string,\n flock: Flock,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncFlockDoc requested\", { flockDocId });\n try {\n const session = await this.ensureFlockDocSession(flockDocId, flock);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncFlockDoc failed\", { flockDocId, error: result.error });\n return { ok: false };\n }\n debug(\"syncFlockDoc completed\", { flockDocId });\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncFlockDoc error\", { flockDocId, error });\n return { ok: false };\n }\n }\n\n joinFlockDocRoom(\n flockDocId: string,\n flock: Flock,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinFlockDocRoom requested\", { flockDocId });\n\n const existing = this.flockDocSessions.get(flockDocId);\n const rawSessionPromise = this.ensureFlockDocSession(\n flockDocId,\n flock,\n params?.auth,\n );\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.flock === flock\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"flock doc session refCount incremented\", {\n flockDocId,\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseFlockDocSession(flockDocId, session),\n teardownUnretained: (session) => {\n if (\n session.refCount === 0 &&\n this.flockDocSessions.get(flockDocId) === session\n ) {\n void this.teardownFlockDocSession(flockDocId, session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForFlockDocFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveFlockDocSubscription(session),\n rejoin: (session) => this.rejoinFlockDocSession(session),\n });\n }\n\n async forgetFlockDoc(flockDocId: string): Promise<void> {\n debug(\"forgetFlockDoc requested\", { flockDocId });\n const session = this.flockDocSessions.get(flockDocId);\n if (session) {\n await this.teardownFlockDocSession(flockDocId, session);\n }\n await this.remoteCursorStore.delete?.(\n this.getFlockDocStreamUrl(flockDocId),\n );\n }\n\n // -------------------------------------------------------------------------\n // Ephemeral (not supported)\n // -------------------------------------------------------------------------\n\n joinEphemeralRoom(\n _roomId: string,\n ): TransportSubscription & { store: import(\"loro-crdt\").EphemeralStore } {\n throw new Error(\"StreamsTransportAdapter does not support ephemeral rooms\");\n }\n\n private createRoomSubscription<S extends StreamsSessionBase>({\n rawSessionPromise,\n initialStatus,\n retain,\n release,\n teardownUnretained,\n waitForFirstSync,\n getActiveSubscription,\n rejoin,\n }: CreateRoomSubscriptionOptions<S>): TransportSubscription {\n const statusProxy = createStatusEmitter(initialStatus);\n let unsubscribed = false;\n let retained = false;\n let detachStatusBridge: (() => void) | undefined;\n\n const sessionPromise = rawSessionPromise\n .then((session) => {\n const forwardStatus = (status: TransportRoomStatus) => {\n emitStatus(statusProxy, status);\n };\n session.statusEmitter.listeners.add(forwardStatus);\n detachStatusBridge = () => {\n session.statusEmitter.listeners.delete(forwardStatus);\n };\n emitStatus(statusProxy, session.statusEmitter.status);\n\n if (unsubscribed || session.closed) {\n detachStatusBridge();\n detachStatusBridge = undefined;\n throw createSubscriptionClosedError();\n }\n\n retain(session);\n retained = true;\n return session;\n })\n .catch((error) => {\n emitStatus(statusProxy, \"error\");\n throw error;\n });\n\n const requireActiveSession = async (): Promise<S> => {\n const session = await sessionPromise;\n if (unsubscribed || session.closed || !retained) {\n throw createSubscriptionClosedError();\n }\n return session;\n };\n\n void sessionPromise\n .then((session) => waitForFirstSync(session))\n .catch(() => {});\n\n return {\n unsubscribe: () => {\n if (unsubscribed) return;\n unsubscribed = true;\n detachStatusBridge?.();\n detachStatusBridge = undefined;\n void rawSessionPromise\n .then((session) => {\n if (retained) {\n release(session);\n } else {\n teardownUnretained(session);\n }\n })\n .catch(() => {});\n },\n get firstSyncedWithRemote() {\n return requireActiveSession().then((session) =>\n waitForFirstSync(session),\n );\n },\n waitUntilSynced: async () => {\n const session = await requireActiveSession();\n const activeSubscription = await getActiveSubscription(session);\n await activeSubscription.waitUntilSynced();\n },\n rejoin: async () => {\n const session = await requireActiveSession();\n await rejoin(session);\n },\n get status(): TransportRoomStatus {\n return statusProxy.status;\n },\n onStatusChange: (listener) => subscribeStatus(statusProxy, listener),\n };\n }\n\n // -------------------------------------------------------------------------\n // Internal: session management\n // -------------------------------------------------------------------------\n\n private resolveAuth(joinAuth?: Uint8Array): StreamsAuthProvider {\n if (joinAuth && joinAuth.length > 0) {\n const token = new TextDecoder().decode(joinAuth);\n return () => token;\n }\n return this.options.auth;\n }\n\n private joinMetaSession(\n session: MetaSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) => this.metaSession === candidate,\n createJoinError: createMetaJoinError,\n });\n }\n\n private joinDocSession(\n session: DocSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) =>\n this.docSessions.get(candidate.docId) === candidate,\n createJoinError: (error) => createDocJoinError(session.docId, error),\n });\n }\n\n private joinFlockDocSession(\n session: FlockDocSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) =>\n this.flockDocSessions.get(candidate.flockDocId) === candidate,\n createJoinError: (error) =>\n createFlockDocJoinError(session.flockDocId, error),\n });\n }\n\n private joinSession<S extends StreamsSessionBase>(\n session: S,\n options: JoinSessionOptions<S>,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n\n let joinPromise!: Promise<StreamsTransportSubscription>;\n joinPromise = (async () => {\n await Promise.resolve();\n try {\n if (session.closed || !options.isCurrent(session)) {\n throw createSubscriptionClosedError();\n }\n\n // Signal transport-level connectivity before the join/sync begins,\n // so consumers can observe a meaningful syncing state while the\n // initial bootstrap is in progress.\n emitStatus(session.statusEmitter, \"connecting\");\n this.setConnectionStatus(\"connected\");\n\n const joinParams = {\n onStatusChange: (status: StreamsRoomStatus | \"connecting\") => {\n const s = mapStreamsStatus(status);\n emitStatus(session.statusEmitter, s);\n this.setConnectionStatus(mapConnectionStatus(s));\n },\n };\n const joinResult = await session.stream.join(joinParams);\n if (!joinResult.ok) {\n if (joinResult.error.retryable) {\n const retainedJoin = await session.stream.join(joinParams);\n if (retainedJoin.ok) {\n return this.retainJoinedSubscription(\n session,\n retainedJoin.value,\n options,\n );\n }\n }\n throw options.createJoinError(joinResult.error);\n }\n\n return this.retainJoinedSubscription(\n session,\n joinResult.value,\n options,\n );\n } catch (error) {\n const normalized = toError(error);\n session.subscription = undefined;\n session.lastJoinError = normalized;\n emitStatus(session.statusEmitter, \"error\");\n this.setConnectionStatus(\"disconnected\");\n throw normalized;\n } finally {\n if (session.joinPromise === joinPromise) {\n session.joinPromise = undefined;\n }\n }\n })();\n session.joinPromise = joinPromise;\n return joinPromise;\n }\n\n private retainJoinedSubscription<S extends StreamsSessionBase>(\n session: S,\n subscription: StreamsTransportSubscription,\n options: JoinSessionOptions<S>,\n ): StreamsTransportSubscription {\n if (session.closed || !options.isCurrent(session)) {\n subscription.unsubscribe();\n throw createSubscriptionClosedError();\n }\n\n session.subscription = subscription;\n session.lastJoinError = undefined;\n const status = mapStreamsStatus(subscription.status);\n emitStatus(session.statusEmitter, status);\n this.setConnectionStatus(mapConnectionStatus(status));\n return subscription;\n }\n\n private getActiveMetaSubscription(\n session: MetaSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ?? new Error(\"meta room is not joined\"),\n );\n }\n\n private async waitForMetaFirstSync(session: MetaSession): Promise<void> {\n const subscription = await this.joinMetaSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createMetaJoinError(subscription.lastError);\n }\n throw error;\n }\n }\n\n private getActiveDocSubscription(\n session: DocSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ?? new Error(`doc room ${session.docId} is not joined`),\n );\n }\n\n private async waitForDocFirstSync(session: DocSession): Promise<void> {\n const subscription = await this.joinDocSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createDocJoinError(session.docId, subscription.lastError);\n }\n throw error;\n }\n }\n\n private getActiveFlockDocSubscription(\n session: FlockDocSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ??\n new Error(`flock doc room ${session.flockDocId} is not joined`),\n );\n }\n\n private async waitForFlockDocFirstSync(\n session: FlockDocSession,\n ): Promise<void> {\n const subscription = await this.joinFlockDocSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createFlockDocJoinError(session.flockDocId, subscription.lastError);\n }\n throw error;\n }\n }\n\n private async rejoinMetaSession(session: MetaSession): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin meta session\", { status });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinMetaSession(session);\n }\n\n private async rejoinDocSession(session: DocSession): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin doc session\", { docId: session.docId, status });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinDocSession(session);\n }\n\n private async rejoinFlockDocSession(\n session: FlockDocSession,\n ): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin flock doc session\", {\n flockDocId: session.flockDocId,\n status,\n });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinFlockDocSession(session);\n }\n\n private releaseMetaSession(session: MetaSession): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"meta session refCount decremented\", {\n refCount: session.refCount,\n });\n if (session.refCount === 0 && this.metaSession === session) {\n debug(\"tearing down meta session (refCount=0)\");\n void this.teardownMetaSession(session).catch(() => {});\n }\n }\n\n private releaseDocSession(docId: string, session: DocSession): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"doc session refCount decremented\", {\n docId,\n refCount: session.refCount,\n });\n if (session.refCount === 0 && this.docSessions.get(docId) === session) {\n debug(\"tearing down doc session (refCount=0)\", { docId });\n void this.teardownDocSession(docId, session).catch(() => {});\n }\n }\n\n private releaseFlockDocSession(\n flockDocId: string,\n session: FlockDocSession,\n ): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"flock doc session refCount decremented\", {\n flockDocId,\n refCount: session.refCount,\n });\n if (\n session.refCount === 0 &&\n this.flockDocSessions.get(flockDocId) === session\n ) {\n debug(\"tearing down flock doc session (refCount=0)\", { flockDocId });\n void this.teardownFlockDocSession(flockDocId, session).catch(() => {});\n }\n }\n\n private async teardownMetaSession(session: MetaSession): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.metaSession === session) {\n this.metaSession = undefined;\n }\n }\n\n private async teardownDocSession(\n docId: string,\n session: DocSession,\n ): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.docSessions.get(docId) === session) {\n this.docSessions.delete(docId);\n }\n }\n\n private async teardownFlockDocSession(\n flockDocId: string,\n session: FlockDocSession,\n ): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.flockDocSessions.get(flockDocId) === session) {\n this.flockDocSessions.delete(flockDocId);\n }\n }\n\n private async ensureMetaSession(\n flock: Flock,\n joinAuth?: Uint8Array,\n ): Promise<MetaSession> {\n if (this.metaSession && this.metaSession.flock === flock) {\n debug(\"reusing meta session\");\n return this.metaSession;\n }\n\n // Tear down previous session if flock instance changed\n if (this.metaSession) {\n debug(\"tearing down previous meta session (flock mismatch)\");\n await this.teardownMetaSession(this.metaSession);\n\n // Delete stale cursor so the new session bootstraps from scratch.\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId: this.options.metaStreamId ?? \"repo-meta\",\n baseUrl: this.options.baseUrl,\n });\n await this.remoteCursorStore.delete?.(streamUrl);\n }\n\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId: this.options.metaStreamId ?? \"repo-meta\",\n baseUrl: this.options.baseUrl,\n });\n debug(\"creating meta StreamsCrdt\", { streamUrl });\n\n const adapter = createFlockAdapter(patchFlockExportJson(flock));\n const { onPersistMeta } = this.options;\n const stream = new StreamsCrdt({\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n beforeRemoteCursorSave: onPersistMeta\n ? async () => {\n await onPersistMeta(flock);\n }\n : undefined,\n });\n\n const session: MetaSession = {\n stream,\n flock,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.metaSession = session;\n return session;\n }\n\n private async ensureDocSession(\n docId: string,\n doc: LoroDoc,\n joinAuth?: Uint8Array,\n ): Promise<DocSession> {\n const existing = this.docSessions.get(docId);\n if (existing && existing.doc === doc) {\n debug(\"reusing doc session\", { docId });\n return existing;\n }\n\n // Tear down previous session if doc instance changed\n if (existing) {\n debug(\"tearing down previous doc session (doc mismatch)\", { docId });\n await this.teardownDocSession(docId, existing);\n\n // Delete stale cursor so the new session bootstraps from scratch.\n // Without this, the cursor would tell StreamsCrdt to resume from a later\n // offset while the new doc is empty, creating a data hole.\n const streamId = this.options.docStreamId?.(docId) ?? docId;\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n await this.remoteCursorStore.delete?.(streamUrl);\n }\n\n const streamId = this.options.docStreamId?.(docId) ?? docId;\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n debug(\"creating doc StreamsCrdt\", { docId, streamUrl });\n\n const adapter = createLoroDocAdapter(doc);\n const { onPersistDoc } = this.options;\n const stream = new StreamsCrdt({\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n beforeRemoteCursorSave: onPersistDoc\n ? async () => {\n await onPersistDoc(docId, doc);\n }\n : undefined,\n });\n\n const session: DocSession = {\n stream,\n doc,\n docId,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.docSessions.set(docId, session);\n return session;\n }\n\n private async ensureFlockDocSession(\n flockDocId: string,\n flock: Flock,\n joinAuth?: Uint8Array,\n ): Promise<FlockDocSession> {\n const existing = this.flockDocSessions.get(flockDocId);\n if (existing && existing.flock === flock) {\n debug(\"reusing flock doc session\", { flockDocId });\n return existing;\n }\n\n if (existing) {\n debug(\"tearing down previous flock doc session (flock mismatch)\", {\n flockDocId,\n });\n await this.teardownFlockDocSession(flockDocId, existing);\n await this.remoteCursorStore.delete?.(\n this.getFlockDocStreamUrl(flockDocId),\n );\n }\n\n const streamUrl = this.getFlockDocStreamUrl(flockDocId);\n debug(\"creating flock doc StreamsCrdt\", { flockDocId, streamUrl });\n\n const adapter = createFlockAdapter(patchFlockExportJson(flock));\n const { onPersistFlockDoc } = this.options;\n const streamOptions = {\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n streamTtlSeconds: this.resolveFlockDocStreamTtlSeconds(flockDocId),\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n beforeRemoteCursorSave: onPersistFlockDoc\n ? async () => {\n await onPersistFlockDoc(flockDocId, flock);\n }\n : undefined,\n };\n const stream = new StreamsCrdt(streamOptions);\n\n const session: FlockDocSession = {\n stream,\n flock,\n flockDocId,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.flockDocSessions.set(flockDocId, session);\n return session;\n }\n\n private getFlockDocStreamUrl(flockDocId: string): string {\n const streamId = this.options.flockDocStreamId?.(flockDocId) ??\n `flock:${flockDocId}`;\n return createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n }\n\n private resolveFlockDocStreamTtlSeconds(\n flockDocId: string,\n ): number | undefined {\n const configured = this.options.flockDocStreamTtlMs;\n const ttlMs =\n typeof configured === \"function\"\n ? configured(flockDocId)\n : configured;\n if (\n typeof ttlMs !== \"number\" ||\n !Number.isFinite(ttlMs) ||\n ttlMs < 0\n ) {\n return undefined;\n }\n return ttlMs === 0 ? 0 : Math.ceil(ttlMs / 1_000);\n }\n\n // -------------------------------------------------------------------------\n // Internal: connection status\n // -------------------------------------------------------------------------\n\n private setConnectionStatus(status: TransportConnectionStatus): void {\n if (this.connectionStatus === status) return;\n this.connectionStatus = status;\n for (const listener of Array.from(this.connectionStatusListeners)) {\n try {\n listener(status);\n } catch (error) {\n debug(\"connection status listener error\", error);\n }\n }\n }\n}\n\nexport type { TransportJoinParams, TransportSubscription, TransportSyncResult };\n"],"mappings":";;;;;;AA4BA,MAAM,QAAQ,kBAAkB,oBAAoB;;;;;;;;;;;;;;;;;AAkBpD,SAAS,qBAAqB,OAAqB;CACjD,MAAM,OAAO,MAAM,WAAW,KAAK,MAAM;AACzC,CAAC,MAAc,cACb,KACA,0BACG;AACH,MAAI,OAAO,OAAO,QAAQ,YAAY,UAAU,KAAK;GACnD,MAAM,OAAO,IAAI;AACjB,OACE,QAAQ,QACR,OAAO,SAAS,YAChB,OAAO,KAAK,KAAe,CAAC,WAAW,GACvC;IAEA,MAAM,EAAE,MAAM,MAAO,GAAG,SAAS;AACjC,QAAI,OAAO,KAAK,KAAK,CAAC,WAAW,EAC/B,QAAO,MAAM;AAEf,WAAO,KAAK,MAAa,sBAAuB;;;AAGpD,SAAO,QAAQ,SACX,MAAM,GACN,KAAK,KAAY,sBAAuB;;AAE9C,QAAO;;AA0GT,SAAS,oBACP,UAA+B,cAChB;AACf,QAAO;EAAE,QAAQ;EAAS,2BAAW,IAAI,KAAK;EAAE;;AAGlD,SAAS,WAAW,SAAwB,QAAmC;AAC7E,SAAQ,SAAS;AACjB,MAAK,MAAM,MAAM,MAAM,KAAK,QAAQ,UAAU,CAC5C,KAAI;AACF,KAAG,OAAO;UACH,OAAO;AACd,QAAM,yBAAyB,MAAM;;;AAK3C,SAAS,gBACP,SACA,UACY;AACZ,SAAQ,UAAU,IAAI,SAAS;AAC/B,KAAI;AACF,WAAS,QAAQ,OAA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,AAAQ,oBAAoB,QAAyC;AACnE,MAAI,KAAK,qBAAqB,OAAQ;AACtC,OAAK,mBAAmB;AACxB,OAAK,MAAM,YAAY,MAAM,KAAK,KAAK,0BAA0B,CAC/D,KAAI;AACF,YAAS,OAAO;WACT,OAAO;AACd,SAAM,oCAAoC,MAAM"}
|
|
1
|
+
{"version":3,"file":"streams.js","names":["rejoinAttempts: Promise<unknown>[]","detachStatusBridge: (() => void) | undefined","joinPromise!: Promise<StreamsTransportSubscription>","streamUrl","session: MetaSession","streamId","session: DocSession","session: FlockDocSession"],"sources":["../../src/transport/streams.ts"],"sourcesContent":["import { LoroDoc } from \"loro-crdt\";\nimport type { Flock } from \"@loro-dev/flock-wasm\";\nimport {\n StreamsCrdt,\n InMemoryRemoteCursorStore,\n createStreamUrl,\n type RemoteCursorStore,\n type SnapshotUploadOptions,\n type SnapshotCodec,\n type StreamsCrdtShardUrlsOptions,\n type StreamsAuthProvider,\n type TransportSubscription as StreamsTransportSubscription,\n type TransportRoomStatus as StreamsRoomStatus,\n type TransportError as StreamsTransportError,\n type JsonObject as StreamsJsonObject,\n} from \"@loro-dev/streams-crdt\";\nimport { createLoroDocAdapter } from \"@loro-dev/streams-crdt/loro\";\nimport { createFlockAdapter } from \"@loro-dev/streams-crdt/flock\";\nimport { createDebugLogger } from \"../internal/debug\";\n\nimport type {\n TransportAdapter,\n TransportJoinParams,\n TransportSubscription,\n TransportSyncResult,\n TransportRoomStatus,\n TransportConnectionStatus,\n} from \"../types\";\n\nconst debug = createDebugLogger(\"transport:streams\");\n\n/**\n * Patches `flock.exportJson` so that an empty `from` version-vector (`{}`)\n * is treated as \"export everything\" (i.e. no `from` constraint).\n *\n * **Root cause:** `encodeVersionVectorForFfi({})` in flock-wasm produces an\n * empty object instead of `undefined`. The WASM layer then treats that as\n * \"everything is up-to-date\" and returns `{}` (no entries).\n *\n * The fix removes the `from` key from the options object entirely so that\n * `exportJson` falls through to a full-export code path. We cannot simply\n * set `from: undefined` because `isExportOptions` checks for the *presence*\n * of the key, causing `exportJsonWithHooks` (async) to be called in a sync\n * context.\n *\n * This can be removed once flock-wasm normalises empty version-vectors.\n */\nfunction patchFlockExportJson(flock: Flock): Flock {\n const orig = flock.exportJson.bind(flock);\n (flock as any).exportJson = (\n arg?: Record<string, unknown>,\n pruneTombstonesBefore?: number,\n ) => {\n if (arg && typeof arg === \"object\" && \"from\" in arg) {\n const from = arg.from;\n if (\n from != null &&\n typeof from === \"object\" &&\n Object.keys(from as object).length === 0\n ) {\n // Strip the `from` key so the call degrades to a full export.\n const { from: _from, ...rest } = arg;\n if (Object.keys(rest).length === 0) {\n return orig();\n }\n return orig(rest as any, pruneTombstonesBefore!);\n }\n }\n return arg === undefined\n ? orig()\n : orig(arg as any, pruneTombstonesBefore!);\n };\n return flock;\n}\n\nexport interface StreamsTransportOptions {\n /** Durable Streams bucket identifier. */\n readonly bucketId: string;\n /** Stream ID for metadata. Defaults to `\"repo-meta\"`. */\n readonly metaStreamId?: string;\n /** Maps a docId to a stream ID. Defaults to the docId itself. */\n readonly docStreamId?: (docId: string) => string;\n /** Maps a Flock doc id to a stream ID. Defaults to `flock:${flockDocId}`. */\n readonly flockDocStreamId?: (flockDocId: string) => string;\n /** Auth provider passed to each `StreamsCrdt` instance. */\n readonly auth: StreamsAuthProvider;\n /** Cursor store for checkpoint persistence. Defaults to `InMemoryRemoteCursorStore`. */\n readonly remoteCursorStore?: RemoteCursorStore;\n /** Auto-create streams on first join/sync. Defaults to `true`. */\n readonly createStreamIfMissing?: boolean;\n /**\n * Called inside `beforeRemoteCursorSave` for document streams.\n * Use this to persist the LoroDoc state via your StorageAdapter before the cursor advances.\n */\n readonly onPersistDoc?: (docId: string, doc: LoroDoc) => Promise<void>;\n /**\n * Called inside `beforeRemoteCursorSave` for Flock document streams.\n */\n readonly onPersistFlockDoc?: (flockDocId: string, flock: Flock) => Promise<void>;\n /**\n * Called inside `beforeRemoteCursorSave` for the metadata stream.\n * Use this to persist the Flock state via your StorageAdapter before the cursor advances.\n */\n readonly onPersistMeta?: (flock: Flock) => Promise<void>;\n /** Optional snapshot upload configuration forwarded to `StreamsCrdt`. */\n readonly snapshotUpload?: SnapshotUploadOptions;\n /** Optional snapshot codec configuration forwarded to `StreamsCrdt`. */\n readonly snapshotCodec?: SnapshotCodec;\n /**\n * Retention duration passed to streams-crdt when a Flock document stream is\n * created. Return `undefined` for persistent streams.\n */\n readonly flockDocStreamTtlMs?:\n | number\n | ((flockDocId: string) => number | undefined);\n /** Optional reconnect configuration forwarded to `StreamsCrdt`. */\n readonly reconnectConfig?: Partial<{\n readonly delays: readonly number[];\n readonly jitterFraction: number;\n readonly maxAttempts: number;\n readonly connectTimeoutMs: number;\n readonly pollTimeoutMs: number;\n }>;\n /** Optional base URL for `createStreamUrl`. */\n readonly baseUrl?: string;\n /** Optional request shard origin pools forwarded to `StreamsCrdt`. */\n readonly shardUrls?: StreamsCrdtShardUrlsOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Internal session types\n// ---------------------------------------------------------------------------\n\ntype StreamsSessionBase = {\n stream: StreamsCrdt<StreamsJsonObject>;\n subscription?: StreamsTransportSubscription;\n joinPromise?: Promise<StreamsTransportSubscription>;\n lastJoinError?: Error;\n closed: boolean;\n refCount: number;\n statusEmitter: StatusEmitter;\n};\n\ntype MetaSession = StreamsSessionBase & {\n flock: Flock;\n};\n\ntype DocSession = StreamsSessionBase & {\n doc: LoroDoc;\n docId: string;\n};\n\ntype FlockDocSession = StreamsSessionBase & {\n flock: Flock;\n flockDocId: string;\n};\n\ntype CreateRoomSubscriptionOptions<S extends StreamsSessionBase> = {\n readonly rawSessionPromise: Promise<S>;\n readonly initialStatus: TransportRoomStatus;\n readonly retain: (session: S) => void;\n readonly release: (session: S) => void;\n readonly teardownUnretained: (session: S) => void;\n readonly waitForFirstSync: (session: S) => Promise<void>;\n readonly getActiveSubscription: (\n session: S,\n ) => Promise<StreamsTransportSubscription>;\n readonly rejoin: (session: S) => Promise<void>;\n};\n\ntype JoinSessionOptions<S extends StreamsSessionBase> = {\n readonly isCurrent: (session: S) => boolean;\n readonly createJoinError: (error?: StreamsTransportError) => Error;\n};\n\ntype StatusEmitter = {\n status: TransportRoomStatus;\n listeners: Set<(status: TransportRoomStatus) => void>;\n};\n\nfunction createStatusEmitter(\n initial: TransportRoomStatus = \"connecting\",\n): StatusEmitter {\n return { status: initial, listeners: new Set() };\n}\n\nfunction emitStatus(emitter: StatusEmitter, status: TransportRoomStatus): void {\n emitter.status = status;\n for (const cb of Array.from(emitter.listeners)) {\n try {\n cb(status);\n } catch (error) {\n debug(\"status listener error\", error);\n }\n }\n}\n\nfunction subscribeStatus(\n emitter: StatusEmitter,\n listener: (status: TransportRoomStatus) => void,\n): () => void {\n emitter.listeners.add(listener);\n try {\n listener(emitter.status);\n } catch (error) {\n debug(\"status listener error\", error);\n }\n return () => {\n emitter.listeners.delete(listener);\n };\n}\n\nfunction createSubscriptionClosedError(): Error {\n return new Error(\"subscription closed\");\n}\n\nfunction toError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error));\n}\n\nfunction createMetaJoinError(error?: StreamsTransportError): Error {\n return new Error(`Failed to join meta room: ${error?.code ?? \"unknown\"}`);\n}\n\nfunction createDocJoinError(\n docId: string,\n error?: StreamsTransportError,\n): Error {\n return new Error(\n `Failed to join doc room ${docId}: ${error?.code ?? \"unknown\"}`,\n );\n}\n\nfunction createFlockDocJoinError(\n flockDocId: string,\n error?: StreamsTransportError,\n): Error {\n return new Error(\n `Failed to join Flock doc room ${flockDocId}: ${error?.code ?? \"unknown\"}`,\n );\n}\n\nfunction mapStreamsStatus(\n status: StreamsRoomStatus | \"connecting\",\n): TransportRoomStatus {\n switch (status) {\n case \"joined\":\n return \"joined\";\n case \"reconnecting\":\n return \"reconnecting\";\n case \"error\":\n return \"error\";\n case \"connecting\":\n return \"connecting\";\n case \"disconnected\":\n default:\n return \"disconnected\";\n }\n}\n\nfunction mapConnectionStatus(\n status: TransportRoomStatus,\n): TransportConnectionStatus {\n switch (status) {\n case \"connecting\":\n return \"connecting\";\n case \"disconnected\":\n return \"disconnected\";\n case \"joined\":\n return \"connected\";\n case \"error\":\n return \"disconnected\";\n case \"reconnecting\":\n return \"connecting\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// StreamsTransportAdapter\n// ---------------------------------------------------------------------------\n\n/**\n * {@link TransportAdapter} implementation backed by `@loro-dev/streams-crdt`.\n *\n * Uses Durable Streams (HTTP long-poll) for syncing metadata and documents.\n * Ephemeral rooms are not supported.\n */\nexport class StreamsTransportAdapter implements TransportAdapter {\n private readonly options: StreamsTransportOptions;\n private readonly remoteCursorStore: RemoteCursorStore;\n private metaSession?: MetaSession;\n private readonly docSessions = new Map<string, DocSession>();\n private readonly flockDocSessions = new Map<string, FlockDocSession>();\n private connectionStatus: TransportConnectionStatus = \"disconnected\";\n private readonly connectionStatusListeners = new Set<\n (status: TransportConnectionStatus) => void\n >();\n\n constructor(options: StreamsTransportOptions) {\n this.options = options;\n this.remoteCursorStore =\n options.remoteCursorStore ?? new InMemoryRemoteCursorStore();\n }\n\n // -------------------------------------------------------------------------\n // Connection lifecycle\n // -------------------------------------------------------------------------\n\n async connect(): Promise<void> {\n debug(\"connect requested\");\n this.setConnectionStatus(\"connected\");\n }\n\n async close(): Promise<void> {\n debug(\"close requested\");\n\n // Close all doc streams\n for (const [docId, session] of this.docSessions) {\n debug(\"closing doc session\", { docId });\n await this.teardownDocSession(docId, session);\n }\n this.docSessions.clear();\n\n for (const [flockDocId, session] of this.flockDocSessions) {\n debug(\"closing flock doc session\", { flockDocId });\n await this.teardownFlockDocSession(flockDocId, session);\n }\n this.flockDocSessions.clear();\n\n // Close meta stream\n if (this.metaSession) {\n debug(\"closing meta session\");\n await this.teardownMetaSession(this.metaSession);\n this.metaSession = undefined;\n }\n\n this.setConnectionStatus(\"disconnected\");\n debug(\"close completed\");\n }\n\n isConnected(): boolean {\n return this.connectionStatus === \"connected\";\n }\n\n getStatus(): TransportConnectionStatus {\n return this.connectionStatus;\n }\n\n onStatusChange(\n listener: (status: TransportConnectionStatus) => void,\n ): () => void {\n this.connectionStatusListeners.add(listener);\n return () => {\n this.connectionStatusListeners.delete(listener);\n };\n }\n\n getLatency(): number | undefined {\n return undefined;\n }\n\n onLatency(_listener: (latencyMs: number) => void): () => void {\n return () => {};\n }\n\n async reconnect(): Promise<void> {\n debug(\"reconnect requested\");\n this.setConnectionStatus(\"connected\");\n const rejoinAttempts: Promise<unknown>[] = [];\n\n // Re-join disconnected meta session\n if (this.metaSession && !this.metaSession.closed) {\n if (this.metaSession.subscription) {\n const status = this.metaSession.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin meta session\", { status });\n this.metaSession.stream.rejoin();\n }\n } else if (this.metaSession.refCount > 0) {\n debug(\"retry incomplete meta session\");\n rejoinAttempts.push(this.joinMetaSession(this.metaSession));\n }\n }\n\n // Re-join disconnected doc sessions\n for (const [docId, session] of this.docSessions) {\n if (session.closed) continue;\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin doc session\", { docId, status });\n session.stream.rejoin();\n }\n } else if (session.refCount > 0) {\n debug(\"retry incomplete doc session\", { docId });\n rejoinAttempts.push(this.joinDocSession(session));\n }\n }\n\n for (const [flockDocId, session] of this.flockDocSessions) {\n if (session.closed) continue;\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin flock doc session\", { flockDocId, status });\n session.stream.rejoin();\n }\n } else if (session.refCount > 0) {\n debug(\"retry incomplete flock doc session\", { flockDocId });\n rejoinAttempts.push(this.joinFlockDocSession(session));\n }\n }\n\n await Promise.all(rejoinAttempts);\n }\n\n // -------------------------------------------------------------------------\n // Metadata sync / join\n // -------------------------------------------------------------------------\n\n async syncMeta(\n flock: Flock,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncMeta requested\");\n try {\n const session = await this.ensureMetaSession(flock);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncMeta failed\", result.error);\n return { ok: false };\n }\n debug(\"syncMeta completed\");\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncMeta error\", error);\n return { ok: false };\n }\n }\n\n joinMetaRoom(\n flock: Flock,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinMetaRoom requested\");\n\n const existing = this.metaSession;\n const rawSessionPromise = this.ensureMetaSession(flock, params?.auth);\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.flock === flock\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"meta session refCount incremented\", {\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseMetaSession(session),\n teardownUnretained: (session) => {\n if (session.refCount === 0 && this.metaSession === session) {\n void this.teardownMetaSession(session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForMetaFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveMetaSubscription(session),\n rejoin: (session) => this.rejoinMetaSession(session),\n });\n }\n\n // -------------------------------------------------------------------------\n // Document sync / join\n // -------------------------------------------------------------------------\n\n async syncDoc(\n docId: string,\n doc: LoroDoc,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncDoc requested\", { docId });\n try {\n const session = await this.ensureDocSession(docId, doc);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncDoc failed\", { docId, error: result.error });\n return { ok: false };\n }\n debug(\"syncDoc completed\", { docId });\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncDoc error\", { docId, error });\n return { ok: false };\n }\n }\n\n joinDocRoom(\n docId: string,\n doc: LoroDoc,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinDocRoom requested\", { docId });\n\n const existing = this.docSessions.get(docId);\n const rawSessionPromise = this.ensureDocSession(docId, doc, params?.auth);\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.doc === doc\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"doc session refCount incremented\", {\n docId,\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseDocSession(docId, session),\n teardownUnretained: (session) => {\n if (\n session.refCount === 0 &&\n this.docSessions.get(docId) === session\n ) {\n void this.teardownDocSession(docId, session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForDocFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveDocSubscription(session),\n rejoin: (session) => this.rejoinDocSession(session),\n });\n }\n\n async syncFlockDoc(\n flockDocId: string,\n flock: Flock,\n _options?: { timeout?: number },\n ): Promise<TransportSyncResult> {\n debug(\"syncFlockDoc requested\", { flockDocId });\n try {\n const session = await this.ensureFlockDocSession(flockDocId, flock);\n const result = await session.stream.sync();\n if (!result.ok) {\n debug(\"syncFlockDoc failed\", { flockDocId, error: result.error });\n return { ok: false };\n }\n debug(\"syncFlockDoc completed\", { flockDocId });\n this.setConnectionStatus(\"connected\");\n return { ok: true };\n } catch (error) {\n debug(\"syncFlockDoc error\", { flockDocId, error });\n return { ok: false };\n }\n }\n\n joinFlockDocRoom(\n flockDocId: string,\n flock: Flock,\n params?: TransportJoinParams,\n ): TransportSubscription {\n debug(\"joinFlockDocRoom requested\", { flockDocId });\n\n const existing = this.flockDocSessions.get(flockDocId);\n const rawSessionPromise = this.ensureFlockDocSession(\n flockDocId,\n flock,\n params?.auth,\n );\n return this.createRoomSubscription({\n rawSessionPromise,\n initialStatus:\n existing && existing.flock === flock\n ? existing.statusEmitter.status\n : \"connecting\",\n retain: (session) => {\n session.refCount += 1;\n debug(\"flock doc session refCount incremented\", {\n flockDocId,\n refCount: session.refCount,\n });\n },\n release: (session) => this.releaseFlockDocSession(flockDocId, session),\n teardownUnretained: (session) => {\n if (\n session.refCount === 0 &&\n this.flockDocSessions.get(flockDocId) === session\n ) {\n void this.teardownFlockDocSession(flockDocId, session).catch(() => {});\n }\n },\n waitForFirstSync: (session) => this.waitForFlockDocFirstSync(session),\n getActiveSubscription: (session) =>\n this.getActiveFlockDocSubscription(session),\n rejoin: (session) => this.rejoinFlockDocSession(session),\n });\n }\n\n async forgetFlockDoc(flockDocId: string): Promise<void> {\n debug(\"forgetFlockDoc requested\", { flockDocId });\n const session = this.flockDocSessions.get(flockDocId);\n if (session) {\n await this.teardownFlockDocSession(flockDocId, session);\n }\n await this.remoteCursorStore.delete?.(\n this.getFlockDocStreamUrl(flockDocId),\n );\n }\n\n // -------------------------------------------------------------------------\n // Ephemeral (not supported)\n // -------------------------------------------------------------------------\n\n joinEphemeralRoom(\n _roomId: string,\n ): TransportSubscription & { store: import(\"loro-crdt\").EphemeralStore } {\n throw new Error(\"StreamsTransportAdapter does not support ephemeral rooms\");\n }\n\n private createRoomSubscription<S extends StreamsSessionBase>({\n rawSessionPromise,\n initialStatus,\n retain,\n release,\n teardownUnretained,\n waitForFirstSync,\n getActiveSubscription,\n rejoin,\n }: CreateRoomSubscriptionOptions<S>): TransportSubscription {\n const statusProxy = createStatusEmitter(initialStatus);\n let unsubscribed = false;\n let retained = false;\n let detachStatusBridge: (() => void) | undefined;\n\n const sessionPromise = rawSessionPromise\n .then((session) => {\n const forwardStatus = (status: TransportRoomStatus) => {\n emitStatus(statusProxy, status);\n };\n session.statusEmitter.listeners.add(forwardStatus);\n detachStatusBridge = () => {\n session.statusEmitter.listeners.delete(forwardStatus);\n };\n emitStatus(statusProxy, session.statusEmitter.status);\n\n if (unsubscribed || session.closed) {\n detachStatusBridge();\n detachStatusBridge = undefined;\n throw createSubscriptionClosedError();\n }\n\n retain(session);\n retained = true;\n return session;\n })\n .catch((error) => {\n emitStatus(statusProxy, \"error\");\n throw error;\n });\n\n const requireActiveSession = async (): Promise<S> => {\n const session = await sessionPromise;\n if (unsubscribed || session.closed || !retained) {\n throw createSubscriptionClosedError();\n }\n return session;\n };\n\n void sessionPromise\n .then((session) => waitForFirstSync(session))\n .catch(() => {});\n\n return {\n unsubscribe: () => {\n if (unsubscribed) return;\n unsubscribed = true;\n detachStatusBridge?.();\n detachStatusBridge = undefined;\n void rawSessionPromise\n .then((session) => {\n if (retained) {\n release(session);\n } else {\n teardownUnretained(session);\n }\n })\n .catch(() => {});\n },\n get firstSyncedWithRemote() {\n return requireActiveSession().then((session) =>\n waitForFirstSync(session),\n );\n },\n waitUntilSynced: async () => {\n const session = await requireActiveSession();\n const activeSubscription = await getActiveSubscription(session);\n await activeSubscription.waitUntilSynced();\n },\n rejoin: async () => {\n const session = await requireActiveSession();\n await rejoin(session);\n },\n get status(): TransportRoomStatus {\n return statusProxy.status;\n },\n onStatusChange: (listener) => subscribeStatus(statusProxy, listener),\n };\n }\n\n // -------------------------------------------------------------------------\n // Internal: session management\n // -------------------------------------------------------------------------\n\n private resolveAuth(joinAuth?: Uint8Array): StreamsAuthProvider {\n if (joinAuth && joinAuth.length > 0) {\n const token = new TextDecoder().decode(joinAuth);\n return () => token;\n }\n return this.options.auth;\n }\n\n private joinMetaSession(\n session: MetaSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) => this.metaSession === candidate,\n createJoinError: createMetaJoinError,\n });\n }\n\n private joinDocSession(\n session: DocSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) =>\n this.docSessions.get(candidate.docId) === candidate,\n createJoinError: (error) => createDocJoinError(session.docId, error),\n });\n }\n\n private joinFlockDocSession(\n session: FlockDocSession,\n ): Promise<StreamsTransportSubscription> {\n return this.joinSession(session, {\n isCurrent: (candidate) =>\n this.flockDocSessions.get(candidate.flockDocId) === candidate,\n createJoinError: (error) =>\n createFlockDocJoinError(session.flockDocId, error),\n });\n }\n\n private joinSession<S extends StreamsSessionBase>(\n session: S,\n options: JoinSessionOptions<S>,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n\n let joinPromise!: Promise<StreamsTransportSubscription>;\n joinPromise = (async () => {\n await Promise.resolve();\n try {\n if (session.closed || !options.isCurrent(session)) {\n throw createSubscriptionClosedError();\n }\n\n // Signal transport-level connectivity before the join/sync begins,\n // so consumers can observe a meaningful syncing state while the\n // initial bootstrap is in progress.\n emitStatus(session.statusEmitter, \"connecting\");\n this.setConnectionStatus(\"connected\");\n\n const joinParams = {\n onStatusChange: (status: StreamsRoomStatus | \"connecting\") => {\n const s = mapStreamsStatus(status);\n emitStatus(session.statusEmitter, s);\n this.setConnectionStatus(mapConnectionStatus(s));\n },\n };\n const joinResult = await session.stream.join(joinParams);\n if (!joinResult.ok) {\n if (joinResult.error.retryable) {\n const retainedJoin = await session.stream.join(joinParams);\n if (retainedJoin.ok) {\n return this.retainJoinedSubscription(\n session,\n retainedJoin.value,\n options,\n );\n }\n }\n throw options.createJoinError(joinResult.error);\n }\n\n return this.retainJoinedSubscription(\n session,\n joinResult.value,\n options,\n );\n } catch (error) {\n const normalized = toError(error);\n session.subscription = undefined;\n session.lastJoinError = normalized;\n emitStatus(session.statusEmitter, \"error\");\n this.setConnectionStatus(\"disconnected\");\n throw normalized;\n } finally {\n if (session.joinPromise === joinPromise) {\n session.joinPromise = undefined;\n }\n }\n })();\n session.joinPromise = joinPromise;\n return joinPromise;\n }\n\n private retainJoinedSubscription<S extends StreamsSessionBase>(\n session: S,\n subscription: StreamsTransportSubscription,\n options: JoinSessionOptions<S>,\n ): StreamsTransportSubscription {\n if (session.closed || !options.isCurrent(session)) {\n subscription.unsubscribe();\n throw createSubscriptionClosedError();\n }\n\n session.subscription = subscription;\n session.lastJoinError = undefined;\n const status = mapStreamsStatus(subscription.status);\n emitStatus(session.statusEmitter, status);\n this.setConnectionStatus(mapConnectionStatus(status));\n return subscription;\n }\n\n private getActiveMetaSubscription(\n session: MetaSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ?? new Error(\"meta room is not joined\"),\n );\n }\n\n private async waitForMetaFirstSync(session: MetaSession): Promise<void> {\n const subscription = await this.joinMetaSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createMetaJoinError(subscription.lastError);\n }\n throw error;\n }\n }\n\n private getActiveDocSubscription(\n session: DocSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ?? new Error(`doc room ${session.docId} is not joined`),\n );\n }\n\n private async waitForDocFirstSync(session: DocSession): Promise<void> {\n const subscription = await this.joinDocSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createDocJoinError(session.docId, subscription.lastError);\n }\n throw error;\n }\n }\n\n private getActiveFlockDocSubscription(\n session: FlockDocSession,\n ): Promise<StreamsTransportSubscription> {\n if (session.closed) {\n return Promise.reject(createSubscriptionClosedError());\n }\n if (session.subscription) {\n return Promise.resolve(session.subscription);\n }\n if (session.joinPromise) {\n return session.joinPromise;\n }\n return Promise.reject(\n session.lastJoinError ??\n new Error(`flock doc room ${session.flockDocId} is not joined`),\n );\n }\n\n private async waitForFlockDocFirstSync(\n session: FlockDocSession,\n ): Promise<void> {\n const subscription = await this.joinFlockDocSession(session);\n try {\n await subscription.waitUntilSynced();\n } catch (error) {\n if (subscription.lastError) {\n throw createFlockDocJoinError(session.flockDocId, subscription.lastError);\n }\n throw error;\n }\n }\n\n private async rejoinMetaSession(session: MetaSession): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin meta session\", { status });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinMetaSession(session);\n }\n\n private async rejoinDocSession(session: DocSession): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin doc session\", { docId: session.docId, status });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinDocSession(session);\n }\n\n private async rejoinFlockDocSession(\n session: FlockDocSession,\n ): Promise<void> {\n if (session.closed) {\n throw createSubscriptionClosedError();\n }\n if (session.subscription) {\n const status = session.subscription.status;\n if (status === \"disconnected\" || status === \"error\") {\n debug(\"rejoin flock doc session\", {\n flockDocId: session.flockDocId,\n status,\n });\n session.stream.rejoin();\n }\n return;\n }\n await this.joinFlockDocSession(session);\n }\n\n private releaseMetaSession(session: MetaSession): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"meta session refCount decremented\", {\n refCount: session.refCount,\n });\n if (session.refCount === 0 && this.metaSession === session) {\n debug(\"tearing down meta session (refCount=0)\");\n void this.teardownMetaSession(session).catch(() => {});\n }\n }\n\n private releaseDocSession(docId: string, session: DocSession): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"doc session refCount decremented\", {\n docId,\n refCount: session.refCount,\n });\n if (session.refCount === 0 && this.docSessions.get(docId) === session) {\n debug(\"tearing down doc session (refCount=0)\", { docId });\n void this.teardownDocSession(docId, session).catch(() => {});\n }\n }\n\n private releaseFlockDocSession(\n flockDocId: string,\n session: FlockDocSession,\n ): void {\n session.refCount = Math.max(0, session.refCount - 1);\n debug(\"flock doc session refCount decremented\", {\n flockDocId,\n refCount: session.refCount,\n });\n if (\n session.refCount === 0 &&\n this.flockDocSessions.get(flockDocId) === session\n ) {\n debug(\"tearing down flock doc session (refCount=0)\", { flockDocId });\n void this.teardownFlockDocSession(flockDocId, session).catch(() => {});\n }\n }\n\n private async teardownMetaSession(session: MetaSession): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.metaSession === session) {\n this.metaSession = undefined;\n }\n }\n\n private async teardownDocSession(\n docId: string,\n session: DocSession,\n ): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.docSessions.get(docId) === session) {\n this.docSessions.delete(docId);\n }\n }\n\n private async teardownFlockDocSession(\n flockDocId: string,\n session: FlockDocSession,\n ): Promise<void> {\n session.closed = true;\n session.subscription?.unsubscribe();\n session.subscription = undefined;\n session.joinPromise = undefined;\n await session.stream.close();\n emitStatus(session.statusEmitter, \"disconnected\");\n if (this.flockDocSessions.get(flockDocId) === session) {\n this.flockDocSessions.delete(flockDocId);\n }\n }\n\n private async ensureMetaSession(\n flock: Flock,\n joinAuth?: Uint8Array,\n ): Promise<MetaSession> {\n if (this.metaSession && this.metaSession.flock === flock) {\n debug(\"reusing meta session\");\n return this.metaSession;\n }\n\n // Tear down previous session if flock instance changed\n if (this.metaSession) {\n debug(\"tearing down previous meta session (flock mismatch)\");\n await this.teardownMetaSession(this.metaSession);\n\n // Delete stale cursor so the new session bootstraps from scratch.\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId: this.options.metaStreamId ?? \"repo-meta\",\n baseUrl: this.options.baseUrl,\n });\n await this.remoteCursorStore.delete?.(streamUrl);\n }\n\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId: this.options.metaStreamId ?? \"repo-meta\",\n baseUrl: this.options.baseUrl,\n });\n debug(\"creating meta StreamsCrdt\", { streamUrl });\n\n const adapter = createFlockAdapter(patchFlockExportJson(flock));\n const { onPersistMeta } = this.options;\n const stream = new StreamsCrdt({\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n shardUrls: this.options.shardUrls,\n beforeRemoteCursorSave: onPersistMeta\n ? async () => {\n await onPersistMeta(flock);\n }\n : undefined,\n });\n\n const session: MetaSession = {\n stream,\n flock,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.metaSession = session;\n return session;\n }\n\n private async ensureDocSession(\n docId: string,\n doc: LoroDoc,\n joinAuth?: Uint8Array,\n ): Promise<DocSession> {\n const existing = this.docSessions.get(docId);\n if (existing && existing.doc === doc) {\n debug(\"reusing doc session\", { docId });\n return existing;\n }\n\n // Tear down previous session if doc instance changed\n if (existing) {\n debug(\"tearing down previous doc session (doc mismatch)\", { docId });\n await this.teardownDocSession(docId, existing);\n\n // Delete stale cursor so the new session bootstraps from scratch.\n // Without this, the cursor would tell StreamsCrdt to resume from a later\n // offset while the new doc is empty, creating a data hole.\n const streamId = this.options.docStreamId?.(docId) ?? docId;\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n await this.remoteCursorStore.delete?.(streamUrl);\n }\n\n const streamId = this.options.docStreamId?.(docId) ?? docId;\n const streamUrl = createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n debug(\"creating doc StreamsCrdt\", { docId, streamUrl });\n\n const adapter = createLoroDocAdapter(doc);\n const { onPersistDoc } = this.options;\n const stream = new StreamsCrdt({\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n shardUrls: this.options.shardUrls,\n beforeRemoteCursorSave: onPersistDoc\n ? async () => {\n await onPersistDoc(docId, doc);\n }\n : undefined,\n });\n\n const session: DocSession = {\n stream,\n doc,\n docId,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.docSessions.set(docId, session);\n return session;\n }\n\n private async ensureFlockDocSession(\n flockDocId: string,\n flock: Flock,\n joinAuth?: Uint8Array,\n ): Promise<FlockDocSession> {\n const existing = this.flockDocSessions.get(flockDocId);\n if (existing && existing.flock === flock) {\n debug(\"reusing flock doc session\", { flockDocId });\n return existing;\n }\n\n if (existing) {\n debug(\"tearing down previous flock doc session (flock mismatch)\", {\n flockDocId,\n });\n await this.teardownFlockDocSession(flockDocId, existing);\n await this.remoteCursorStore.delete?.(\n this.getFlockDocStreamUrl(flockDocId),\n );\n }\n\n const streamUrl = this.getFlockDocStreamUrl(flockDocId);\n debug(\"creating flock doc StreamsCrdt\", { flockDocId, streamUrl });\n\n const adapter = createFlockAdapter(patchFlockExportJson(flock));\n const { onPersistFlockDoc } = this.options;\n const streamOptions = {\n streamUrl,\n adapter,\n auth: this.resolveAuth(joinAuth),\n remoteCursorStore: this.remoteCursorStore,\n createStreamIfMissing: this.options.createStreamIfMissing ?? true,\n streamTtlSeconds: this.resolveFlockDocStreamTtlSeconds(flockDocId),\n snapshotCodec: this.options.snapshotCodec,\n snapshotUpload: this.options.snapshotUpload,\n reconnectConfig: this.options.reconnectConfig,\n shardUrls: this.options.shardUrls,\n beforeRemoteCursorSave: onPersistFlockDoc\n ? async () => {\n await onPersistFlockDoc(flockDocId, flock);\n }\n : undefined,\n };\n const stream = new StreamsCrdt(streamOptions);\n\n const session: FlockDocSession = {\n stream,\n flock,\n flockDocId,\n closed: false,\n refCount: 0,\n statusEmitter: createStatusEmitter(\"connecting\"),\n };\n this.flockDocSessions.set(flockDocId, session);\n return session;\n }\n\n private getFlockDocStreamUrl(flockDocId: string): string {\n const streamId = this.options.flockDocStreamId?.(flockDocId) ??\n `flock:${flockDocId}`;\n return createStreamUrl({\n bucketId: this.options.bucketId,\n streamId,\n baseUrl: this.options.baseUrl,\n });\n }\n\n private resolveFlockDocStreamTtlSeconds(\n flockDocId: string,\n ): number | undefined {\n const configured = this.options.flockDocStreamTtlMs;\n const ttlMs =\n typeof configured === \"function\"\n ? configured(flockDocId)\n : configured;\n if (\n typeof ttlMs !== \"number\" ||\n !Number.isFinite(ttlMs) ||\n ttlMs < 0\n ) {\n return undefined;\n }\n return ttlMs === 0 ? 0 : Math.ceil(ttlMs / 1_000);\n }\n\n // -------------------------------------------------------------------------\n // Internal: connection status\n // -------------------------------------------------------------------------\n\n private setConnectionStatus(status: TransportConnectionStatus): void {\n if (this.connectionStatus === status) return;\n this.connectionStatus = status;\n for (const listener of Array.from(this.connectionStatusListeners)) {\n try {\n listener(status);\n } catch (error) {\n debug(\"connection status listener error\", error);\n }\n }\n }\n}\n\nexport type { TransportJoinParams, TransportSubscription, TransportSyncResult };\n"],"mappings":";;;;;;AA6BA,MAAM,QAAQ,kBAAkB,oBAAoB;;;;;;;;;;;;;;;;;AAkBpD,SAAS,qBAAqB,OAAqB;CACjD,MAAM,OAAO,MAAM,WAAW,KAAK,MAAM;AACzC,CAAC,MAAc,cACb,KACA,0BACG;AACH,MAAI,OAAO,OAAO,QAAQ,YAAY,UAAU,KAAK;GACnD,MAAM,OAAO,IAAI;AACjB,OACE,QAAQ,QACR,OAAO,SAAS,YAChB,OAAO,KAAK,KAAe,CAAC,WAAW,GACvC;IAEA,MAAM,EAAE,MAAM,MAAO,GAAG,SAAS;AACjC,QAAI,OAAO,KAAK,KAAK,CAAC,WAAW,EAC/B,QAAO,MAAM;AAEf,WAAO,KAAK,MAAa,sBAAuB;;;AAGpD,SAAO,QAAQ,SACX,MAAM,GACN,KAAK,KAAY,sBAAuB;;AAE9C,QAAO;;AA4GT,SAAS,oBACP,UAA+B,cAChB;AACf,QAAO;EAAE,QAAQ;EAAS,2BAAW,IAAI,KAAK;EAAE;;AAGlD,SAAS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