loro-repo 0.18.0 → 0.18.2
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.
|
@@ -9,6 +9,9 @@ __loro_dev_streams_crdt_flock = require_chunk.__toESM(__loro_dev_streams_crdt_fl
|
|
|
9
9
|
|
|
10
10
|
//#region src/transport/streams.ts
|
|
11
11
|
const debug = require_debug.createDebugLogger("transport:streams");
|
|
12
|
+
function shouldRejoinRoom(status) {
|
|
13
|
+
return status === "disconnected" || status === "error" || status === "reconnecting";
|
|
14
|
+
}
|
|
12
15
|
/**
|
|
13
16
|
* Patches `flock.exportJson` so that an empty `from` version-vector (`{}`)
|
|
14
17
|
* is treated as "export everything" (i.e. no `from` constraint).
|
|
@@ -159,12 +162,12 @@ var StreamsTransportAdapter = class {
|
|
|
159
162
|
}
|
|
160
163
|
async reconnect() {
|
|
161
164
|
debug("reconnect requested");
|
|
162
|
-
this.
|
|
165
|
+
this.recomputeConnectionStatus();
|
|
163
166
|
const rejoinAttempts = [];
|
|
164
167
|
if (this.metaSession && !this.metaSession.closed) {
|
|
165
168
|
if (this.metaSession.subscription) {
|
|
166
169
|
const status = this.metaSession.subscription.status;
|
|
167
|
-
if (status
|
|
170
|
+
if (shouldRejoinRoom(status)) {
|
|
168
171
|
debug("rejoin meta session", { status });
|
|
169
172
|
this.metaSession.stream.rejoin();
|
|
170
173
|
}
|
|
@@ -177,7 +180,7 @@ var StreamsTransportAdapter = class {
|
|
|
177
180
|
if (session.closed) continue;
|
|
178
181
|
if (session.subscription) {
|
|
179
182
|
const status = session.subscription.status;
|
|
180
|
-
if (status
|
|
183
|
+
if (shouldRejoinRoom(status)) {
|
|
181
184
|
debug("rejoin doc session", {
|
|
182
185
|
docId,
|
|
183
186
|
status
|
|
@@ -193,7 +196,7 @@ var StreamsTransportAdapter = class {
|
|
|
193
196
|
if (session.closed) continue;
|
|
194
197
|
if (session.subscription) {
|
|
195
198
|
const status = session.subscription.status;
|
|
196
|
-
if (status
|
|
199
|
+
if (shouldRejoinRoom(status)) {
|
|
197
200
|
debug("rejoin flock doc session", {
|
|
198
201
|
flockDocId,
|
|
199
202
|
status
|
|
@@ -206,6 +209,7 @@ var StreamsTransportAdapter = class {
|
|
|
206
209
|
}
|
|
207
210
|
}
|
|
208
211
|
await Promise.all(rejoinAttempts);
|
|
212
|
+
this.recomputeConnectionStatus();
|
|
209
213
|
}
|
|
210
214
|
async syncMeta(flock, _options) {
|
|
211
215
|
debug("syncMeta requested");
|
|
@@ -525,7 +529,7 @@ var StreamsTransportAdapter = class {
|
|
|
525
529
|
if (session.closed) throw createSubscriptionClosedError();
|
|
526
530
|
if (session.subscription) {
|
|
527
531
|
const status = session.subscription.status;
|
|
528
|
-
if (status
|
|
532
|
+
if (shouldRejoinRoom(status)) {
|
|
529
533
|
debug("rejoin meta session", { status });
|
|
530
534
|
session.stream.rejoin();
|
|
531
535
|
}
|
|
@@ -537,7 +541,7 @@ var StreamsTransportAdapter = class {
|
|
|
537
541
|
if (session.closed) throw createSubscriptionClosedError();
|
|
538
542
|
if (session.subscription) {
|
|
539
543
|
const status = session.subscription.status;
|
|
540
|
-
if (status
|
|
544
|
+
if (shouldRejoinRoom(status)) {
|
|
541
545
|
debug("rejoin doc session", {
|
|
542
546
|
docId: session.docId,
|
|
543
547
|
status
|
|
@@ -552,7 +556,7 @@ var StreamsTransportAdapter = class {
|
|
|
552
556
|
if (session.closed) throw createSubscriptionClosedError();
|
|
553
557
|
if (session.subscription) {
|
|
554
558
|
const status = session.subscription.status;
|
|
555
|
-
if (status
|
|
559
|
+
if (shouldRejoinRoom(status)) {
|
|
556
560
|
debug("rejoin flock doc session", {
|
|
557
561
|
flockDocId: session.flockDocId,
|
|
558
562
|
status
|
|
@@ -653,6 +657,7 @@ var StreamsTransportAdapter = class {
|
|
|
653
657
|
snapshotCodec: this.options.snapshotCodec,
|
|
654
658
|
snapshotUpload: this.options.snapshotUpload,
|
|
655
659
|
reconnectConfig: this.options.reconnectConfig,
|
|
660
|
+
shardUrls: this.options.shardUrls,
|
|
656
661
|
beforeRemoteCursorSave: onPersistMeta ? async () => {
|
|
657
662
|
await onPersistMeta(flock);
|
|
658
663
|
} : void 0
|
|
@@ -704,6 +709,7 @@ var StreamsTransportAdapter = class {
|
|
|
704
709
|
snapshotCodec: this.options.snapshotCodec,
|
|
705
710
|
snapshotUpload: this.options.snapshotUpload,
|
|
706
711
|
reconnectConfig: this.options.reconnectConfig,
|
|
712
|
+
shardUrls: this.options.shardUrls,
|
|
707
713
|
beforeRemoteCursorSave: onPersistDoc ? async () => {
|
|
708
714
|
await onPersistDoc(docId, doc);
|
|
709
715
|
} : void 0
|
|
@@ -746,6 +752,7 @@ var StreamsTransportAdapter = class {
|
|
|
746
752
|
snapshotCodec: this.options.snapshotCodec,
|
|
747
753
|
snapshotUpload: this.options.snapshotUpload,
|
|
748
754
|
reconnectConfig: this.options.reconnectConfig,
|
|
755
|
+
shardUrls: this.options.shardUrls,
|
|
749
756
|
beforeRemoteCursorSave: onPersistFlockDoc ? async () => {
|
|
750
757
|
await onPersistFlockDoc(flockDocId, flock);
|
|
751
758
|
} : void 0
|
|
@@ -773,6 +780,29 @@ var StreamsTransportAdapter = class {
|
|
|
773
780
|
if (typeof ttlMs !== "number" || !Number.isFinite(ttlMs) || ttlMs < 0) return;
|
|
774
781
|
return ttlMs === 0 ? 0 : Math.ceil(ttlMs / 1e3);
|
|
775
782
|
}
|
|
783
|
+
recomputeConnectionStatus() {
|
|
784
|
+
this.setConnectionStatus(this.getConnectionStatusFromSessions());
|
|
785
|
+
}
|
|
786
|
+
getConnectionStatusFromSessions() {
|
|
787
|
+
let hasConnectingSession = false;
|
|
788
|
+
const visit = (session) => {
|
|
789
|
+
if (!session || session.closed) return;
|
|
790
|
+
const status = session.statusEmitter.status;
|
|
791
|
+
if (status === "disconnected" || status === "error") return "disconnected";
|
|
792
|
+
if (status === "connecting" || status === "reconnecting") hasConnectingSession = true;
|
|
793
|
+
};
|
|
794
|
+
const metaStatus = visit(this.metaSession);
|
|
795
|
+
if (metaStatus) return metaStatus;
|
|
796
|
+
for (const session of this.docSessions.values()) {
|
|
797
|
+
const status = visit(session);
|
|
798
|
+
if (status) return status;
|
|
799
|
+
}
|
|
800
|
+
for (const session of this.flockDocSessions.values()) {
|
|
801
|
+
const status = visit(session);
|
|
802
|
+
if (status) return status;
|
|
803
|
+
}
|
|
804
|
+
return hasConnectingSession ? "connecting" : "connected";
|
|
805
|
+
}
|
|
776
806
|
setConnectionStatus(status) {
|
|
777
807
|
if (this.connectionStatus === status) return;
|
|
778
808
|
this.connectionStatus = status;
|
|
@@ -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 { TransportJoinParams, TransportSubscription, TransportSyncResult };\n"],"mappings":";;;;;;;;;;AA4BA,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;;AA0GT,SAAS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AU,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\nfunction shouldRejoinRoom(status: StreamsRoomStatus): boolean {\n return (\n status === \"disconnected\" ||\n status === \"error\" ||\n // StreamsCrdt.rejoin() is the nudge that resets backoff and wakes an\n // already reconnecting room; it does not start a parallel join.\n status === \"reconnecting\"\n );\n}\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.recomputeConnectionStatus();\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 (shouldRejoinRoom(status)) {\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 (shouldRejoinRoom(status)) {\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 (shouldRejoinRoom(status)) {\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 this.recomputeConnectionStatus();\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 (shouldRejoinRoom(status)) {\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 (shouldRejoinRoom(status)) {\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 (shouldRejoinRoom(status)) {\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 recomputeConnectionStatus(): void {\n this.setConnectionStatus(this.getConnectionStatusFromSessions());\n }\n\n private getConnectionStatusFromSessions(): TransportConnectionStatus {\n let hasConnectingSession = false;\n\n const visit = (\n session?: StreamsSessionBase,\n ): TransportConnectionStatus | undefined => {\n if (!session || session.closed) {\n return undefined;\n }\n const status = session.statusEmitter.status;\n if (status === \"disconnected\" || status === \"error\") {\n return \"disconnected\";\n }\n if (status === \"connecting\" || status === \"reconnecting\") {\n hasConnectingSession = true;\n }\n return undefined;\n };\n\n const metaStatus = visit(this.metaSession);\n if (metaStatus) {\n return metaStatus;\n }\n\n for (const session of this.docSessions.values()) {\n const status = visit(session);\n if (status) {\n return status;\n }\n }\n\n for (const session of this.flockDocSessions.values()) {\n const status = visit(session);\n if (status) {\n return status;\n }\n }\n\n return hasConnectingSession ? \"connecting\" : \"connected\";\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;AAEpD,SAAS,iBAAiB,QAAoC;AAC5D,QACE,WAAW,kBACX,WAAW,WAGX,WAAW;;;;;;;;;;;;;;;;;;AAoBf,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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,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,4BAAkC;AACxC,OAAK,oBAAoB,KAAK,iCAAiC,CAAC;;CAGlE,AAAQ,kCAA6D;EACnE,IAAI,uBAAuB;EAE3B,MAAM,SACJ,YAC0C;AAC1C,OAAI,CAAC,WAAW,QAAQ,OACtB;GAEF,MAAM,SAAS,QAAQ,cAAc;AACrC,OAAI,WAAW,kBAAkB,WAAW,QAC1C,QAAO;AAET,OAAI,WAAW,gBAAgB,WAAW,eACxC,wBAAuB;;EAK3B,MAAM,aAAa,MAAM,KAAK,YAAY;AAC1C,MAAI,WACF,QAAO;AAGT,OAAK,MAAM,WAAW,KAAK,YAAY,QAAQ,EAAE;GAC/C,MAAM,SAAS,MAAM,QAAQ;AAC7B,OAAI,OACF,QAAO;;AAIX,OAAK,MAAM,WAAW,KAAK,iBAAiB,QAAQ,EAAE;GACpD,MAAM,SAAS,MAAM,QAAQ;AAC7B,OAAI,OACF,QAAO;;AAIX,SAAO,uBAAuB,eAAe;;CAG/C,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"}
|
|
@@ -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`.
|
|
@@ -120,6 +122,8 @@ declare class StreamsTransportAdapter implements TransportAdapter {
|
|
|
120
122
|
private ensureFlockDocSession;
|
|
121
123
|
private getFlockDocStreamUrl;
|
|
122
124
|
private resolveFlockDocStreamTtlSeconds;
|
|
125
|
+
private recomputeConnectionStatus;
|
|
126
|
+
private getConnectionStatusFromSessions;
|
|
123
127
|
private setConnectionStatus;
|
|
124
128
|
}
|
|
125
129
|
//#endregion
|
|
@@ -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`.
|
|
@@ -120,6 +122,8 @@ declare class StreamsTransportAdapter implements TransportAdapter {
|
|
|
120
122
|
private ensureFlockDocSession;
|
|
121
123
|
private getFlockDocStreamUrl;
|
|
122
124
|
private resolveFlockDocStreamTtlSeconds;
|
|
125
|
+
private recomputeConnectionStatus;
|
|
126
|
+
private getConnectionStatusFromSessions;
|
|
123
127
|
private setConnectionStatus;
|
|
124
128
|
}
|
|
125
129
|
//#endregion
|
|
@@ -5,6 +5,9 @@ import { createFlockAdapter } from "@loro-dev/streams-crdt/flock";
|
|
|
5
5
|
|
|
6
6
|
//#region src/transport/streams.ts
|
|
7
7
|
const debug = createDebugLogger("transport:streams");
|
|
8
|
+
function shouldRejoinRoom(status) {
|
|
9
|
+
return status === "disconnected" || status === "error" || status === "reconnecting";
|
|
10
|
+
}
|
|
8
11
|
/**
|
|
9
12
|
* Patches `flock.exportJson` so that an empty `from` version-vector (`{}`)
|
|
10
13
|
* is treated as "export everything" (i.e. no `from` constraint).
|
|
@@ -155,12 +158,12 @@ var StreamsTransportAdapter = class {
|
|
|
155
158
|
}
|
|
156
159
|
async reconnect() {
|
|
157
160
|
debug("reconnect requested");
|
|
158
|
-
this.
|
|
161
|
+
this.recomputeConnectionStatus();
|
|
159
162
|
const rejoinAttempts = [];
|
|
160
163
|
if (this.metaSession && !this.metaSession.closed) {
|
|
161
164
|
if (this.metaSession.subscription) {
|
|
162
165
|
const status = this.metaSession.subscription.status;
|
|
163
|
-
if (status
|
|
166
|
+
if (shouldRejoinRoom(status)) {
|
|
164
167
|
debug("rejoin meta session", { status });
|
|
165
168
|
this.metaSession.stream.rejoin();
|
|
166
169
|
}
|
|
@@ -173,7 +176,7 @@ var StreamsTransportAdapter = class {
|
|
|
173
176
|
if (session.closed) continue;
|
|
174
177
|
if (session.subscription) {
|
|
175
178
|
const status = session.subscription.status;
|
|
176
|
-
if (status
|
|
179
|
+
if (shouldRejoinRoom(status)) {
|
|
177
180
|
debug("rejoin doc session", {
|
|
178
181
|
docId,
|
|
179
182
|
status
|
|
@@ -189,7 +192,7 @@ var StreamsTransportAdapter = class {
|
|
|
189
192
|
if (session.closed) continue;
|
|
190
193
|
if (session.subscription) {
|
|
191
194
|
const status = session.subscription.status;
|
|
192
|
-
if (status
|
|
195
|
+
if (shouldRejoinRoom(status)) {
|
|
193
196
|
debug("rejoin flock doc session", {
|
|
194
197
|
flockDocId,
|
|
195
198
|
status
|
|
@@ -202,6 +205,7 @@ var StreamsTransportAdapter = class {
|
|
|
202
205
|
}
|
|
203
206
|
}
|
|
204
207
|
await Promise.all(rejoinAttempts);
|
|
208
|
+
this.recomputeConnectionStatus();
|
|
205
209
|
}
|
|
206
210
|
async syncMeta(flock, _options) {
|
|
207
211
|
debug("syncMeta requested");
|
|
@@ -521,7 +525,7 @@ var StreamsTransportAdapter = class {
|
|
|
521
525
|
if (session.closed) throw createSubscriptionClosedError();
|
|
522
526
|
if (session.subscription) {
|
|
523
527
|
const status = session.subscription.status;
|
|
524
|
-
if (status
|
|
528
|
+
if (shouldRejoinRoom(status)) {
|
|
525
529
|
debug("rejoin meta session", { status });
|
|
526
530
|
session.stream.rejoin();
|
|
527
531
|
}
|
|
@@ -533,7 +537,7 @@ var StreamsTransportAdapter = class {
|
|
|
533
537
|
if (session.closed) throw createSubscriptionClosedError();
|
|
534
538
|
if (session.subscription) {
|
|
535
539
|
const status = session.subscription.status;
|
|
536
|
-
if (status
|
|
540
|
+
if (shouldRejoinRoom(status)) {
|
|
537
541
|
debug("rejoin doc session", {
|
|
538
542
|
docId: session.docId,
|
|
539
543
|
status
|
|
@@ -548,7 +552,7 @@ var StreamsTransportAdapter = class {
|
|
|
548
552
|
if (session.closed) throw createSubscriptionClosedError();
|
|
549
553
|
if (session.subscription) {
|
|
550
554
|
const status = session.subscription.status;
|
|
551
|
-
if (status
|
|
555
|
+
if (shouldRejoinRoom(status)) {
|
|
552
556
|
debug("rejoin flock doc session", {
|
|
553
557
|
flockDocId: session.flockDocId,
|
|
554
558
|
status
|
|
@@ -649,6 +653,7 @@ var StreamsTransportAdapter = class {
|
|
|
649
653
|
snapshotCodec: this.options.snapshotCodec,
|
|
650
654
|
snapshotUpload: this.options.snapshotUpload,
|
|
651
655
|
reconnectConfig: this.options.reconnectConfig,
|
|
656
|
+
shardUrls: this.options.shardUrls,
|
|
652
657
|
beforeRemoteCursorSave: onPersistMeta ? async () => {
|
|
653
658
|
await onPersistMeta(flock);
|
|
654
659
|
} : void 0
|
|
@@ -700,6 +705,7 @@ var StreamsTransportAdapter = class {
|
|
|
700
705
|
snapshotCodec: this.options.snapshotCodec,
|
|
701
706
|
snapshotUpload: this.options.snapshotUpload,
|
|
702
707
|
reconnectConfig: this.options.reconnectConfig,
|
|
708
|
+
shardUrls: this.options.shardUrls,
|
|
703
709
|
beforeRemoteCursorSave: onPersistDoc ? async () => {
|
|
704
710
|
await onPersistDoc(docId, doc);
|
|
705
711
|
} : void 0
|
|
@@ -742,6 +748,7 @@ var StreamsTransportAdapter = class {
|
|
|
742
748
|
snapshotCodec: this.options.snapshotCodec,
|
|
743
749
|
snapshotUpload: this.options.snapshotUpload,
|
|
744
750
|
reconnectConfig: this.options.reconnectConfig,
|
|
751
|
+
shardUrls: this.options.shardUrls,
|
|
745
752
|
beforeRemoteCursorSave: onPersistFlockDoc ? async () => {
|
|
746
753
|
await onPersistFlockDoc(flockDocId, flock);
|
|
747
754
|
} : void 0
|
|
@@ -769,6 +776,29 @@ var StreamsTransportAdapter = class {
|
|
|
769
776
|
if (typeof ttlMs !== "number" || !Number.isFinite(ttlMs) || ttlMs < 0) return;
|
|
770
777
|
return ttlMs === 0 ? 0 : Math.ceil(ttlMs / 1e3);
|
|
771
778
|
}
|
|
779
|
+
recomputeConnectionStatus() {
|
|
780
|
+
this.setConnectionStatus(this.getConnectionStatusFromSessions());
|
|
781
|
+
}
|
|
782
|
+
getConnectionStatusFromSessions() {
|
|
783
|
+
let hasConnectingSession = false;
|
|
784
|
+
const visit = (session) => {
|
|
785
|
+
if (!session || session.closed) return;
|
|
786
|
+
const status = session.statusEmitter.status;
|
|
787
|
+
if (status === "disconnected" || status === "error") return "disconnected";
|
|
788
|
+
if (status === "connecting" || status === "reconnecting") hasConnectingSession = true;
|
|
789
|
+
};
|
|
790
|
+
const metaStatus = visit(this.metaSession);
|
|
791
|
+
if (metaStatus) return metaStatus;
|
|
792
|
+
for (const session of this.docSessions.values()) {
|
|
793
|
+
const status = visit(session);
|
|
794
|
+
if (status) return status;
|
|
795
|
+
}
|
|
796
|
+
for (const session of this.flockDocSessions.values()) {
|
|
797
|
+
const status = visit(session);
|
|
798
|
+
if (status) return status;
|
|
799
|
+
}
|
|
800
|
+
return hasConnectingSession ? "connecting" : "connected";
|
|
801
|
+
}
|
|
772
802
|
setConnectionStatus(status) {
|
|
773
803
|
if (this.connectionStatus === status) return;
|
|
774
804
|
this.connectionStatus = status;
|
|
@@ -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,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Ae,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,SAAO,gBAAgB;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.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\nfunction shouldRejoinRoom(status: StreamsRoomStatus): boolean {\n return (\n status === \"disconnected\" ||\n status === \"error\" ||\n // StreamsCrdt.rejoin() is the nudge that resets backoff and wakes an\n // already reconnecting room; it does not start a parallel join.\n status === \"reconnecting\"\n );\n}\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.recomputeConnectionStatus();\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 (shouldRejoinRoom(status)) {\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 (shouldRejoinRoom(status)) {\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 (shouldRejoinRoom(status)) {\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 this.recomputeConnectionStatus();\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 (shouldRejoinRoom(status)) {\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 (shouldRejoinRoom(status)) {\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 (shouldRejoinRoom(status)) {\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 recomputeConnectionStatus(): void {\n this.setConnectionStatus(this.getConnectionStatusFromSessions());\n }\n\n private getConnectionStatusFromSessions(): TransportConnectionStatus {\n let hasConnectingSession = false;\n\n const visit = (\n session?: StreamsSessionBase,\n ): TransportConnectionStatus | undefined => {\n if (!session || session.closed) {\n return undefined;\n }\n const status = session.statusEmitter.status;\n if (status === \"disconnected\" || status === \"error\") {\n return \"disconnected\";\n }\n if (status === \"connecting\" || status === \"reconnecting\") {\n hasConnectingSession = true;\n }\n return undefined;\n };\n\n const metaStatus = visit(this.metaSession);\n if (metaStatus) {\n return metaStatus;\n }\n\n for (const session of this.docSessions.values()) {\n const status = visit(session);\n if (status) {\n return status;\n }\n }\n\n for (const session of this.flockDocSessions.values()) {\n const status = visit(session);\n if (status) {\n return status;\n }\n }\n\n return hasConnectingSession ? \"connecting\" : \"connected\";\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;AAEpD,SAAS,iBAAiB,QAAoC;AAC5D,QACE,WAAW,kBACX,WAAW,WAGX,WAAW;;;;;;;;;;;;;;;;;;AAoBf,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,QA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