lody 0.115.0 → 0.116.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/dist/{access-Sut1_1-c.js → access-DIhEb_MP.js} +333 -314
  2. package/dist/{acp-interaction-owner-uSfNzpiU.js → acp-interaction-owner-8OMcZVET.js} +33 -33
  3. package/dist/{agent-execution-D1-dEIN6.js → agent-execution-ZTPT3A88.js} +13 -13
  4. package/dist/{analytics-events-BQIrmfJp.js → analytics-events-BNLOju7l.js} +2 -2
  5. package/dist/{app-J2sTmsZo.js → app-DzrwnZPK.js} +34 -34
  6. package/dist/{application-runtime-BPgp9fKR.js → application-runtime-4EGQJvLm.js} +2 -2
  7. package/dist/{auth-CTegS0TL.js → auth-CA7u_ijj.js} +8 -8
  8. package/dist/{automation-BL7x_nUm.js → automation-ClFKwWKg.js} +34 -34
  9. package/dist/baguette-worker.js +6 -6
  10. package/dist/chunks/{vendor-@agentclientprotocol-sdk-CpxTRW1f.js → vendor-@agentclientprotocol-sdk-54yhgJSn.js} +2 -2
  11. package/dist/chunks/{vendor-@anthropic-ai-claude-agent-sdk-B0HhZ112.js → vendor-@anthropic-ai-claude-agent-sdk-NAjHQcVv.js} +27 -3
  12. package/dist/chunks/{vendor-@better-auth-api-key-D0bKvhcn.js → vendor-@better-auth-api-key-Dy9PtbSj.js} +2 -2
  13. package/dist/chunks/{vendor-@better-auth-core-Dpzqxq_j.js → vendor-@better-auth-core-C7hql1k7.js} +8 -8
  14. package/dist/chunks/{vendor-@effect-platform-node-shared-DkrmBObz.js → vendor-@effect-platform-node-shared-DUSlMsdQ.js} +2 -2
  15. package/dist/chunks/{vendor-@loro-dev-streams-client-DPTfaXHE.js → vendor-@loro-dev-streams-client-DkeRiNAY.js} +1329 -88
  16. package/dist/chunks/{vendor-@loro-dev-streams-crdt-BOuVa3yO.js → vendor-@loro-dev-streams-crdt-CsXRvQxK.js} +861 -322
  17. package/dist/chunks/{vendor-@modelcontextprotocol-client-B_Q9G9Ku.js → vendor-@modelcontextprotocol-client-DuJtk4js.js} +3 -3
  18. package/dist/chunks/{vendor-@modelcontextprotocol-core-CW-vRGZP.js → vendor-@modelcontextprotocol-core-BkUcdvo6.js} +2 -2
  19. package/dist/chunks/{vendor-@modelcontextprotocol-node-CSCPUEbv.js → vendor-@modelcontextprotocol-node-D0s30TCx.js} +2 -2
  20. package/dist/chunks/{vendor-@modelcontextprotocol-server-BA5N3RYD.js → vendor-@modelcontextprotocol-server-C9c_OMTp.js} +3 -3
  21. package/dist/chunks/{vendor-@opencode-codemode-61MXX511.js → vendor-@opencode-codemode-DmkYINkB.js} +2 -2
  22. package/dist/chunks/{vendor-@sorbetai-artifacts-Dt9BTK8Q.js → vendor-@sorbetai-artifacts-Vz3r0uhj.js} +3 -3
  23. package/dist/chunks/{vendor-@sorbetai-context-COh8_Kmc.js → vendor-@sorbetai-context-BV7q3KwO.js} +2 -2
  24. package/dist/chunks/{vendor-@sorbetai-control-HcZa4Y-V.js → vendor-@sorbetai-control-C9pxQF9a.js} +137 -51
  25. package/dist/chunks/{vendor-@sorbetai-plugins-Bs93fyHc.js → vendor-@sorbetai-plugins-COkYjDxn.js} +3 -3
  26. package/dist/chunks/{vendor-@sorbetai-runtime-kicj4Xs_.js → vendor-@sorbetai-runtime-DKAfUiS0.js} +172 -60
  27. package/dist/chunks/{vendor-@sorbetai-schema-BYxzbt6U.js → vendor-@sorbetai-schema-D53JJ0HJ.js} +2 -2
  28. package/dist/chunks/{vendor-better-auth-PQ6PT4aF.js → vendor-better-auth-D1bP-dEy.js} +2 -2
  29. package/dist/chunks/{vendor-effect-CNM-5PoN.js → vendor-effect-BTVRmkqM.js} +418 -418
  30. package/dist/chunks/{vendor-es-toolkit-DnvFX_hl.js → vendor-es-toolkit-BDp9OdLC.js} +4 -4
  31. package/dist/chunks/{vendor-loro-repo-B1zdQ8Qd.js → vendor-loro-repo-DbOhEZ39.js} +2166 -93
  32. package/dist/chunks/{vendor-zod-DAcQjQuC.js → vendor-zod-nebGZ0VM.js} +6 -6
  33. package/dist/claude-acp.js +28 -7
  34. package/dist/{cli-platform-Cfc6A61f.js → cli-platform-qpp4fxi7.js} +6 -6
  35. package/dist/{cli-presence-application-D2Dn0fPM.js → cli-presence-application-Cw9rnD3u.js} +18 -18
  36. package/dist/{client-BsIzN-iC.js → client-09TiIsd2.js} +33 -33
  37. package/dist/{cloudflared-native-DmvSYnMb.js → cloudflared-native-Ber1sIlU.js} +4 -4
  38. package/dist/cloudflared-worker.js +7 -7
  39. package/dist/{code-collab-Cgso3Ix3.js → code-collab-DRoDl8u7.js} +3 -3
  40. package/dist/codex-acp.js +2 -1
  41. package/dist/{command-runtime-C7EPuHLe.js → command-runtime-CYs2KAyh.js} +774 -224
  42. package/dist/{const-LYLptZ7f.js → const-C9yql4zo.js} +2 -2
  43. package/dist/{control-CgRxpxvc.js → control-HMzEZJTm.js} +36 -36
  44. package/dist/{cross-workspace-D6-aE1-w.js → cross-workspace-CEB-pWmO.js} +3 -3
  45. package/dist/{daemon-runner-Bn8O9-a0.js → daemon-runner-BHgvKJ_l.js} +27 -27
  46. package/dist/{daemon-DWm2IzH9.js → daemon-s8LqFNYd.js} +30 -30
  47. package/dist/{daemon-session-tools-BSAgq4O1.js → daemon-session-tools-CrxHUVDk.js} +46 -46
  48. package/dist/{daemon-shared-NcwWGSEj.js → daemon-shared-BGfDcTED.js} +10 -10
  49. package/dist/{daemon-update-qOLnkZcv.js → daemon-update-BjGbzSFc.js} +2 -2
  50. package/dist/deepseek-acp.js +14 -2
  51. package/dist/{deepseek-harness-runtime-D6lV9pxi.js → deepseek-harness-runtime-CtfyKY7w.js} +8 -8
  52. package/dist/{deepseek-system-node-C2YpUQwp.js → deepseek-system-node-CBHH8N-Z.js} +4 -4
  53. package/dist/{device-preview-BjqAbZ9g.js → device-preview-WVdriBmC.js} +36 -11
  54. package/dist/devin-acp.js +2 -1
  55. package/dist/{diff-line-counts-ClicfZ_E.js → diff-line-counts-C7vhQioX.js} +2 -2
  56. package/dist/{diff-worker-task-BVD3EgeO.js → diff-worker-task-wwEm25bo.js} +2 -2
  57. package/dist/diff-worker.js +5 -5
  58. package/dist/{discovery-query-C_7lyBI8.js → discovery-query-6rvHO0Ax.js} +4 -4
  59. package/dist/{dsh-DVyIAYZ9.js → dsh-D8jYqbih.js} +9 -9
  60. package/dist/{dsh-plugins-Dfsqsiu7.js → dsh-plugins-BGuhIgPz.js} +15 -15
  61. package/dist/{e2ee-CslOKVIM.js → e2ee-BDxs5Gma.js} +3 -3
  62. package/dist/{e2ee-execution-intent-DYBEG410.js → e2ee-execution-intent-BTTWEaTs.js} +4 -4
  63. package/dist/{export-C-zeWP1i.js → export-BVe6KJcH.js} +40 -40
  64. package/dist/{feedback-Dde39k5W.js → feedback-8RRkLuXP.js} +34 -34
  65. package/dist/{feedback-jvl2Dz8w.js → feedback-Da3aBQ2E.js} +4 -4
  66. package/dist/{file-index-scan-core-Bta7tnbY.js → file-index-scan-core-QNHdA1nq.js} +5 -5
  67. package/dist/file-index-scan-worker.js +8 -8
  68. package/dist/{file-lock-By0YSSDw.js → file-lock-Oeerthnp.js} +9 -9
  69. package/dist/{github-BtMkInqL.js → github-B3lOSLjx.js} +33 -33
  70. package/dist/grok-acp.js +2 -1
  71. package/dist/{http-transport-C1f1XEnB.js → http-transport-3J_3rzKQ.js} +6 -6
  72. package/dist/{index-C41WZg1y.js → index-C5TYbo5p.js} +2 -2
  73. package/dist/{index-CitAbDql.js → index-CNsJ2gEh.js} +19 -6
  74. package/dist/{index-BUam8GIX.js → index-CbO2HBCx.js} +35 -35
  75. package/dist/{index-Ce9khNjj.js → index-CvTdgB45.js} +87 -75
  76. package/dist/{index-BsfKnSuo.js → index-CzJfh76P.js} +991 -964
  77. package/dist/index-DdJk9U2O.js +202 -0
  78. package/dist/{index-Dy-FYtdl.js → index-DtKSPvAx.js} +41 -41
  79. package/dist/{index-CZG5q6QS.js → index-PK9ed2VJ.js} +4 -4
  80. package/dist/{index-CwHleXV2.js → index-Z-EXLH2-.js} +2 -2
  81. package/dist/index.js +15 -15
  82. package/dist/{internal-BPOwohVc.js → internal-210PnQHj.js} +48 -48
  83. package/dist/{ios-simulator-BduF_qia.js → ios-simulator-B8Edygo_.js} +10 -10
  84. package/dist/{local-cli-host-lease-Chm4-jV0.js → local-cli-host-lease-BcOQ-7Gk.js} +3 -3
  85. package/dist/{local-ipc-B8vySppK.js → local-ipc-BNwkKO5i.js} +156 -103
  86. package/dist/{local-project-control-client-CIBpaXbo.js → local-project-control-client-BKaZlhrn.js} +5 -5
  87. package/dist/{lody-mcp-http-protocol-DBLKn7SZ.js → lody-mcp-http-protocol-C24PR-58.js} +46 -10
  88. package/dist/{lody-mcp-server-B4OeNPT4.js → lody-mcp-server-C_KUMdUq.js} +84 -39
  89. package/dist/{logger-C-G7jpWR.js → logger-zm-QQb1B.js} +2 -2
  90. package/dist/{login-Df1IkdeV.js → login-DoRU06W8.js} +18 -18
  91. package/dist/{login-shell-env-HKDW5zwx.js → login-shell-env-CFLesG20.js} +6 -6
  92. package/dist/{logout-gDuSiB0l.js → logout-4T76xG1C.js} +18 -18
  93. package/dist/{machine-bjdZ1hmy.js → machine-BFM6JQSw.js} +42 -42
  94. package/dist/{machine-identity-restore-BuoxXyiw.js → machine-identity-restore-CYjkTQcN.js} +3 -3
  95. package/dist/{machine-protocol-capabilities-DEhAj9SH.js → machine-protocol-capabilities-DcJpLvsC.js} +68 -47
  96. package/dist/{magpie-import-IrqfCF6i.js → magpie-import-CsiqaviF.js} +52 -50
  97. package/dist/{managed-daemon-forwarding-BpXhy_-O.js → managed-daemon-forwarding-D10w26x_.js} +9 -9
  98. package/dist/{managed-daemon-release-CwkvVtSj.js → managed-daemon-release-Bq0NQ5KB.js} +8 -8
  99. package/dist/{mcp-DTnh_PAT.js → mcp-CFSVE37k.js} +39 -39
  100. package/dist/{migrate-CUdZ3XBR.js → migrate-D0JGnFDi.js} +40 -38
  101. package/dist/{open-browser-3TOC7G1u.js → open-browser-CXJ_k8PZ.js} +3 -3
  102. package/dist/{operation-CzLcjV3W.js → operation-CjjYD8KR.js} +35 -35
  103. package/dist/{operation-store-rllAX2mr.js → operation-store-CjW-plfi.js} +6 -6
  104. package/dist/{presence-CZco7UQH.js → presence-DfPa6xSX.js} +95 -71
  105. package/dist/{presence-legacy-DIYBtj5j.js → presence-legacy-B7H0xyqf.js} +5 -5
  106. package/dist/{process-DrX1wZZk.js → process-BU5vWwzZ.js} +3 -3
  107. package/dist/{process-options-DNYWY_s6.js → process-options-CvxupoAj.js} +4 -4
  108. package/dist/{project-C_EZ2dLN.js → project-DbFdl-Tc.js} +41 -41
  109. package/dist/{project-path-CAQE9bes.js → project-path-BylnHhzQ.js} +11 -11
  110. package/dist/{realtime-journal-DyMe8jsR.js → realtime-journal-D5hdU6Fc.js} +2 -2
  111. package/dist/{register-VLBUVPh5.js → register-DzkfcD0R.js} +33 -33
  112. package/dist/{registry-generated-wkLapT7U.js → registry-generated-BtQFYqS0.js} +30 -30
  113. package/dist/{remote-pairing-D24xSpRh.js → remote-pairing-B-1pCVbn.js} +40 -40
  114. package/dist/{reset-identity-DVubJrt0.js → reset-identity-BKSdKzDv.js} +40 -40
  115. package/dist/{review-6aCgWEdv.js → review-DHDdCwwj.js} +9 -9
  116. package/dist/{review-viewer-CRYK94SE.js → review-viewer-DO7rhsH9.js} +3 -3
  117. package/dist/{rpc-secret-CPdan_XW.js → rpc-secret-Ds9rnsWf.js} +2 -2
  118. package/dist/{runtime-diagnostics-5l1pBD3m.js → runtime-diagnostics-BElvgU5u.js} +5 -5
  119. package/dist/{schedule-CGTbG70S.js → schedule-C-UJnfpM.js} +39 -39
  120. package/dist/{schedule-command-client-C6matZWn.js → schedule-command-client-B2k5ix1s.js} +38 -38
  121. package/dist/{schedule-command-service-2gToipBI.js → schedule-command-service-pFq9cQHf.js} +134 -58
  122. package/dist/{schedule-documents-DRc0byQm.js → schedule-documents-Di23etFx.js} +3 -3
  123. package/dist/{schedule-recurrence-BVxMRfp4.js → schedule-recurrence-D4r80Udd.js} +42 -14
  124. package/dist/{schedule-repository-dz9iwR0x.js → schedule-repository-BNUNXl15.js} +4 -4
  125. package/dist/{schedule-run-preparation-1oSQ5i-A.js → schedule-run-preparation-D2GjotJy.js} +5 -5
  126. package/dist/{schedule-types-BquxGfza.js → schedule-types-B9O0I1Ui.js} +472 -364
  127. package/dist/{service-D9xJKmI-.js → service-pb71b8fj.js} +5 -5
  128. package/dist/{session-npaRR-y3.js → session-C6dNbMjx.js} +21 -21
  129. package/dist/{session-file-blob-store-CBHDgf4e.js → session-file-blob-store-CdpmEU94.js} +4 -4
  130. package/dist/{session-image-download-DUwc2Fb4.js → session-image-download-DeZ6r1-w.js} +4 -4
  131. package/dist/{session-input-MeZheBJ0.js → session-input-Dz8R9xPL.js} +3 -3
  132. package/dist/{session-link-demCF_Y_.js → session-link-CABPzB2T.js} +51 -2
  133. package/dist/{session-link-export-BM1zZQRs.js → session-link-export-CabjkQNk.js} +3 -3
  134. package/dist/{session-operation-targets-lq3rsTnV.js → session-operation-targets-B-VimRwZ.js} +3 -3
  135. package/dist/{setting-Cq6nKJgF.js → setting-CKO-Tb-e.js} +116 -64
  136. package/dist/{start-BolVcMOA.js → start-B83c1-EW.js} +957 -297
  137. package/dist/streams-crdt-factory-CkuXGilB.js +17 -0
  138. package/dist/{subagent-emitter-DALyc5yu.js → subagent-emitter-D-zUFnS9.js} +2 -2
  139. package/dist/{subagent-events-CyFbbE20.js → subagent-events-D22OQNDm.js} +7 -2
  140. package/dist/{sync-BrDYKZ4H.js → sync-Cf_HanAI.js} +35 -35
  141. package/dist/{time-sync-D63wG9u-.js → time-sync-DjSg4eHx.js} +2 -2
  142. package/dist/{workspace-Bthb-nhu.js → workspace-BCjgp5pF.js} +36 -36
  143. package/dist/{workspace-legacy-jZ0D5Xl-.js → workspace-legacy-DJAko-Yj.js} +24 -24
  144. package/package.json +5 -5
  145. package/dist/index-BTgKuz44.js +0 -65
@@ -1,5 +1,5 @@
1
- import { a as acquireDurableWsMultiplexer, f as formatWsOffset, D as DsWsError, i as isValidWsStreamFullId, p as parseWsOffset, I as IoOwner, r as readSseEvents, d as decodeSsePayload, n as networkErrorCode, s as safeRequestId, S as StreamsClient, b as DEFAULT_TIMEOUT_CONFIG, t as thrownToStreamError, c as createDiagnosticId, e as StreamsAuth, g as parseSseControlData, o as ownedTask, m as makeStreamsHttp, w as withSafeSpan, h as StreamsHttpFailure, j as StreamsHttpClosed, k as StreamsHttpReleaseFailure, l as isSseUnsupportedErrorText, q as extractBoundary, u as decodeMultipartMixed, v as parseStreamErrorCode } from "./vendor-@loro-dev-streams-client-DPTfaXHE.js";
2
- import { R as fnUntraced, av as TaggedError, ax as succeed, s as succeed$1, y as map, aw as Service, b0 as Reference, v as void_, b4 as logDebug, aA as Clock, aB as die, a3 as make, a4 as provide, a5 as make$1, j as fail, ae as combine, al as interrupt, aD as make$2, b5 as forkIn, a2 as gen, a9 as exit, ad as isFailure, b6 as fail$1, aN as done, as as _await, aW as make$3, aZ as setHeader, b7 as bodyUint8Array, aY as bearerToken, a_ as provideService, a$ as TracerDisabledWhen, aF as mapError, aG as promise, L as try_, aU as failCause, aK as ensuring, d as sync, b8 as never, aI as timeoutOrElse, aH as makeUnsafe, r as raceFirst, ap as hasInterruptsOnly, ao as isSuccess, b9 as yieldNow, aV as findErrorOption, ba as currentTimeMillis, aj as doneUnsafe, aE as sleep$1, b as flatMap, aa as close, ab as void_$1, aq as join, au as interruptible, ah as asVoid, p as fail$2, aM as catchCause, aL as addFinalizer, q as suspend, E as orDie, a8 as run$1, _ as fail$3, ay as uninterruptibleMask, ac as tap, bb as isTimeoutError, aR as await_, bc as catch_, ai as empty, bd as uninterruptible, be as makeUnsafe$1, b1 as fromWeb, b2 as HttpClientError, b3 as TransportError, bf as make$4, x as effect, bg as provide$1, aC as make$5, a6 as make$6, bh as make$7, C as acquireRelease, bi as shutdown, bj as make$8, e as forever, bk as take, bl as Scope, bm as changes, bn as buffer, bo as interruptWhen, T as offerUnsafe, aP as onExit, bp as forever$1, bq as setInputType, br as modifyDelay, bs as next, ag as succeed$2, Y as offer, bt as toStepWithSleep, aJ as all, bu as isExit, bv as isDone, bw as set, ak as isPromise, B as tryPromise, at as isDoneUnsafe, af as andThen, bx as catchTag, by as filter, bz as take$1, bA as runDrain } from "./vendor-effect-CNM-5PoN.js";
1
+ import { w as wsAuthFromProvider, a as acquireDurableWsMultiplexer, f as formatWsOffset, D as DsWsError, p as parseWsOffset, i as isValidWsStreamFullId, d as deriveWsAuthPoolKey, I as IoOwner, r as readSseEvents, b as decodeSsePayload, n as networkErrorCode, s as safeRequestId, S as StreamsClient, c as DEFAULT_TIMEOUT_CONFIG, t as thrownToStreamError, e as createDiagnosticId, g as StreamsAuth, h as parseSseControlData, o as ownedTask, m as makeStreamsHttp, j as withSafeSpan, k as StreamsHttpFailure, l as StreamsHttpClosed, q as StreamsHttpReleaseFailure, u as isSseUnsupportedErrorText, v as extractBoundary, x as decodeMultipartMixed, y as parseStreamErrorCode } from "./vendor-@loro-dev-streams-client-DkeRiNAY.js";
2
+ import { N as fnUntraced, T as TaggedError, J as succeed, K as succeed$1, ar as map, S as Service, an as Reference, q as void_, as as logDebug, O as Clock, P as die, m as make, p as provide, b as make$1, R as fail, h as combine, y as interrupt, U as make$2, at as forkIn, g as gen, e as exit, i as isFailure, au as fail$1, a7 as done, _ as _await, ah as make$3, ak as setHeader, av as bodyUint8Array, aj as bearerToken, al as provideService, am as TracerDisabledWhen, Y as mapError, V as promise, aw as try_, af as failCause, a2 as ensuring, s as sync, ax as never, $ as timeoutOrElse, Z as makeUnsafe, W as raceFirst, D as hasInterruptsOnly, C as isSuccess, ay as yieldNow, ag as findErrorOption, az as currentTimeMillis, o as doneUnsafe, X as sleep$1, E as flatMap, f as close, v as void_$1, F as join, I as interruptible, l as asVoid, a6 as fail$2, a5 as catchCause, a3 as addFinalizer, x as suspend, a4 as orDie, r as run$1, u as fail$3, L as uninterruptibleMask, t as tap, aA as isTimeoutError, ac as await_, aB as catch_, n as empty, aC as uninterruptible, aD as makeUnsafe$1, ao as fromWeb, ap as HttpClientError, aq as TransportError, aE as make$4, aF as effect, aG as provide$1, Q as make$5, c as make$6, aH as make$7, ab as acquireRelease, aI as shutdown, aJ as make$8, aK as forever, aL as take, aM as Scope, aN as changes, aO as buffer, aP as interruptWhen, aQ as offerUnsafe, a9 as onExit, aR as succeed$2, aa as acquireUseRelease, aS as forever$1, aT as setInputType, aU as modifyDelay, aV as next, k as succeed$3, aW as offer, aX as toStepWithSleep, a1 as all, aY as isExit, aZ as isDone, a0 as callback, a_ as set, w as isPromise, z as tryPromise, H as isDoneUnsafe, j as andThen, a$ as catchTag, b0 as filter, b1 as take$1, b2 as runDrain } from "./vendor-effect-BTVRmkqM.js";
3
3
  import { L as LoroDoc, V as VersionVector, d as decodeImportBlobMeta } from "./vendor-loro-crdt-2CFvB1HS.js";
4
4
  import { F as Flock } from "./vendor-@loro-dev-flock-wasm-BH1ts_Xn.js";
5
5
  const contexts = /* @__PURE__ */ new WeakMap();
@@ -1215,6 +1215,8 @@ function resolveNextOffsetAfterConcurrentAdvance(requestOffset, currentOffset, r
1215
1215
  if (current != null && incoming != null) return incoming > current ? responseNextOffset : currentOffset;
1216
1216
  return currentOffset;
1217
1217
  }
1218
+ const DS_WS_INITIAL_MAX_INLINE_BYTES = 65536n;
1219
+ const WS_READ_COOLDOWN_MS = 3e4;
1218
1220
  function wsStreamIdFor(streamUrl, override) {
1219
1221
  if (override != null) return isValidWsStreamFullId(override) ? override : void 0;
1220
1222
  let url;
@@ -1252,190 +1254,11 @@ function joinOffsetFor(offset) {
1252
1254
  return;
1253
1255
  }
1254
1256
  }
1255
- const bridgedFunctionAuth = /* @__PURE__ */ new WeakMap();
1256
- const stringAuthPoolKeys = /* @__PURE__ */ new WeakMap();
1257
- const SHA256_K = new Uint32Array([
1258
- 1116352408,
1259
- 1899447441,
1260
- 3049323471,
1261
- 3921009573,
1262
- 961987163,
1263
- 1508970993,
1264
- 2453635748,
1265
- 2870763221,
1266
- 3624381080,
1267
- 310598401,
1268
- 607225278,
1269
- 1426881987,
1270
- 1925078388,
1271
- 2162078206,
1272
- 2614888103,
1273
- 3248222580,
1274
- 3835390401,
1275
- 4022224774,
1276
- 264347078,
1277
- 604807628,
1278
- 770255983,
1279
- 1249150122,
1280
- 1555081692,
1281
- 1996064986,
1282
- 2554220882,
1283
- 2821834349,
1284
- 2952996808,
1285
- 3210313671,
1286
- 3336571891,
1287
- 3584528711,
1288
- 113926993,
1289
- 338241895,
1290
- 666307205,
1291
- 773529912,
1292
- 1294757372,
1293
- 1396182291,
1294
- 1695183700,
1295
- 1986661051,
1296
- 2177026350,
1297
- 2456956037,
1298
- 2730485921,
1299
- 2820302411,
1300
- 3259730800,
1301
- 3345764771,
1302
- 3516065817,
1303
- 3600352804,
1304
- 4094571909,
1305
- 275423344,
1306
- 430227734,
1307
- 506948616,
1308
- 659060556,
1309
- 883997877,
1310
- 958139571,
1311
- 1322822218,
1312
- 1537002063,
1313
- 1747873779,
1314
- 1955562222,
1315
- 2024104815,
1316
- 2227730452,
1317
- 2361852424,
1318
- 2428436474,
1319
- 2756734187,
1320
- 3204031479,
1321
- 3329325298
1322
- ]);
1323
- function rotr32(value, bits) {
1324
- return value >>> bits | value << 32 - bits;
1325
- }
1326
- function sha256Utf8Hex(input) {
1327
- const bytes = new TextEncoder().encode(input);
1328
- const totalLen = Math.ceil((bytes.length + 9) / 64) * 64;
1329
- const padded = new Uint8Array(totalLen);
1330
- padded.set(bytes);
1331
- padded[bytes.length] = 128;
1332
- const view = new DataView(padded.buffer);
1333
- view.setUint32(totalLen - 8, Math.floor(bytes.length / 536870912), false);
1334
- view.setUint32(totalLen - 4, bytes.length << 3 >>> 0, false);
1335
- let h0 = 1779033703;
1336
- let h1 = 3144134277;
1337
- let h2 = 1013904242;
1338
- let h3 = 2773480762;
1339
- let h4 = 1359893119;
1340
- let h5 = 2600822924;
1341
- let h6 = 528734635;
1342
- let h7 = 1541459225;
1343
- const w = new Uint32Array(64);
1344
- for (let offset = 0; offset < totalLen; offset += 64) {
1345
- for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(offset + i * 4, false);
1346
- for (let i = 16; i < 64; i += 1) {
1347
- const w15 = w[i - 15];
1348
- const w2 = w[i - 2];
1349
- const s0 = rotr32(w15, 7) ^ rotr32(w15, 18) ^ w15 >>> 3;
1350
- const s1 = rotr32(w2, 17) ^ rotr32(w2, 19) ^ w2 >>> 10;
1351
- w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
1352
- }
1353
- let a = h0;
1354
- let b = h1;
1355
- let c = h2;
1356
- let d = h3;
1357
- let e = h4;
1358
- let f = h5;
1359
- let g = h6;
1360
- let h = h7;
1361
- for (let i = 0; i < 64; i += 1) {
1362
- const s1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25);
1363
- const ch = e & f ^ ~e & g;
1364
- const temp1 = h + s1 + ch + SHA256_K[i] + w[i] >>> 0;
1365
- const temp2 = (rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
1366
- h = g;
1367
- g = f;
1368
- f = e;
1369
- e = d + temp1 >>> 0;
1370
- d = c;
1371
- c = b;
1372
- b = a;
1373
- a = temp1 + temp2 >>> 0;
1374
- }
1375
- h0 = h0 + a >>> 0;
1376
- h1 = h1 + b >>> 0;
1377
- h2 = h2 + c >>> 0;
1378
- h3 = h3 + d >>> 0;
1379
- h4 = h4 + e >>> 0;
1380
- h5 = h5 + f >>> 0;
1381
- h6 = h6 + g >>> 0;
1382
- h7 = h7 + h >>> 0;
1383
- }
1384
- return [
1385
- h0,
1386
- h1,
1387
- h2,
1388
- h3,
1389
- h4,
1390
- h5,
1391
- h6,
1392
- h7
1393
- ].map((word) => (word >>> 0).toString(16).padStart(8, "0")).join("");
1394
- }
1395
- function wsAuthFromProvider(provider) {
1396
- if (provider == null) return void 0;
1397
- if (typeof provider === "string") {
1398
- const token = requireToken(provider);
1399
- const bridged2 = () => token;
1400
- stringAuthPoolKeys.set(bridged2, `token-sha256:${sha256Utf8Hex(token)}`);
1401
- return bridged2;
1402
- }
1403
- let bridged = bridgedFunctionAuth.get(provider);
1404
- if (bridged == null) {
1405
- let lastToken;
1406
- bridged = async ({ reason }) => {
1407
- const refresh = () => provider({
1408
- reason: "unauthorized",
1409
- status: 401,
1410
- previousToken: lastToken
1411
- });
1412
- let token = requireToken(await (reason === "reauth" ? refresh() : provider({ reason: "request" })) ?? void 0);
1413
- if (reason === "renew" && token === lastToken) token = requireToken(await refresh() ?? void 0);
1414
- lastToken = token;
1415
- return token;
1416
- };
1417
- bridgedFunctionAuth.set(provider, bridged);
1418
- }
1419
- return bridged;
1420
- }
1421
- function requireToken(token) {
1422
- const trimmed = token?.trim();
1423
- if (trimmed == null || trimmed.length === 0) throw new Error("WebSocket transport requires a token");
1424
- return trimmed;
1257
+ function wsAuthFromProvider$1(provider) {
1258
+ return wsAuthFromProvider(provider);
1425
1259
  }
1426
- const poolIds = /* @__PURE__ */ new WeakMap();
1427
- let nextPoolId = 0;
1428
1260
  function poolKeyFor(options, auth) {
1429
- if (options.authPoolKey != null) return `key:${options.authPoolKey}`;
1430
- if (auth == null) return "anonymous";
1431
- const tokenKey = stringAuthPoolKeys.get(auth);
1432
- if (tokenKey != null) return tokenKey;
1433
- let id = poolIds.get(auth);
1434
- if (id == null) {
1435
- id = ++nextPoolId;
1436
- poolIds.set(auth, id);
1437
- }
1438
- return `auth:${id}`;
1261
+ return deriveWsAuthPoolKey(options, auth);
1439
1262
  }
1440
1263
  const httpFallbacks = /* @__PURE__ */ new WeakMap();
1441
1264
  const dispatchHttpFallback = (request) => {
@@ -1473,6 +1296,7 @@ var WsRoomTransport = class WsRoomTransport2 {
1473
1296
  auth;
1474
1297
  lease;
1475
1298
  readDisabled = false;
1299
+ readCooldownUntil;
1476
1300
  writeDisabled = false;
1477
1301
  constructor(init2) {
1478
1302
  this.options = init2.options;
@@ -1507,22 +1331,43 @@ var WsRoomTransport = class WsRoomTransport2 {
1507
1331
  });
1508
1332
  }
1509
1333
  get readsAvailable() {
1510
- return !this.readDisabled;
1334
+ if (this.readDisabled) return false;
1335
+ if (this.readCooldownUntil != null) {
1336
+ if (Date.now() < this.readCooldownUntil) return false;
1337
+ this.readCooldownUntil = void 0;
1338
+ }
1339
+ return true;
1511
1340
  }
1512
1341
  get writesAvailable() {
1513
1342
  return !this.writeDisabled;
1514
1343
  }
1515
- disableReads() {
1516
- this.readDisabled = true;
1344
+ get isMultiplexerReady() {
1345
+ return (this.lease?.multiplexer ?? this.options.multiplexer)?.state === "ready";
1346
+ }
1347
+ get isMultiplexerUnavailable() {
1517
1348
  const state = this.lease?.multiplexer.state ?? this.options.multiplexer?.state;
1518
- if (state != null && [
1349
+ return state != null && [
1519
1350
  "closed",
1520
1351
  "unsupported",
1521
1352
  "terminated"
1522
- ].includes(state)) this.writeDisabled = true;
1353
+ ].includes(state);
1354
+ }
1355
+ disableReads(reason) {
1356
+ const state = this.lease?.multiplexer.state ?? this.options.multiplexer?.state;
1357
+ const muxUnavailable = state != null && [
1358
+ "closed",
1359
+ "unsupported",
1360
+ "terminated"
1361
+ ].includes(state);
1362
+ if (reason == null || reason === "unsupported_content_type" || muxUnavailable) {
1363
+ this.readDisabled = true;
1364
+ this.readCooldownUntil = void 0;
1365
+ } else this.readCooldownUntil = Date.now() + WS_READ_COOLDOWN_MS;
1366
+ if (muxUnavailable) this.writeDisabled = true;
1523
1367
  if (this.writeDisabled) this.release();
1524
1368
  }
1525
1369
  reconnect() {
1370
+ this.readCooldownUntil = void 0;
1526
1371
  this.lease?.multiplexer.reconnect();
1527
1372
  this.options.multiplexer?.reconnect();
1528
1373
  }
@@ -1530,13 +1375,16 @@ var WsRoomTransport = class WsRoomTransport2 {
1530
1375
  if (this.options.multiplexer != null) return this.options.multiplexer;
1531
1376
  if (this.lease == null) this.lease = acquireDurableWsMultiplexer({
1532
1377
  url: this.url,
1533
- authPoolKey: `streams-crdt\0${poolKeyFor(this.options, this.auth)}`,
1378
+ authPoolKey: poolKeyFor(this.options, this.auth),
1534
1379
  ...this.auth != null && { auth: this.auth },
1535
1380
  ...this.options.authMode != null && { authMode: this.options.authMode },
1536
1381
  ...this.options.webSocketFactory != null && { webSocketFactory: this.options.webSocketFactory },
1537
1382
  ...this.fetchImpl != null && { fetch: this.fetchImpl },
1538
1383
  ...this.options.probe != null && { probe: this.options.probe },
1539
- ...this.options.onEvent != null && { onEvent: this.options.onEvent },
1384
+ onEvent: (event) => {
1385
+ if (event.type === "ready") this.readCooldownUntil = void 0;
1386
+ this.options.onEvent?.(event);
1387
+ },
1540
1388
  httpAppend: dispatchHttpFallback,
1541
1389
  httpEphemeralPublish: dispatchHttpFallback
1542
1390
  });
@@ -1564,21 +1412,22 @@ var WsRoomTransport = class WsRoomTransport2 {
1564
1412
  return supported;
1565
1413
  }
1566
1414
  /** Live durable read from an HTTP offset token; `undefined` keeps HTTP SSE. */
1567
- openDurable(offset) {
1415
+ openDurable(offset, options) {
1568
1416
  const joinAt = joinOffsetFor(offset);
1569
- if (joinAt == null || this.readDisabled) {
1417
+ if (joinAt == null) {
1570
1418
  this.readDisabled = true;
1571
1419
  return;
1572
1420
  }
1421
+ if (!this.readsAvailable) return;
1573
1422
  try {
1574
- return new WsDurableSession(this.multiplexer(), this.streamId, joinAt);
1423
+ return new WsDurableSession(this.multiplexer(), this.streamId, joinAt, options);
1575
1424
  } catch {
1576
1425
  this.readDisabled = true;
1577
1426
  return;
1578
1427
  }
1579
1428
  }
1580
1429
  openEphemeral() {
1581
- if (this.channel == null || this.readDisabled) return void 0;
1430
+ if (this.channel == null || !this.readsAvailable) return void 0;
1582
1431
  try {
1583
1432
  return new WsEphemeralSession(this.multiplexer(), this.streamId, this.channel);
1584
1433
  } catch {
@@ -1619,7 +1468,8 @@ var WsRoomTransport = class WsRoomTransport2 {
1619
1468
  };
1620
1469
  return {
1621
1470
  kind: "ack",
1622
- nextOffset: formatWsOffset(result.nextOffset)
1471
+ nextOffset: formatWsOffset(result.nextOffset),
1472
+ ...result.prevOffset != null && { prevOffset: formatWsOffset(result.prevOffset) }
1623
1473
  };
1624
1474
  } catch (error) {
1625
1475
  if (!(error instanceof DsWsError)) return {
@@ -1707,6 +1557,41 @@ var EventQueue = class {
1707
1557
  return this.items.splice(0);
1708
1558
  }
1709
1559
  };
1560
+ function toOpenInfo(info) {
1561
+ return {
1562
+ startOffset: formatWsOffset(info.startOffset),
1563
+ ...info.tailOffset != null && { tailOffset: formatWsOffset(info.tailOffset) },
1564
+ ...info.snapshotOffset != null && { snapshotOffset: formatWsOffset(info.snapshotOffset) },
1565
+ ...info.snapshotBytes != null && { snapshotBytes: info.snapshotBytes },
1566
+ streamClosed: info.streamClosed,
1567
+ contentType: info.contentType,
1568
+ v11: info.v11
1569
+ };
1570
+ }
1571
+ function decideWsInitialSync(info, options) {
1572
+ if (!info.v11 || info.tailOffset == null) return { kind: options.hasNumericCursor ? "catchup" : "bootstrap" };
1573
+ let start;
1574
+ let tail;
1575
+ try {
1576
+ start = parseWsOffset(info.startOffset);
1577
+ tail = parseWsOffset(info.tailOffset);
1578
+ } catch {
1579
+ return { kind: options.hasNumericCursor ? "catchup" : "bootstrap" };
1580
+ }
1581
+ const lag = tail > start ? tail - start : 0n;
1582
+ if (!options.hasNumericCursor) return tail === 0n && !options.incompleteRecoveryActive ? { kind: "inline" } : { kind: "bootstrap" };
1583
+ if (options.incompleteRecoveryActive) return { kind: "catchup" };
1584
+ if (lag <= (options.maxInlineBytes ?? 65536n)) return { kind: "inline" };
1585
+ if (info.snapshotOffset != null && info.snapshotBytes != null) try {
1586
+ const snap = parseWsOffset(info.snapshotOffset);
1587
+ const suffix = tail > snap ? tail - snap : 0n;
1588
+ const validProtected = !options.protectedBootstrap || info.snapshotBytes > 0n;
1589
+ if (snap > start && validProtected && info.snapshotBytes + suffix < lag) return { kind: "bootstrap" };
1590
+ } catch {
1591
+ return { kind: "catchup" };
1592
+ }
1593
+ return { kind: "catchup" };
1594
+ }
1710
1595
  const sessionClosed = () => new DsWsError("closed", "session closed", {
1711
1596
  source: "local",
1712
1597
  operation: "handler",
@@ -1718,9 +1603,12 @@ var WsDurableSession = class {
1718
1603
  sub;
1719
1604
  buffered = [];
1720
1605
  closed = false;
1721
- constructor(mux, stream, offset) {
1606
+ epoch = 0;
1607
+ constructor(mux, stream, offset, options) {
1722
1608
  this.sub = mux.joinDurable(stream, offset, {
1723
1609
  onJoined: (info) => {
1610
+ if (this.closed) return;
1611
+ this.epoch += 1;
1724
1612
  this.buffered = [];
1725
1613
  if (info.contentType !== "application/octet-stream") {
1726
1614
  this.queue.push({
@@ -1729,15 +1617,21 @@ var WsDurableSession = class {
1729
1617
  });
1730
1618
  return;
1731
1619
  }
1732
- this.queue.push({ type: "open" });
1620
+ this.queue.push({
1621
+ type: "open",
1622
+ info: toOpenInfo(info)
1623
+ });
1733
1624
  },
1734
1625
  onData: (event) => {
1626
+ if (this.closed) return;
1735
1627
  for (const message of event.messages) this.buffered.push(message);
1736
1628
  },
1737
1629
  onCheckpoint: (event) => {
1630
+ if (this.closed) return Promise.reject(sessionClosed());
1631
+ const epoch = this.epoch;
1738
1632
  const messages = this.buffered;
1739
1633
  this.buffered = [];
1740
- return this.settled((settle) => ({
1634
+ return this.settled(epoch, (settle) => ({
1741
1635
  type: "page",
1742
1636
  updates: messages.flatMap((message) => decodeMultipartPartItems(message)),
1743
1637
  nextOffset: formatWsOffset(event.offset),
@@ -1746,8 +1640,10 @@ var WsDurableSession = class {
1746
1640
  }));
1747
1641
  },
1748
1642
  catchupViaHttp: () => {
1643
+ if (this.closed) return Promise.reject(sessionClosed());
1644
+ const epoch = this.epoch;
1749
1645
  this.buffered = [];
1750
- return this.settled((settle) => ({
1646
+ return this.settled(epoch, (settle) => ({
1751
1647
  type: "catchup",
1752
1648
  ...settle
1753
1649
  })).then((offset2) => {
@@ -1757,6 +1653,7 @@ var WsDurableSession = class {
1757
1653
  });
1758
1654
  },
1759
1655
  onDisconnect: () => {
1656
+ this.epoch += 1;
1760
1657
  this.buffered = [];
1761
1658
  if (!this.closed) this.queue.push({
1762
1659
  type: "error",
@@ -1767,25 +1664,38 @@ var WsDurableSession = class {
1767
1664
  })
1768
1665
  });
1769
1666
  },
1770
- onFallback: (event) => this.queue.push({
1771
- type: "fallback",
1772
- reason: event.reason
1773
- }),
1774
- onEnd: () => this.queue.push({ type: "end" }),
1775
- onError: (error) => this.queue.push({
1776
- type: "error",
1777
- error
1778
- })
1779
- });
1667
+ onFallback: (event) => {
1668
+ if (!this.closed) this.queue.push({
1669
+ type: "fallback",
1670
+ reason: event.reason
1671
+ });
1672
+ },
1673
+ onEnd: () => {
1674
+ if (!this.closed) this.queue.push({ type: "end" });
1675
+ },
1676
+ onError: (error) => {
1677
+ if (!this.closed) this.queue.push({
1678
+ type: "error",
1679
+ error
1680
+ });
1681
+ }
1682
+ }, options);
1780
1683
  }
1781
- settled(make2) {
1782
- if (this.closed) return Promise.reject(sessionClosed());
1684
+ get isClosed() {
1685
+ return this.closed;
1686
+ }
1687
+ settled(epoch, make2) {
1688
+ if (this.closed || epoch !== this.epoch) return Promise.reject(sessionClosed());
1783
1689
  return new Promise((resolve, reject) => {
1784
1690
  const entry = { reject };
1785
1691
  this.pending.add(entry);
1786
1692
  this.queue.push(make2({
1787
1693
  resolve: (value) => {
1788
1694
  this.pending.delete(entry);
1695
+ if (this.closed || epoch !== this.epoch) {
1696
+ reject(sessionClosed());
1697
+ return;
1698
+ }
1789
1699
  resolve(value);
1790
1700
  },
1791
1701
  reject: (error) => {
@@ -1801,6 +1711,7 @@ var WsDurableSession = class {
1801
1711
  close() {
1802
1712
  if (this.closed) return;
1803
1713
  this.closed = true;
1714
+ this.epoch += 1;
1804
1715
  this.sub.leave().catch(() => {
1805
1716
  });
1806
1717
  for (const entry of [...this.pending]) entry.reject(sessionClosed());
@@ -2254,7 +2165,7 @@ const makeEphemeralStream = fnUntraced(function* (options) {
2254
2165
  if (!(yield* promise(() => room.probe()))) return;
2255
2166
  const session = room.openEphemeral();
2256
2167
  if (session == null) {
2257
- room.disableReads();
2168
+ if (room.readsAvailable) room.disableReads("ws_unavailable");
2258
2169
  return;
2259
2170
  }
2260
2171
  yield* gen(function* () {
@@ -2262,7 +2173,7 @@ const makeEphemeralStream = fnUntraced(function* (options) {
2262
2173
  const event = yield* promise(() => session.next());
2263
2174
  if (event.type === "open") continue;
2264
2175
  if (event.type === "fallback") {
2265
- room.disableReads();
2176
+ room.disableReads(event.reason);
2266
2177
  return;
2267
2178
  }
2268
2179
  if (event.type === "error") {
@@ -3153,7 +3064,7 @@ var EphemeralStreamCrdtLegacy = class {
3153
3064
  },
3154
3065
  webSocket: options.webSocket && {
3155
3066
  ...options.webSocket,
3156
- ...options.webSocket.auth == null && options.auth != null && { auth: wsAuthFromProvider(options.auth) }
3067
+ ...options.webSocket.auth == null && options.auth != null && { auth: wsAuthFromProvider$1(options.auth) }
3157
3068
  }
3158
3069
  };
3159
3070
  this.streamUrl = snapshot.streamUrl;
@@ -3433,6 +3344,9 @@ var StreamsTransportClient = class {
3433
3344
  get wsLiveReadsAvailable() {
3434
3345
  return this.webSocket?.readsAvailable === true;
3435
3346
  }
3347
+ get isWsMultiplexerUnavailable() {
3348
+ return this.webSocket?.isMultiplexerUnavailable === true;
3349
+ }
3436
3350
  reconnectWebSocket() {
3437
3351
  this.webSocket?.reconnect();
3438
3352
  }
@@ -3440,23 +3354,45 @@ var StreamsTransportClient = class {
3440
3354
  releaseWebSocket() {
3441
3355
  this.webSocket?.release();
3442
3356
  }
3357
+ disableWsReads(reason) {
3358
+ this.webSocket?.disableReads(reason);
3359
+ }
3360
+ async openWsDurableSession(offset, options, signal) {
3361
+ const ws = this.webSocket;
3362
+ if (ws == null || !ws.readsAvailable) return void 0;
3363
+ if (signal?.aborted) return void 0;
3364
+ if (!await ws.probe()) return void 0;
3365
+ if (signal?.aborted) return void 0;
3366
+ return ws.openDurable(offset, options);
3367
+ }
3443
3368
  /**
3444
- * Live read over `loro-ds-v1` with the SSE page contract of
3369
+ * Live read over `loro-ds-v1` / `loro-ds-v1.1` with the SSE page contract of
3445
3370
  * `readFromOffsetSseItems`: `onControl` runs once per CHECKPOINT with the
3446
3371
  * items of that page (never for unconfirmed `DATA`), so the caller's cursor
3447
3372
  * and pending-import logic are unchanged. `catchup` performs the
3448
3373
  * `CATCHUP_REQUIRED` HTTP catch-up and resolves with the offset reached.
3449
3374
  * Resolves `ws-fallback` whenever the room should continue over HTTP SSE.
3450
3375
  */
3451
- async readFromOffsetWsItems(offset, cursor, onControl, onOpen, signal, catchup) {
3376
+ async readFromOffsetWsItems(offset, cursor, onControl, onOpen, signal, catchup, options) {
3452
3377
  const ws = this.webSocket;
3453
- if (ws == null || !ws.readsAvailable) return { kind: "ws-fallback" };
3378
+ if (ws == null || !ws.readsAvailable) {
3379
+ options?.session?.close();
3380
+ return { kind: "ws-fallback" };
3381
+ }
3454
3382
  const abortReason = () => signal?.reason ?? new DOMException("The operation was aborted.", "AbortError");
3455
- if (signal?.aborted) throw abortReason();
3456
- if (!await ws.probe()) return { kind: "ws-fallback" };
3457
- if (signal?.aborted) throw abortReason();
3458
- const session = ws.openDurable(offset);
3383
+ if (signal?.aborted) {
3384
+ options?.session?.close();
3385
+ throw abortReason();
3386
+ }
3387
+ let session = options?.session != null && !options.session.isClosed ? options.session : void 0;
3388
+ const reusedOpenSession = session != null;
3389
+ if (session == null) {
3390
+ if (!await ws.probe()) return { kind: "ws-fallback" };
3391
+ if (signal?.aborted) throw abortReason();
3392
+ session = ws.openDurable(offset);
3393
+ }
3459
3394
  if (session == null) return { kind: "ws-fallback" };
3395
+ if (reusedOpenSession) onOpen?.();
3460
3396
  let abortHandler;
3461
3397
  const aborted = new Promise((_, reject) => {
3462
3398
  abortHandler = () => reject(abortReason());
@@ -3470,13 +3406,15 @@ var StreamsTransportClient = class {
3470
3406
  const event = await Promise.race([session.next(), aborted]);
3471
3407
  switch (event.type) {
3472
3408
  case "open":
3409
+ options?.onOpenInfo?.(event.info);
3473
3410
  onOpen?.();
3474
3411
  continue;
3475
3412
  case "page": {
3476
3413
  let result;
3477
3414
  try {
3478
3415
  if (signal?.aborted) throw abortReason();
3479
- result = await onControl(event.updates, event.nextOffset, event.upToDate, void 0);
3416
+ result = await Promise.race([Promise.resolve(onControl(event.updates, event.nextOffset, event.upToDate, void 0)), aborted]);
3417
+ if (signal?.aborted) throw abortReason();
3480
3418
  } catch (error) {
3481
3419
  event.reject(error);
3482
3420
  throw error;
@@ -3509,7 +3447,7 @@ var StreamsTransportClient = class {
3509
3447
  latestCursor: cursor
3510
3448
  };
3511
3449
  case "fallback":
3512
- ws.disableReads();
3450
+ ws.disableReads(event.reason);
3513
3451
  return { kind: "ws-fallback" };
3514
3452
  case "error": {
3515
3453
  const classified = classifyWsReadError(event.error);
@@ -3652,7 +3590,8 @@ var StreamsTransportClient = class {
3652
3590
  kind: "ok",
3653
3591
  ackEpoch: producerSession.producerEpoch,
3654
3592
  ackSeq: producerSession.nextProducerSeq,
3655
- nextOffset: outcome2.nextOffset
3593
+ nextOffset: outcome2.nextOffset,
3594
+ ...outcome2.prevOffset != null && { prevOffset: outcome2.prevOffset }
3656
3595
  };
3657
3596
  case "seq-gap":
3658
3597
  return {
@@ -4264,6 +4203,12 @@ var TransportSnapshotManager = class {
4264
4203
  return;
4265
4204
  }
4266
4205
  if (this.getRunnableConfig(state) == null) return;
4206
+ if (this.knownSnapshotOffset != null) {
4207
+ const knownBytes = parseSnapshotByteOffset(this.knownSnapshotOffset);
4208
+ const tailBytes = parseSnapshotByteOffset(state.cursor.nextOffset);
4209
+ const minBytes = readTriggered ? config.maxBytesSinceRemoteSnapshot : config.minBytesSinceRemoteSnapshot;
4210
+ if (tailBytes == null || knownBytes == null || minBytes == null || tailBytes <= knownBytes || tailBytes - knownBytes < minBytes) return;
4211
+ }
4267
4212
  const remoteSnapshotOffset = await observe("head", () => this.readSnapshotOffsetValue(requestDiagnostics("head")));
4268
4213
  this.noteSnapshot(remoteSnapshotOffset);
4269
4214
  const snapshotBytes = parseSnapshotByteOffset(remoteSnapshotOffset);
@@ -4386,11 +4331,16 @@ function createJoinState(cursor, liveMode = "sse") {
4386
4331
  snapshot: createTransportSnapshotState(),
4387
4332
  started: Promise.resolve(),
4388
4333
  syncWaiters: [],
4389
- initialSyncFailed: false
4334
+ initialSyncFailed: false,
4335
+ wsLiveHealthy: false
4390
4336
  };
4391
4337
  }
4392
4338
  async function disposeJoinState(state, options) {
4393
4339
  state.closed = true;
4340
+ state.wsLiveHealthy = false;
4341
+ const handedOffWsSession = state.handedOffWsSession;
4342
+ state.handedOffWsSession = void 0;
4343
+ handedOffWsSession?.close();
4394
4344
  options.snapshotManager.dispose(state);
4395
4345
  if (state.readRestartTimer != null) {
4396
4346
  clearTimeout(state.readRestartTimer);
@@ -4434,6 +4384,7 @@ var StreamsCrdt = class StreamsCrdt2 {
4434
4384
  adapter;
4435
4385
  remoteCursorStore;
4436
4386
  createStreamIfMissing;
4387
+ streamTtlSeconds;
4437
4388
  protectedBootstrap;
4438
4389
  client;
4439
4390
  persistentRecovery;
@@ -4487,6 +4438,8 @@ var StreamsCrdt = class StreamsCrdt2 {
4487
4438
  writeOnlyDisabledReason;
4488
4439
  joinState;
4489
4440
  opQueue = Promise.resolve();
4441
+ syncInvocationSeq = 0;
4442
+ lastLinearizedSyncSeq = 0;
4490
4443
  /** Wall-clock ms of the last durably committed local append, if any. */
4491
4444
  lastLocalAppendAtMs;
4492
4445
  writeBlocked = false;
@@ -4494,6 +4447,12 @@ var StreamsCrdt = class StreamsCrdt2 {
4494
4447
  spaceFencedError;
4495
4448
  streamObserved = false;
4496
4449
  snapshotSuppressedForToken = null;
4450
+ knownRecoveryMetadata;
4451
+ noteWsOpenInfo(info) {
4452
+ this.streamObserved = true;
4453
+ if (info.v11) this.snapshotManager.noteSnapshot(info.snapshotOffset ?? "-1");
4454
+ else if (info.snapshotOffset != null) this.snapshotManager.noteSnapshot(info.snapshotOffset);
4455
+ }
4497
4456
  /**
4498
4457
  * Internal catch-up result used when callers need to handle 410 by
4499
4458
  * preserving local state before rebuilding through bootstrap.
@@ -4545,6 +4504,7 @@ var StreamsCrdt = class StreamsCrdt2 {
4545
4504
  this.streamObserved = this.incompleteRecovery.active || this.incompleteReadCursor != null;
4546
4505
  const authProvider = normalizeAuthProvider(options.auth);
4547
4506
  this.createStreamIfMissing = options.createStreamIfMissing ?? false;
4507
+ this.streamTtlSeconds = options.streamTtlSeconds;
4548
4508
  const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
4549
4509
  this.remoteCursorStore = options.remoteCursorStore ?? new InMemoryRemoteCursorStore();
4550
4510
  this.reconnectConfig = {
@@ -4581,7 +4541,7 @@ var StreamsCrdt = class StreamsCrdt2 {
4581
4541
  options: options.webSocket,
4582
4542
  streamUrl: this.streamUrl,
4583
4543
  fetch: fetchImpl,
4584
- auth: options.webSocket.auth ?? wsAuthFromProvider(options.auth)
4544
+ auth: options.webSocket.auth ?? wsAuthFromProvider$1(options.auth)
4585
4545
  }) : void 0
4586
4546
  });
4587
4547
  this.cursorManager = this.createCursorManager(this.adapter, (cursor, source) => this.saveRemoteCursor(cursor, source));
@@ -4912,9 +4872,10 @@ var StreamsCrdt = class StreamsCrdt2 {
4912
4872
  };
4913
4873
  try {
4914
4874
  this.disableWriteOnlyMode("appendWriteOnly cannot be used after sync() on the same transport");
4875
+ const syncSeq = ++this.syncInvocationSeq;
4915
4876
  return {
4916
4877
  ok: true,
4917
- value: { cursor: await this.syncOnce("sync") }
4878
+ value: { cursor: await this.syncOnce("sync", void 0, syncSeq) }
4918
4879
  };
4919
4880
  } catch (error) {
4920
4881
  if (error instanceof LocalAppendFailedError) return {
@@ -5274,18 +5235,32 @@ var StreamsCrdt = class StreamsCrdt2 {
5274
5235
  state.cursor = joined.cursor;
5275
5236
  state.streamCursor = joined.streamCursor;
5276
5237
  state.liveMode = joined.liveMode;
5238
+ state.handedOffWsSession = joined.handedOffWsSession;
5239
+ state.wsLiveHealthy = joined.wsLiveHealthy === true;
5277
5240
  if (joined.writeBlockedError != null) state.lastWriteError = joined.writeBlockedError;
5278
5241
  this.deferredInitialBacklog = this.incompleteProgress.uploadBaseline == null;
5279
5242
  const pendingLocal = this.deferredInitialBacklog ? { nextRefVersion: joined.localExportRefVersion } : this.exportUpdates(joined.localExportRefVersion);
5280
5243
  const hasQueuedPreSubscribeBatch = pendingLocal.batch != null;
5281
5244
  if (pendingLocal.batch != null) state.pendingLocal.pushBack(pendingLocal.batch);
5282
- if (state.closed) return;
5245
+ if (state.closed) {
5246
+ const leftover = state.handedOffWsSession;
5247
+ state.handedOffWsSession = void 0;
5248
+ leftover?.close();
5249
+ state.wsLiveHealthy = false;
5250
+ return;
5251
+ }
5283
5252
  state.localQueueReady = true;
5284
5253
  if (hasQueuedPreSubscribeBatch && !this.writeBlocked) {
5285
5254
  await this.flushPendingLocal(state);
5286
5255
  if (state.writeSubStatus === "error" || state.readSubStatus === "error" || state.readSubStatus === "disconnected") throw new Error("join local sync failed before subscription became ready");
5287
5256
  }
5288
- if (state.closed) return;
5257
+ if (state.closed) {
5258
+ const leftover = state.handedOffWsSession;
5259
+ state.handedOffWsSession = void 0;
5260
+ leftover?.close();
5261
+ state.wsLiveHealthy = false;
5262
+ return;
5263
+ }
5289
5264
  state.lastError = state.persistenceError ?? (this.writeBlocked ? state.lastWriteError : void 0);
5290
5265
  this.setReadSubStatus(state, "ok");
5291
5266
  this.setWriteSubStatus(state, "ok");
@@ -5298,6 +5273,10 @@ var StreamsCrdt = class StreamsCrdt2 {
5298
5273
  unsubscribe?.();
5299
5274
  }
5300
5275
  if (state.closed) return;
5276
+ const leftover = state.handedOffWsSession;
5277
+ state.handedOffWsSession = void 0;
5278
+ leftover?.close();
5279
+ state.wsLiveHealthy = false;
5301
5280
  this.snapshotManager.dispose(state);
5302
5281
  state.lastError = this.checkOrLatchSpaceFence(error, "join") ?? toTransportError(error, "join");
5303
5282
  state.initialSyncFailed = this.spaceFencedError == null;
@@ -5417,13 +5396,13 @@ var StreamsCrdt = class StreamsCrdt2 {
5417
5396
  return false;
5418
5397
  }
5419
5398
  }
5420
- async syncOnce(operation, parentSignal) {
5399
+ async syncOnce(operation, parentSignal, syncSeq) {
5421
5400
  const execute = () => this.enqueueExclusive(async () => {
5422
5401
  await atErrorBoundary({
5423
5402
  source: "crdt",
5424
5403
  stage: "crdt_export"
5425
5404
  }, () => this.adapter.flushLocalExports?.());
5426
- return this.syncOnceExclusive(operation, parentSignal);
5405
+ return this.syncOnceExclusive(operation, parentSignal, syncSeq);
5427
5406
  });
5428
5407
  try {
5429
5408
  const cursor = await execute();
@@ -5450,9 +5429,13 @@ var StreamsCrdt = class StreamsCrdt2 {
5450
5429
  }
5451
5430
  }
5452
5431
  /** Caller owns opQueue; never wait for the background flush from here. */
5453
- async syncOnceExclusive(operation, parentSignal) {
5432
+ async syncOnceExclusive(operation, parentSignal, syncSeq) {
5454
5433
  const state = this.joinState;
5455
- if (state != null && !state.closed) while (!state.closed && !this.writeBlocked && !this.deferredInitialBacklog && state.pendingLocal.length > 0) await this.flushPendingLocalBatchExclusive(state);
5434
+ let didLinearizePending = false;
5435
+ if (state != null && !state.closed) while (!state.closed && !this.writeBlocked && !this.deferredInitialBacklog && state.pendingLocal.length > 0) {
5436
+ const hadCompleteCursor = this.cursorManager.isCursorComplete(state.cursor);
5437
+ if (await this.flushPendingLocalBatchExclusive(state) && hadCompleteCursor && this.cursorManager.isCursorComplete(state.cursor)) didLinearizePending = true;
5438
+ }
5456
5439
  if ((state == null || state.closed) && this.frozenLocalAppend?.source === "pending" && !this.writeBlocked) {
5457
5440
  const frozen = this.frozenLocalAppend;
5458
5441
  const appended = await this.appendFrozenLocalBatchRemote(frozen);
@@ -5460,18 +5443,27 @@ var StreamsCrdt = class StreamsCrdt2 {
5460
5443
  this.commitProducerAck(appended.producerAck);
5461
5444
  }
5462
5445
  if (this.writeBlocked && this.frozenLocalAppend?.source === "direct" && this.frozenLocalAppend.acknowledged == null) this.abandonFrozenLocalAppend(this.frozenLocalAppend);
5463
- const initial = await this.finalizeDirectLocalAppendIfNeeded(await this.resolveInitialRemoteState(operation, parentSignal));
5446
+ const wsEligibleForSkip = operation === "sync" && state != null && !state.closed && state.wsLiveHealthy === true && state.readSubStatus === "ok" && !state.initialSyncFailed && !state.awaitingInitialTail && state.persistenceError == null && !this.deferredInitialBacklog && !this.incompleteRecovery.active && !this.dependencyWaiting && this.frozenLocalAppend == null && this.cursorManager.isCursorComplete(state.cursor);
5447
+ const linearizedByThisSync = didLinearizePending || syncSeq != null && this.lastLinearizedSyncSeq >= syncSeq;
5448
+ const preExported = wsEligibleForSkip && !this.writeBlocked && !linearizedByThisSync ? this.exportUpdates(state.cursor.serverLowerBoundVersion) : void 0;
5449
+ const canSkipWsCatchup = wsEligibleForSkip && !state.closed && (linearizedByThisSync || preExported?.batch != null || await this.verifyWsTailCurrent(state.cursor.nextOffset, parentSignal)) && !state.closed;
5450
+ const initial = await this.finalizeDirectLocalAppendIfNeeded(canSkipWsCatchup ? {
5451
+ cursor: state.cursor,
5452
+ streamCursor: state.streamCursor,
5453
+ wsLiveHealthy: true
5454
+ } : await this.resolveInitialRemoteState(operation, parentSignal));
5464
5455
  let cursor = initial.cursor;
5456
+ let flushedAfterInitial = false;
5465
5457
  if (state != null && !state.closed) {
5466
5458
  state.cursor = cursor;
5467
5459
  state.streamCursor = initial.streamCursor;
5468
5460
  this.noteInitialTailReached(state);
5469
5461
  while (!state.closed && !this.writeBlocked && state.pendingLocal.length > 0) {
5470
- await this.flushPendingLocalBatchExclusive(state);
5462
+ if (await this.flushPendingLocalBatchExclusive(state)) flushedAfterInitial = true;
5471
5463
  cursor = state.cursor;
5472
5464
  }
5473
5465
  }
5474
- const localBatch = this.exportUpdates(cursor.serverLowerBoundVersion);
5466
+ const localBatch = !flushedAfterInitial && preExported?.batch != null && cursor === state?.cursor ? preExported : this.exportUpdates(cursor.serverLowerBoundVersion);
5475
5467
  if (this.writeBlocked && (localBatch.batch != null || state != null && !state.closed && state.pendingLocal.length > 0)) throw new LocalAppendFailedError(this.lastWriteBlockedError ?? state?.lastWriteError ?? {
5476
5468
  code: "insufficient_storage",
5477
5469
  status: 507,
@@ -5479,7 +5471,7 @@ var StreamsCrdt = class StreamsCrdt2 {
5479
5471
  message: "writes are blocked"
5480
5472
  });
5481
5473
  if (localBatch.batch != null) try {
5482
- const appended = await this.appendLocalBatchDurably(cursor, localBatch.batch);
5474
+ const appended = await this.appendLocalBatchDurably(cursor, localBatch.batch, void 0, "direct", state != null && !state.closed ? state.streamCursor : void 0, state != null && !state.closed && state.wsLiveHealthy === true);
5483
5475
  cursor = appended.cursor;
5484
5476
  if (state != null && !state.closed) {
5485
5477
  state.cursor = cursor;
@@ -5506,23 +5498,32 @@ var StreamsCrdt = class StreamsCrdt2 {
5506
5498
  let localExportRefVersion = cursor.serverLowerBoundVersion;
5507
5499
  let streamCursor = initial.streamCursor;
5508
5500
  const liveMode = preferredLiveMode;
5501
+ let handedOffWsSession = initial.handedOffWsSession;
5502
+ let wsLiveHealthy = initial.wsLiveHealthy;
5509
5503
  let writeBlockedError = this.writeBlocked ? this.lastWriteBlockedError : void 0;
5510
- if (!this.writeBlocked) {
5511
- const exportedLocal = this.exportUpdates(localExportRefVersion);
5512
- localExportRefVersion = exportedLocal.nextRefVersion;
5513
- const exportedBatch = exportedLocal.batch;
5514
- if (exportedBatch != null) try {
5515
- const committed = await this.appendLocalBatchDurably(cursor, exportedBatch, void 0, "direct", streamCursor);
5516
- cursor = committed.cursor;
5517
- streamCursor = committed.streamCursor;
5518
- } catch (error) {
5519
- if (!isWriteBlockedError(error)) throw error;
5520
- if (this.frozenLocalAppend?.source === "direct" && this.frozenLocalAppend.acknowledged == null) this.abandonFrozenLocalAppend(this.frozenLocalAppend);
5521
- const transportError = toTransportError(error, "upload");
5522
- this.writeBlocked = true;
5523
- this.lastWriteBlockedError = transportError;
5524
- writeBlockedError = transportError;
5504
+ try {
5505
+ if (!this.writeBlocked) {
5506
+ const exportedLocal = this.exportUpdates(localExportRefVersion);
5507
+ localExportRefVersion = exportedLocal.nextRefVersion;
5508
+ const exportedBatch = exportedLocal.batch;
5509
+ if (exportedBatch != null) try {
5510
+ const committed = await this.appendLocalBatchDurably(cursor, exportedBatch, void 0, "direct", streamCursor, wsLiveHealthy === true);
5511
+ cursor = committed.cursor;
5512
+ streamCursor = committed.streamCursor;
5513
+ } catch (error) {
5514
+ if (!isWriteBlockedError(error)) throw error;
5515
+ if (this.frozenLocalAppend?.source === "direct" && this.frozenLocalAppend.acknowledged == null) this.abandonFrozenLocalAppend(this.frozenLocalAppend);
5516
+ const transportError = toTransportError(error, "upload");
5517
+ this.writeBlocked = true;
5518
+ this.lastWriteBlockedError = transportError;
5519
+ writeBlockedError = transportError;
5520
+ }
5525
5521
  }
5522
+ } catch (error) {
5523
+ handedOffWsSession?.close();
5524
+ handedOffWsSession = void 0;
5525
+ wsLiveHealthy = false;
5526
+ throw error;
5526
5527
  }
5527
5528
  localExportRefVersion = cursor.serverLowerBoundVersion;
5528
5529
  return {
@@ -5530,6 +5531,8 @@ var StreamsCrdt = class StreamsCrdt2 {
5530
5531
  streamCursor,
5531
5532
  liveMode,
5532
5533
  localExportRefVersion,
5534
+ ...handedOffWsSession != null && { handedOffWsSession },
5535
+ ...wsLiveHealthy != null && { wsLiveHealthy },
5533
5536
  ...writeBlockedError !== void 0 && { writeBlockedError }
5534
5537
  };
5535
5538
  }
@@ -5554,19 +5557,40 @@ var StreamsCrdt = class StreamsCrdt2 {
5554
5557
  }
5555
5558
  const cursor = this.incompleteReadCursor ?? loaded ?? this.createInitialCursor();
5556
5559
  const runInitial = (task) => this.runInitialSyncWithDeadline(operation, task, parentSignal);
5557
- try {
5558
- if ((loaded == null || loaded.nextOffset === "-1") && this.incompleteReadCursor == null) return await runInitial((signal) => this.bootstrapState(cursor, {
5559
- reanchor: true,
5560
- signal,
5561
- timeoutMode: "initial"
5562
- }));
5563
- const caughtUp = await runInitial((signal) => this.catchupOrGone(cursor, {
5560
+ const runHttpInitial = async (current, knownMeta) => {
5561
+ if (current.nextOffset === "-1" && (loaded == null || loaded.nextOffset === "-1") && this.incompleteReadCursor == null) {
5562
+ this.knownRecoveryMetadata = knownMeta;
5563
+ try {
5564
+ return await runInitial((signal) => this.bootstrapState(current, {
5565
+ reanchor: true,
5566
+ signal,
5567
+ timeoutMode: "initial"
5568
+ }));
5569
+ } finally {
5570
+ this.knownRecoveryMetadata = void 0;
5571
+ }
5572
+ }
5573
+ const caughtUp = await runInitial((signal) => this.catchupOrGone(current, {
5564
5574
  goneStrategy: "return-gone",
5565
5575
  signal,
5566
5576
  timeoutMode: "initial"
5567
5577
  }));
5568
- if ("kind" in caughtUp) return await this.recoverFromGoneWithLocalBootstrap(cursor, operation, parentSignal);
5578
+ if ("kind" in caughtUp) {
5579
+ this.knownRecoveryMetadata = knownMeta;
5580
+ try {
5581
+ return await this.recoverFromGoneWithLocalBootstrap(current, operation, parentSignal);
5582
+ } finally {
5583
+ this.knownRecoveryMetadata = void 0;
5584
+ }
5585
+ }
5569
5586
  return caughtUp;
5587
+ };
5588
+ try {
5589
+ if (this.client.wsLiveReadsAvailable && !this.persistentRecovery.waiting(Date.now())) {
5590
+ const wsResult = await this.resolveInitialRemoteStateViaWs(cursor, operation, runInitial, runHttpInitial, parentSignal);
5591
+ if (wsResult != null) return wsResult;
5592
+ }
5593
+ return await runHttpInitial(cursor);
5570
5594
  } catch (error) {
5571
5595
  if (this.checkOrLatchSpaceFence(error, operation === "join" ? "join" : "sync") != null) throw error;
5572
5596
  if (!isStreamNotFoundError(error) || !this.canAutoCreateStream()) throw error;
@@ -5577,6 +5601,199 @@ var StreamsCrdt = class StreamsCrdt2 {
5577
5601
  }));
5578
5602
  }
5579
5603
  }
5604
+ async verifyWsTailCurrent(expectedOffset, parentSignal) {
5605
+ if (!this.client.wsLiveReadsAvailable) return false;
5606
+ try {
5607
+ return await this.runInitialSyncWithDeadline("sync", async (signal) => {
5608
+ const session = await this.client.openWsDurableSession(expectedOffset, { headOnly: true }, signal);
5609
+ if (session == null) return false;
5610
+ const abortReason = () => signal?.reason ?? new DOMException("The operation was aborted.", "AbortError");
5611
+ if (signal?.aborted) {
5612
+ session.close();
5613
+ throw abortReason();
5614
+ }
5615
+ let abortHandler;
5616
+ const aborted = new Promise((_, reject) => {
5617
+ abortHandler = () => reject(abortReason());
5618
+ signal?.addEventListener("abort", abortHandler, { once: true });
5619
+ });
5620
+ aborted.catch(() => {
5621
+ });
5622
+ try {
5623
+ const event = await Promise.race([session.next(), aborted]);
5624
+ if (event.type !== "open") return false;
5625
+ this.noteWsOpenInfo(event.info);
5626
+ return event.info.v11 && event.info.tailOffset === expectedOffset;
5627
+ } finally {
5628
+ if (abortHandler != null) signal?.removeEventListener("abort", abortHandler);
5629
+ session.close();
5630
+ }
5631
+ }, parentSignal);
5632
+ } catch (error) {
5633
+ if (parentSignal?.aborted) throw error;
5634
+ return false;
5635
+ }
5636
+ }
5637
+ async resolveInitialRemoteStateViaWs(initialCursor, operation, runInitial, runHttpInitial, parentSignal) {
5638
+ const hasNumericCursor = initialCursor.nextOffset !== "-1" && !this.incompleteRecovery.active && this.incompleteReadCursor == null;
5639
+ const incompleteActive = this.incompleteRecovery.active || !this.incompleteProgress.complete || this.incompleteReadCursor != null || atSyncErrorBoundary({
5640
+ source: "crdt",
5641
+ stage: "crdt_apply"
5642
+ }, () => this.adapter.getApplyState?.().complete === false);
5643
+ let current = initialCursor;
5644
+ let requestOffset = current.nextOffset;
5645
+ let handedOff = false;
5646
+ let session;
5647
+ let fallbackKnownMeta;
5648
+ let forceGone = false;
5649
+ let forceDecision;
5650
+ const joinOptions = {
5651
+ maxInlineBytes: DS_WS_INITIAL_MAX_INLINE_BYTES,
5652
+ ...this.canAutoCreateStream() && this.adapter.getCreateStreamHeaders == null && {
5653
+ createIfNotFound: true,
5654
+ ...this.streamTtlSeconds != null && { ttlSeconds: BigInt(this.streamTtlSeconds) }
5655
+ }
5656
+ };
5657
+ try {
5658
+ const inlineResult = await runInitial(async (signal) => {
5659
+ session = await this.client.openWsDurableSession(initialCursor.nextOffset, joinOptions, signal);
5660
+ if (session == null) return void 0;
5661
+ const abortReason = () => signal?.reason ?? new DOMException("The operation was aborted.", "AbortError");
5662
+ if (signal?.aborted) throw abortReason();
5663
+ let abortHandler;
5664
+ const aborted = new Promise((_, reject) => {
5665
+ abortHandler = () => reject(abortReason());
5666
+ signal?.addEventListener("abort", abortHandler, { once: true });
5667
+ });
5668
+ aborted.catch(() => {
5669
+ });
5670
+ let decidedInline = false;
5671
+ try {
5672
+ for (; ; ) {
5673
+ const event = await Promise.race([session.next(), aborted]);
5674
+ switch (event.type) {
5675
+ case "open":
5676
+ this.noteWsOpenInfo(event.info);
5677
+ fallbackKnownMeta = event.info.v11 && event.info.tailOffset != null ? {
5678
+ nextOffset: event.info.tailOffset,
5679
+ snapshotOffset: event.info.snapshotOffset ?? null
5680
+ } : void 0;
5681
+ if (!decidedInline) {
5682
+ const decision = decideWsInitialSync(event.info, {
5683
+ hasNumericCursor,
5684
+ incompleteRecoveryActive: incompleteActive,
5685
+ protectedBootstrap: this.protectedBootstrap
5686
+ });
5687
+ if (decision.kind !== "inline") {
5688
+ forceDecision = decision.kind;
5689
+ return;
5690
+ }
5691
+ decidedInline = true;
5692
+ }
5693
+ continue;
5694
+ case "page":
5695
+ try {
5696
+ if (signal?.aborted) throw abortReason();
5697
+ current = await this.cursorManager.applyLiveResult(current, requestOffset, {
5698
+ nextOffset: event.nextOffset,
5699
+ updates: event.updates,
5700
+ upToDate: event.upToDate
5701
+ });
5702
+ } catch (error) {
5703
+ event.reject(error);
5704
+ throw error;
5705
+ }
5706
+ event.resolve();
5707
+ requestOffset = current.nextOffset;
5708
+ if (event.upToDate && this.cursorManager.isCursorComplete(current)) {
5709
+ if (operation === "join") {
5710
+ handedOff = true;
5711
+ return {
5712
+ cursor: current,
5713
+ handedOffWsSession: session,
5714
+ wsLiveHealthy: true
5715
+ };
5716
+ }
5717
+ return { cursor: current };
5718
+ }
5719
+ continue;
5720
+ case "catchup":
5721
+ case "end":
5722
+ return;
5723
+ case "fallback":
5724
+ if (!(joinOptions.createIfNotFound === true && event.reason === "ws_unavailable" && !this.client.isWsMultiplexerUnavailable)) this.client.disableWsReads(event.reason);
5725
+ return;
5726
+ case "error": {
5727
+ if (event.error.status == null) return;
5728
+ const classified = classifyWsReadError(event.error);
5729
+ if (classified.kind === "gone") {
5730
+ forceGone = true;
5731
+ return;
5732
+ }
5733
+ if (classified.kind === "not-found") throw new HttpError("stream not found", 404);
5734
+ throw classified.error;
5735
+ }
5736
+ }
5737
+ }
5738
+ } finally {
5739
+ if (abortHandler != null) signal?.removeEventListener("abort", abortHandler);
5740
+ }
5741
+ });
5742
+ if (inlineResult != null) return inlineResult;
5743
+ } catch (error) {
5744
+ if (!handedOff) {
5745
+ session?.close();
5746
+ session = void 0;
5747
+ }
5748
+ if (error instanceof CrdtApplyIncompleteError) {
5749
+ this.knownRecoveryMetadata = fallbackKnownMeta;
5750
+ try {
5751
+ return await runInitial((signal) => this.bootstrapState({
5752
+ ...current,
5753
+ nextOffset: "-1",
5754
+ serverLowerBoundVersion: atSyncErrorBoundary({
5755
+ source: "crdt",
5756
+ stage: "crdt_export"
5757
+ }, () => this.adapter.emptyVersion())
5758
+ }, {
5759
+ signal,
5760
+ timeoutMode: "initial"
5761
+ }));
5762
+ } finally {
5763
+ this.knownRecoveryMetadata = void 0;
5764
+ }
5765
+ }
5766
+ throw error;
5767
+ } finally {
5768
+ if (!handedOff) session?.close();
5769
+ }
5770
+ if (forceGone) {
5771
+ this.knownRecoveryMetadata = fallbackKnownMeta;
5772
+ try {
5773
+ if (!hasNumericCursor) return await runInitial((signal) => this.bootstrapState(this.createInitialCursor(), {
5774
+ reanchor: true,
5775
+ signal,
5776
+ timeoutMode: "initial"
5777
+ }));
5778
+ return await this.recoverFromGoneWithLocalBootstrap(current, operation, parentSignal);
5779
+ } finally {
5780
+ this.knownRecoveryMetadata = void 0;
5781
+ }
5782
+ }
5783
+ if (forceDecision === "bootstrap") {
5784
+ this.knownRecoveryMetadata = fallbackKnownMeta;
5785
+ try {
5786
+ return await runInitial((signal) => this.bootstrapState(current, {
5787
+ reanchor: true,
5788
+ signal,
5789
+ timeoutMode: "initial"
5790
+ }));
5791
+ } finally {
5792
+ this.knownRecoveryMetadata = void 0;
5793
+ }
5794
+ }
5795
+ return await runHttpInitial(current, fallbackKnownMeta);
5796
+ }
5580
5797
  async resolvePullOnlyRemoteState(operation, parentSignal) {
5581
5798
  const loaded = await atErrorBoundary({
5582
5799
  source: "cursor_store",
@@ -5640,7 +5857,11 @@ var StreamsCrdt = class StreamsCrdt2 {
5640
5857
  }
5641
5858
  async bootstrapState(cursor, options = {}) {
5642
5859
  const cursorManager = options.cursorManager ?? this.cursorManager;
5643
- if (this.incompleteProgress.uploadBaseline == null && await this.persistentRecovery.unchanged(() => this.client.readRecoveryMetadata(), () => {
5860
+ if (this.incompleteProgress.uploadBaseline == null && await this.persistentRecovery.unchanged(() => {
5861
+ const known = this.knownRecoveryMetadata;
5862
+ this.knownRecoveryMetadata = void 0;
5863
+ return known != null ? Promise.resolve(known) : this.client.readRecoveryMetadata();
5864
+ }, () => {
5644
5865
  const version = this.adapter.getCurrentVersion?.();
5645
5866
  return version == null || !jsonObjectEquals(version, this.adapter.emptyVersion()) || (this.joinState?.pendingLocal.length ?? 0) > 0 || this.frozenLocalAppend != null;
5646
5867
  }, Date.now())) {
@@ -5843,10 +6064,22 @@ var StreamsCrdt = class StreamsCrdt2 {
5843
6064
  this.committedLocalStreamCursor = committed.streamCursor;
5844
6065
  return committed.cursor;
5845
6066
  }
5846
- async appendLocalBatchDurably(cursor, batch, pendingCount, source = pendingCount == null ? "direct" : "pending", streamCursor) {
5847
- const frozen = await this.getOrCreateFrozenLocalAppend(cursor, batch, pendingCount, source);
6067
+ async appendLocalBatchDurably(cursor, batch, pendingCount, source = pendingCount == null ? "direct" : "pending", streamCursor, preferWs) {
6068
+ const frozen = await this.getOrCreateFrozenLocalAppend(cursor, batch, pendingCount, source, preferWs);
5848
6069
  const appended = await this.appendFrozenLocalBatchRemote(frozen);
6070
+ if (appended.prevOffset != null && appended.prevOffset === frozen.baseCursor.nextOffset && this.cursorManager.isCursorComplete(frozen.baseCursor)) {
6071
+ const saved = await this.saveRemoteCursor(appended.cursor, "local");
6072
+ this.commitProducerAck(appended.producerAck);
6073
+ if (frozen.appendStartedSyncSeq != null && this.cursorManager.isCursorComplete(saved)) this.lastLinearizedSyncSeq = Math.max(this.lastLinearizedSyncSeq, frozen.appendStartedSyncSeq);
6074
+ return {
6075
+ cursor: saved,
6076
+ pendingCount: frozen.pendingCount,
6077
+ streamCursor
6078
+ };
6079
+ }
6080
+ const catchupStartedSyncSeq = this.syncInvocationSeq;
5849
6081
  const caughtUp = await this.catchupLocalAppend(frozen, streamCursor);
6082
+ if (this.cursorManager.isCursorComplete(caughtUp.cursor)) this.lastLinearizedSyncSeq = Math.max(this.lastLinearizedSyncSeq, catchupStartedSyncSeq);
5850
6083
  this.commitProducerAck(appended.producerAck);
5851
6084
  return {
5852
6085
  cursor: caughtUp.cursor,
@@ -5881,21 +6114,23 @@ var StreamsCrdt = class StreamsCrdt2 {
5881
6114
  pendingCount: frozen.pendingCount
5882
6115
  };
5883
6116
  }
5884
- async getOrCreateFrozenLocalAppend(cursor, batch, pendingCount, source = pendingCount == null ? "direct" : "pending") {
6117
+ async getOrCreateFrozenLocalAppend(cursor, batch, pendingCount, source = pendingCount == null ? "direct" : "pending", preferWs) {
5885
6118
  const existing = this.frozenLocalAppend;
5886
6119
  if (existing != null) {
5887
6120
  if (existing.source !== source) throw new Error(`${existing.source} local append must be finalized before ${source} append`);
5888
6121
  return existing;
5889
6122
  }
6123
+ const wireUpdates = this.encodeUpdateItems == null ? batch.updates : await atErrorBoundary({
6124
+ source: "local",
6125
+ stage: "payload_encode"
6126
+ }, this.encodeUpdateItems.bind(this, batch.updates));
5890
6127
  const frozen = {
5891
6128
  source,
5892
6129
  baseCursor: cursor,
5893
6130
  batch,
5894
6131
  pendingCount,
5895
- wireUpdates: this.encodeUpdateItems == null ? batch.updates : await atErrorBoundary({
5896
- source: "local",
5897
- stage: "payload_encode"
5898
- }, this.encodeUpdateItems.bind(this, batch.updates)),
6132
+ ...preferWs === true && { preferWs: true },
6133
+ wireUpdates,
5899
6134
  producerSession: this.createCurrentProducerSession()
5900
6135
  };
5901
6136
  this.frozenLocalAppend = frozen;
@@ -5905,8 +6140,9 @@ var StreamsCrdt = class StreamsCrdt2 {
5905
6140
  if (frozen.acknowledged != null) return frozen.acknowledged;
5906
6141
  for (let attempt = 0; attempt < 3; attempt += 1) {
5907
6142
  let result;
6143
+ const attemptStartedSyncSeq = this.syncInvocationSeq;
5908
6144
  try {
5909
- result = await atErrorBoundary({ stage: "upload" }, () => this.client.appendUpdates(frozen.wireUpdates, frozen.producerSession, { preferWs: frozen.source === "pending" && this.joinState != null && !this.joinState.closed }));
6145
+ result = await atErrorBoundary({ stage: "upload" }, () => this.client.appendUpdates(frozen.wireUpdates, frozen.producerSession, { preferWs: (frozen.preferWs === true || frozen.source === "pending") && (this.joinState == null || !this.joinState.closed) }));
5910
6146
  } catch (error) {
5911
6147
  if (this.checkOrLatchSpaceFence(error, "upload") != null) throw error;
5912
6148
  if (isStreamNotFoundError(error) && this.canAutoCreateStream()) {
@@ -5929,8 +6165,10 @@ var StreamsCrdt = class StreamsCrdt2 {
5929
6165
  producerAck: {
5930
6166
  epoch: result.ackEpoch,
5931
6167
  seq: result.ackSeq
5932
- }
6168
+ },
6169
+ ...result.prevOffset != null && { prevOffset: result.prevOffset }
5933
6170
  };
6171
+ frozen.appendStartedSyncSeq = attemptStartedSyncSeq;
5934
6172
  frozen.acknowledged = appended;
5935
6173
  return appended;
5936
6174
  }
@@ -5954,9 +6192,21 @@ var StreamsCrdt = class StreamsCrdt2 {
5954
6192
  const frozen = this.frozenLocalAppend;
5955
6193
  if (frozen == null || frozen.pendingCount != null) return state;
5956
6194
  const appended = await this.appendFrozenLocalBatchRemote(frozen);
6195
+ if (appended.prevOffset != null && appended.prevOffset === frozen.baseCursor.nextOffset && this.cursorManager.isCursorComplete(frozen.baseCursor)) {
6196
+ const saved = await this.saveRemoteCursor(appended.cursor, "local");
6197
+ this.commitProducerAck(appended.producerAck);
6198
+ return {
6199
+ ...state,
6200
+ cursor: saved
6201
+ };
6202
+ }
6203
+ state.handedOffWsSession?.close();
5957
6204
  const caughtUp = await this.catchupLocalAppend(frozen, state.streamCursor);
5958
6205
  this.commitProducerAck(appended.producerAck);
5959
- return caughtUp;
6206
+ return {
6207
+ cursor: caughtUp.cursor,
6208
+ streamCursor: caughtUp.streamCursor
6209
+ };
5960
6210
  }
5961
6211
  createCurrentProducerSession() {
5962
6212
  return {
@@ -6292,6 +6542,15 @@ var StreamsCrdt = class StreamsCrdt2 {
6292
6542
  async runReadLoopIterations(state) {
6293
6543
  if (state.requestController == null || state.requestController.signal.aborted) state.requestController = new AbortController();
6294
6544
  while (!state.closed) {
6545
+ let handedOffWsSession = state.handedOffWsSession;
6546
+ state.handedOffWsSession = void 0;
6547
+ const closeHandedOff = () => {
6548
+ if (handedOffWsSession != null) {
6549
+ handedOffWsSession.close();
6550
+ handedOffWsSession = void 0;
6551
+ state.wsLiveHealthy = false;
6552
+ }
6553
+ };
6295
6554
  const capturedController = state.requestController;
6296
6555
  let inactivityTimer = null;
6297
6556
  let dependencyProbeTimer;
@@ -6315,8 +6574,10 @@ var StreamsCrdt = class StreamsCrdt2 {
6315
6574
  }, timeoutMs);
6316
6575
  };
6317
6576
  try {
6318
- if (this.incompleteProgress.needsReanchor && (this.persistentRecovery.fencedTail == null || !this.persistentRecovery.waiting(Date.now()))) await this.rebootstrapLiveState(state, capturedController?.signal, true);
6319
- else if (this.persistentRecovery.fencedTail != null) this.incompleteRecovery.shouldProbe(Date.now());
6577
+ if (this.incompleteProgress.needsReanchor && (this.persistentRecovery.fencedTail == null || !this.persistentRecovery.waiting(Date.now()))) {
6578
+ closeHandedOff();
6579
+ await this.rebootstrapLiveState(state, capturedController?.signal, true);
6580
+ } else if (this.persistentRecovery.fencedTail != null) this.incompleteRecovery.shouldProbe(Date.now());
6320
6581
  else if (this.incompleteRecovery.shouldProbe(Date.now())) {
6321
6582
  let offset = null;
6322
6583
  try {
@@ -6324,9 +6585,14 @@ var StreamsCrdt = class StreamsCrdt2 {
6324
6585
  } catch (error) {
6325
6586
  if (this.checkOrLatchSpaceFence(error, "live") != null) throw error;
6326
6587
  }
6327
- if (this.incompleteRecovery.hasNewSnapshot(offset)) await this.rebootstrapLiveState(state, capturedController?.signal, true);
6588
+ if (this.incompleteRecovery.hasNewSnapshot(offset)) {
6589
+ closeHandedOff();
6590
+ await this.rebootstrapLiveState(state, capturedController?.signal, true);
6591
+ }
6328
6592
  }
6329
6593
  if (state.liveMode === "long-poll") {
6594
+ closeHandedOff();
6595
+ state.wsLiveHealthy = false;
6330
6596
  const requestOffset = this.persistentRecovery.fencedTail ?? state.cursor.nextOffset;
6331
6597
  const response = await atErrorBoundary({ stage: "catch_up" }, () => this.client.readFromOffset(requestOffset, state.streamCursor, "long-poll", capturedController?.signal));
6332
6598
  if (this.persistentRecovery.fencedTail != null && response.kind !== "gone") {
@@ -6370,7 +6636,7 @@ var StreamsCrdt = class StreamsCrdt2 {
6370
6636
  wsLive = this.persistentRecovery.fencedTail == null && this.client.wsLiveReadsAvailable;
6371
6637
  resetInactivity();
6372
6638
  const sseStartedAtMs = Date.now();
6373
- const onControl = (updates, nextOffset, upToDate, streamCursor) => {
6639
+ const onControl = async (updates, nextOffset, upToDate, streamCursor) => {
6374
6640
  if (capturedController?.signal.aborted) return "stop";
6375
6641
  resetInactivity();
6376
6642
  if (this.persistentRecovery.fencedTail != null) {
@@ -6388,7 +6654,7 @@ var StreamsCrdt = class StreamsCrdt2 {
6388
6654
  upToDate,
6389
6655
  streamCursor
6390
6656
  });
6391
- flushChain = flushChain.then(async () => {
6657
+ const step = flushChain.then(async () => {
6392
6658
  const events = pendingRemote.splice(0);
6393
6659
  if (events.length === 0 || state.closed || capturedController?.signal.aborted) return;
6394
6660
  const allUpdates = events.flatMap((e) => e.updates);
@@ -6404,8 +6670,11 @@ var StreamsCrdt = class StreamsCrdt2 {
6404
6670
  }));
6405
6671
  if (this.cursorManager.isCursorComplete(state.cursor)) {
6406
6672
  sseAppliedProgress = true;
6407
- if (lastEvent.upToDate) this.noteInitialTailReached(state);
6408
- }
6673
+ if (lastEvent.upToDate) {
6674
+ state.wsLiveHealthy = wsLive;
6675
+ this.noteInitialTailReached(state);
6676
+ } else state.wsLiveHealthy = false;
6677
+ } else state.wsLiveHealthy = false;
6409
6678
  for (let i = events.length - 1; i >= 0; i--) if (events[i].streamCursor != null) {
6410
6679
  state.streamCursor = events[i].streamCursor;
6411
6680
  break;
@@ -6417,7 +6686,12 @@ var StreamsCrdt = class StreamsCrdt2 {
6417
6686
  }).catch((flushError) => {
6418
6687
  this.logError("sse flush chain error", flushError, { streamUrl: this.streamUrl });
6419
6688
  capturedController?.abort(flushError);
6689
+ throw flushError;
6690
+ });
6691
+ flushChain = step.catch(() => {
6420
6692
  });
6693
+ await step;
6694
+ if (capturedController?.signal.aborted) return "stop";
6421
6695
  };
6422
6696
  const onOpen = () => {
6423
6697
  this.streamObserved = true;
@@ -6426,6 +6700,7 @@ var StreamsCrdt = class StreamsCrdt2 {
6426
6700
  this.setReadSubStatus(state, "ok");
6427
6701
  };
6428
6702
  const catchupViaHttp = async () => {
6703
+ state.wsLiveHealthy = false;
6429
6704
  await flushChain;
6430
6705
  const signal = capturedController?.signal;
6431
6706
  if (signal?.aborted) throw signal.reason ?? new DOMException("Aborted", "AbortError");
@@ -6453,10 +6728,23 @@ var StreamsCrdt = class StreamsCrdt2 {
6453
6728
  if (state.pendingLocal.length > 0) this.flushPendingLocal(state);
6454
6729
  return state.cursor.nextOffset;
6455
6730
  };
6456
- const readResult = wsLive ? await this.client.readFromOffsetWsItems(sseRequestOffset, state.streamCursor, onControl, onOpen, capturedController?.signal, catchupViaHttp) : await this.client.readFromOffsetSseItems(sseRequestOffset, state.streamCursor, onControl, onOpen, capturedController?.signal, resetInactivity);
6731
+ if (!wsLive) {
6732
+ closeHandedOff();
6733
+ state.wsLiveHealthy = false;
6734
+ }
6735
+ const sessionToReuse = handedOffWsSession;
6736
+ handedOffWsSession = void 0;
6737
+ const readResult = wsLive ? await this.client.readFromOffsetWsItems(sseRequestOffset, state.streamCursor, onControl, onOpen, capturedController?.signal, catchupViaHttp, {
6738
+ session: sessionToReuse,
6739
+ onOpenInfo: (info) => {
6740
+ this.noteWsOpenInfo(info);
6741
+ if (info.v11 && info.tailOffset != null && info.tailOffset === sseRequestOffset && this.cursorManager.isCursorComplete(state.cursor)) state.wsLiveHealthy = true;
6742
+ }
6743
+ }) : await this.client.readFromOffsetSseItems(sseRequestOffset, state.streamCursor, onControl, onOpen, capturedController?.signal, resetInactivity);
6457
6744
  clearInactivity();
6458
6745
  if (dependencyProbeTimer != null) clearTimeout(dependencyProbeTimer);
6459
6746
  await flushChain;
6747
+ state.wsLiveHealthy = false;
6460
6748
  if (state.closed) return;
6461
6749
  if (readResult.kind === "ws-fallback") {
6462
6750
  this.logDebug("websocket live read fell back to SSE");
@@ -6487,6 +6775,8 @@ var StreamsCrdt = class StreamsCrdt2 {
6487
6775
  }
6488
6776
  await this.rebootstrapLiveState(state, capturedController?.signal);
6489
6777
  } catch (error) {
6778
+ closeHandedOff();
6779
+ state.wsLiveHealthy = false;
6490
6780
  clearInactivity();
6491
6781
  if (dependencyProbeTimer != null) clearTimeout(dependencyProbeTimer);
6492
6782
  if (state.closed) return;
@@ -7758,12 +8048,35 @@ fnUntraced(function* (options) {
7758
8048
  let unresolved = incompleteProgress.unresolved;
7759
8049
  const persistentRecovery = new PersistentIncompleteRecovery(streamUrl, options.incompleteRecoveryStore);
7760
8050
  let knownSnapshotOffset = null;
8051
+ let knownTailOffset = null;
8052
+ let knownRecoveryMetadata;
8053
+ const noteTailOffset = (offset) => {
8054
+ if (offset == null) return;
8055
+ knownTailOffset = knownTailOffset == null ? offset : resolveNextOffsetAfterConcurrentAdvance(knownTailOffset, knownTailOffset, offset);
8056
+ };
8057
+ const noteWsOpenInfo = (info) => {
8058
+ streamObserved = true;
8059
+ noteTailOffset(info.tailOffset);
8060
+ if (info.v11) knownSnapshotOffset = info.snapshotOffset ?? "-1";
8061
+ else if (info.snapshotOffset != null) knownSnapshotOffset = info.snapshotOffset;
8062
+ };
8063
+ const nextWsEvent = (session) => callback((resume) => {
8064
+ let active = true;
8065
+ session.next().then((event) => {
8066
+ if (active) resume(succeed$1(event));
8067
+ });
8068
+ return sync(() => {
8069
+ active = false;
8070
+ });
8071
+ });
7761
8072
  let recoveryTentative = false;
7762
8073
  let incompleteRemote;
7763
8074
  let streamCursor;
7764
8075
  let lastAckAtMs;
7765
8076
  let localRevision = 0;
7766
8077
  let syncTicket = 0;
8078
+ let syncInvocationSeq = 0;
8079
+ let lastLinearizedSyncSeq = 0;
7767
8080
  let foreignRevision = 0;
7768
8081
  let writeBlocked = false;
7769
8082
  let lastWriteBlockedFailure;
@@ -8176,9 +8489,11 @@ fnUntraced(function* (options) {
8176
8489
  unresolved = remoteFact?.complete === false ? remoteFact.unresolved : applied.unresolved;
8177
8490
  const remoteVersion = remoteFact?.version ?? (complete && result.upToDate ? adapter.mergeVersions(applied.version, acknowledgedVersion) : applied.version);
8178
8491
  if (!jsonObjectEquals(adapter.mergeVersions(before, acknowledgedVersion), adapter.mergeVersions(adapter.mergeVersions(before, acknowledgedVersion), applied.version))) foreignRevision++;
8492
+ const nextCursorOffset = resolveNextOffsetAfterConcurrentAdvance(requestOffset, cursor.nextOffset, result.nextOffset);
8493
+ noteTailOffset(nextCursorOffset);
8179
8494
  cursor = {
8180
8495
  ...cursor,
8181
- nextOffset: resolveNextOffsetAfterConcurrentAdvance(requestOffset, cursor.nextOffset, result.nextOffset),
8496
+ nextOffset: nextCursorOffset,
8182
8497
  serverLowerBoundVersion: remoteVersion
8183
8498
  };
8184
8499
  if (result.streamCursor != null) streamCursor = result.streamCursor;
@@ -8199,7 +8514,7 @@ fnUntraced(function* (options) {
8199
8514
  head.epoch ??= producerEpoch;
8200
8515
  head.seq ??= nextSeq;
8201
8516
  });
8202
- const appendTransport = (g, body, epoch, seq, onAck) => wsRoom == null || !wsRoom.writesAvailable || !g.initialized ? protocol(g).append(body, producerId, epoch, seq, onAck) : promise(() => wsRoom.append(body, {
8517
+ const appendTransport = (g, body, epoch, seq, onAck) => wsRoom == null || !wsRoom.writesAvailable || !g.initialized ? protocol(g).append(body, producerId, epoch, seq, (tail) => onAck(tail)) : promise(() => wsRoom.append(body, {
8203
8518
  id: producerId,
8204
8519
  epoch,
8205
8520
  seq
@@ -8207,10 +8522,11 @@ fnUntraced(function* (options) {
8207
8522
  switch (outcome2.kind) {
8208
8523
  case "ack":
8209
8524
  return sync(() => {
8210
- onAck(outcome2.nextOffset);
8525
+ onAck(outcome2.nextOffset, outcome2.prevOffset);
8211
8526
  return {
8212
8527
  kind: "ack",
8213
- tail: outcome2.nextOffset
8528
+ tail: outcome2.nextOffset,
8529
+ ...outcome2.prevOffset != null && { prevOffset: outcome2.prevOffset }
8214
8530
  };
8215
8531
  });
8216
8532
  case "seq-gap":
@@ -8226,15 +8542,19 @@ fnUntraced(function* (options) {
8226
8542
  case "failed":
8227
8543
  return fail(outcome2.error);
8228
8544
  default:
8229
- return protocol(g).append(body, producerId, epoch, seq, onAck);
8545
+ return protocol(g).append(body, producerId, epoch, seq, (tail) => onAck(tail));
8230
8546
  }
8231
8547
  }));
8232
8548
  const appendUnlocked = fnUntraced(function* (g, head) {
8233
8549
  yield* freeze(g, head);
8234
8550
  if (head.ack == null) {
8235
8551
  for (let repair = 0; repair < 3; repair++) {
8236
- const result = yield* boundary(g, "fetch", "upload", appendTransport(g, head.body, head.epoch, head.seq, (tail) => {
8552
+ const attemptSyncSeq = syncInvocationSeq;
8553
+ const result = yield* boundary(g, "fetch", "upload", appendTransport(g, head.body, head.epoch, head.seq, (tail, prevOffset) => {
8237
8554
  head.ack = tail;
8555
+ head.ackPrevOffset = prevOffset;
8556
+ head.ackSyncSeq = attemptSyncSeq;
8557
+ noteTailOffset(tail);
8238
8558
  }));
8239
8559
  if (result.kind === "ack") {
8240
8560
  streamObserved = true;
@@ -8315,7 +8635,9 @@ fnUntraced(function* (options) {
8315
8635
  },
8316
8636
  catch: (error) => project(fail$3(error), "crdt", "crdt_apply")
8317
8637
  });
8318
- const head = yield* exit(boundary(g, "fetch", "bootstrap", protocol(g).recoveryMetadata));
8638
+ const knownMeta = knownRecoveryMetadata;
8639
+ knownRecoveryMetadata = void 0;
8640
+ const head = knownMeta != null ? succeed$2(knownMeta) : yield* exit(boundary(g, "fetch", "bootstrap", protocol(g).recoveryMetadata));
8319
8641
  if (isSuccess(head) && !hasLocalHistory() && head.value.nextOffset === record.observedTailOffset && (head.value.snapshotOffset ?? "-1") === (record.observedSnapshotOffset ?? "-1")) {
8320
8642
  persistentRecovery.noteUnchanged(now);
8321
8643
  streamObserved = true;
@@ -8354,6 +8676,7 @@ fnUntraced(function* (options) {
8354
8676
  incompleteRecovery.noteSnapshot(response.snapshotOffset);
8355
8677
  persistentRecovery.snapshotOffset = response.snapshotOffset;
8356
8678
  knownSnapshotOffset = response.snapshotOffset;
8679
+ knownTailOffset = response.nextOffset;
8357
8680
  if (recovery && writeBlocked) {
8358
8681
  if (!g.backlogInitialized) yield* prepareBacklogBody(g);
8359
8682
  const pendingUpdates = pending.filter((head) => head.ack == null).flatMap((head) => head.batch.updates.map((u) => new Uint8Array(u)));
@@ -8434,8 +8757,10 @@ fnUntraced(function* (options) {
8434
8757
  }
8435
8758
  });
8436
8759
  const drain = fnUntraced(function* (g, watermark = lastId, readBack = true, through) {
8437
- if (incompleteProgress.uploadBaseline == null) return;
8760
+ if (incompleteProgress.uploadBaseline == null) return false;
8761
+ let didLinearize = false;
8438
8762
  while (true) {
8763
+ let appendedHead;
8439
8764
  if (!(yield* appendGate.withPermit(gen(function* () {
8440
8765
  yield* check(g);
8441
8766
  const head = pending[0];
@@ -8444,16 +8769,33 @@ fnUntraced(function* (options) {
8444
8769
  if (writeBlocked && lastWriteBlockedFailure != null) return yield* fail(lastWriteBlockedFailure);
8445
8770
  yield* appendUnlocked(g, head);
8446
8771
  if (pending[0] === head) pending.shift();
8772
+ appendedHead = head;
8447
8773
  g.writeFailed = false;
8448
8774
  yield* notify();
8449
8775
  return true;
8450
- })))) return;
8451
- if (readBack && complete && !recoveryTentative) yield* catchup(g, void 0, "local");
8776
+ })))) return didLinearize;
8777
+ if (readBack && complete && !recoveryTentative) if (appendedHead?.ack != null && appendedHead.ackPrevOffset != null && appendedHead.ackPrevOffset === cursor.nextOffset) {
8778
+ noteTailOffset(appendedHead.ack);
8779
+ cursor = {
8780
+ ...cursor,
8781
+ nextOffset: appendedHead.ack,
8782
+ serverLowerBoundVersion: adapter.mergeVersions(cursor.serverLowerBoundVersion, appendedHead.batch.version)
8783
+ };
8784
+ yield* notify();
8785
+ yield* checkpoint(g, "local", true);
8786
+ if (appendedHead.ackSyncSeq != null) lastLinearizedSyncSeq = Math.max(lastLinearizedSyncSeq, appendedHead.ackSyncSeq);
8787
+ didLinearize = true;
8788
+ } else {
8789
+ const catchupSyncSeq = syncInvocationSeq;
8790
+ yield* catchup(g, void 0, "local");
8791
+ if (complete && !recoveryTentative) lastLinearizedSyncSeq = Math.max(lastLinearizedSyncSeq, catchupSyncSeq);
8792
+ didLinearize = true;
8793
+ }
8452
8794
  }
8453
8795
  });
8454
8796
  const drainRecordingWriteBlock = fnUntraced(function* (g, watermark = lastId, readBack = true, through) {
8455
8797
  const result = yield* exit(drain(g, watermark, readBack, through));
8456
- if (isSuccess(result)) return;
8798
+ if (isSuccess(result)) return result.value;
8457
8799
  const blockedFailure = asWriteBlockedFailure(result.cause);
8458
8800
  if (blockedFailure != null) yield* noteWriteBlocked(blockedFailure);
8459
8801
  return yield* failCause(result.cause);
@@ -8488,17 +8830,41 @@ fnUntraced(function* (options) {
8488
8830
  yield* prepareBacklog(g);
8489
8831
  if (writeBlocked && pending.length === 0) yield* exportBacklog(g, cursor.serverLowerBoundVersion);
8490
8832
  if (writeBlocked && pending.length > 0 && lastWriteBlockedFailure != null) return yield* fail(lastWriteBlockedFailure);
8833
+ const verifyWsTailCurrent = fnUntraced(function* (expectedOffset) {
8834
+ if (wsRoom == null || !wsRoom.readsAvailable) return false;
8835
+ const probeExit = yield* exit(promise(() => wsRoom.probe()));
8836
+ if (isFailure(probeExit)) {
8837
+ if (hasInterruptsOnly(probeExit.cause)) return yield* failCause(probeExit.cause);
8838
+ return false;
8839
+ }
8840
+ if (!probeExit.value || !g.online) return false;
8841
+ return yield* acquireUseRelease(sync(() => wsRoom.openDurable(expectedOffset, { headOnly: true })), (session) => session == null ? succeed$1(false) : nextWsEvent(session).pipe(map((event) => {
8842
+ if (event.type !== "open") return false;
8843
+ noteWsOpenInfo(event.info);
8844
+ return event.info.v11 && event.info.tailOffset === expectedOffset;
8845
+ }), timeoutOrElse({
8846
+ duration: config.connectTimeoutMs > 0 ? config.connectTimeoutMs : 5e3,
8847
+ orElse: () => succeed$1(false)
8848
+ })), (session) => sync(() => {
8849
+ session?.close();
8850
+ }));
8851
+ });
8852
+ const canSkipWsRead = () => wsRoom != null && wsRoom.readsAvailable && g.wsLiveHealthy && g.initialized && g.readStatus === "joined" && complete && !recoveryTentative && !g.readRejoinPending && !incompleteRecovery.active && !dependencyWaiting;
8491
8853
  const watermark = lastId;
8492
8854
  transaction.revision = localRevision;
8493
- if (complete) yield* catchup(g);
8494
- yield* drainRecordingWriteBlock(g, watermark);
8855
+ if (complete && !canSkipWsRead()) yield* catchup(g);
8856
+ const didLinearize1 = yield* drainRecordingWriteBlock(g, watermark);
8495
8857
  if (!complete) yield* catchup(g);
8496
8858
  if (recoveryTentative) yield* bootstrap(g, true);
8859
+ let didLinearize2 = false;
8497
8860
  if (pending.length === 0 && !writeBlocked) {
8498
8861
  yield* exportBacklog(g, cursor.serverLowerBoundVersion);
8499
- yield* drainRecordingWriteBlock(g);
8862
+ didLinearize2 = yield* drainRecordingWriteBlock(g);
8500
8863
  }
8501
- yield* catchup(g);
8864
+ if (canSkipWsRead()) {
8865
+ const requiredSyncSeq = transaction.maxSyncSeq ?? syncInvocationSeq;
8866
+ if (!(didLinearize1 || didLinearize2 || lastLinearizedSyncSeq >= requiredSyncSeq) && !(yield* verifyWsTailCurrent(cursor.nextOffset))) yield* catchup(g);
8867
+ } else yield* catchup(g);
8502
8868
  if (!complete || recoveryTentative) return yield* fail(project(fail$3(new CrdtApplyIncompleteError(unresolved ?? [])), "crdt", "crdt_apply"));
8503
8869
  return {
8504
8870
  kind: "confirmed",
@@ -8565,13 +8931,124 @@ fnUntraced(function* (options) {
8565
8931
  if (saved.streamUrl !== streamUrl) return yield* fail(project(fail$3(new ProtocolError("cursor belongs to a different stream")), "cursor_store", "cursor_load"));
8566
8932
  cursor = saved;
8567
8933
  durable = saved;
8934
+ knownTailOffset = saved.nextOffset;
8568
8935
  if (saved.nextOffset !== "-1") {
8569
8936
  streamObserved = true;
8570
8937
  incompleteProgress.uploadBaseline = saved.serverLowerBoundVersion;
8571
8938
  }
8572
8939
  }
8573
8940
  }
8574
- const body = durable == null && incompleteProgress.cursor == null ? bootstrap(g, false, true) : catchup(g);
8941
+ const tryInitialWs = fnUntraced(function* (g2) {
8942
+ if ((options.readMode ?? "sse") !== "sse" || wsRoom == null || !wsRoom.readsAvailable || persistentRecovery.waiting(clock.currentTimeMillisUnsafe())) return false;
8943
+ if (!(yield* promise(() => wsRoom.probe())) || !g2.online) return false;
8944
+ const canAutoCreateJoin = Boolean(options.createStreamIfMissing && !streamObserved && spaceFenced == null && adapter.getCreateStreamHeaders == null);
8945
+ const session = wsRoom.openDurable(cursor.nextOffset, {
8946
+ maxInlineBytes: DS_WS_INITIAL_MAX_INLINE_BYTES,
8947
+ ...canAutoCreateJoin && {
8948
+ createIfNotFound: true,
8949
+ ...options.streamTtlSeconds != null && { ttlSeconds: BigInt(options.streamTtlSeconds) }
8950
+ }
8951
+ });
8952
+ if (session == null) return false;
8953
+ const hasNumericCursor = cursor.nextOffset !== "-1" && !incompleteRecovery.active && incompleteProgress.cursor == null;
8954
+ const incompleteActive = incompleteRecovery.active || !complete || incompleteProgress.cursor != null;
8955
+ let handedOff = false;
8956
+ let decidedInline = false;
8957
+ let requested = cursor.nextOffset;
8958
+ let forceBootstrap = false;
8959
+ let forceCatchup = false;
8960
+ const cleanup = sync(() => {
8961
+ if (!handedOff) session.close();
8962
+ });
8963
+ const outcome2 = yield* exit(gen(function* () {
8964
+ while (g2.online) {
8965
+ const event = yield* nextWsEvent(session);
8966
+ if (event.type === "open") {
8967
+ noteWsOpenInfo(event.info);
8968
+ knownRecoveryMetadata = event.info.v11 && event.info.tailOffset != null ? {
8969
+ nextOffset: event.info.tailOffset,
8970
+ snapshotOffset: event.info.snapshotOffset ?? null
8971
+ } : void 0;
8972
+ if (!decidedInline) {
8973
+ const decision = decideWsInitialSync(event.info, {
8974
+ hasNumericCursor,
8975
+ incompleteRecoveryActive: incompleteActive,
8976
+ protectedBootstrap: options.e2ee != null
8977
+ });
8978
+ if (decision.kind === "bootstrap") {
8979
+ forceBootstrap = true;
8980
+ return false;
8981
+ }
8982
+ if (decision.kind === "catchup") {
8983
+ forceCatchup = true;
8984
+ return false;
8985
+ }
8986
+ decidedInline = true;
8987
+ }
8988
+ continue;
8989
+ }
8990
+ if (event.type === "page") {
8991
+ const applied = yield* exit(applyRead(g2, {
8992
+ updates: event.updates,
8993
+ nextOffset: event.nextOffset,
8994
+ upToDate: event.upToDate
8995
+ }, requested));
8996
+ if (isFailure(applied)) {
8997
+ event.reject(/* @__PURE__ */ new Error("page apply failed"));
8998
+ return yield* failCause(applied.cause);
8999
+ }
9000
+ event.resolve();
9001
+ requested = cursor.nextOffset;
9002
+ if (event.upToDate && complete && !recoveryTentative) {
9003
+ g2.handedOffWsSession = session;
9004
+ g2.wsLiveHealthy = true;
9005
+ handedOff = true;
9006
+ knownRecoveryMetadata = void 0;
9007
+ return true;
9008
+ }
9009
+ continue;
9010
+ }
9011
+ if (event.type === "catchup" || event.type === "end") return false;
9012
+ if (event.type === "fallback") {
9013
+ if (!(canAutoCreateJoin && event.reason === "ws_unavailable" && !wsRoom.isMultiplexerUnavailable)) wsRoom.disableReads(event.reason);
9014
+ return false;
9015
+ }
9016
+ if (event.error.status == null) return false;
9017
+ const classified = classifyWsReadError(event.error);
9018
+ if (classified.kind === "gone") {
9019
+ forceBootstrap = true;
9020
+ return false;
9021
+ }
9022
+ if (classified.kind === "not-found") return yield* boundary(g2, "fetch", "bootstrap", fail(new HttpError("stream not found", 404)));
9023
+ return yield* boundary(g2, "fetch", "catch_up", fail(classified.error));
9024
+ }
9025
+ return false;
9026
+ }).pipe(ensuring(cleanup)));
9027
+ if (isFailure(outcome2)) {
9028
+ knownRecoveryMetadata = void 0;
9029
+ return yield* failCause(outcome2.cause);
9030
+ }
9031
+ if (outcome2.value) {
9032
+ knownRecoveryMetadata = void 0;
9033
+ return true;
9034
+ }
9035
+ if (forceBootstrap) {
9036
+ yield* bootstrap(g2, durable != null || incompleteProgress.cursor != null, true).pipe(ensuring(sync(() => {
9037
+ knownRecoveryMetadata = void 0;
9038
+ })));
9039
+ return true;
9040
+ }
9041
+ if (forceCatchup) {
9042
+ yield* catchup(g2).pipe(ensuring(sync(() => {
9043
+ knownRecoveryMetadata = void 0;
9044
+ })));
9045
+ return true;
9046
+ }
9047
+ knownRecoveryMetadata = void 0;
9048
+ return false;
9049
+ });
9050
+ const httpBody = () => durable == null && incompleteProgress.cursor == null ? bootstrap(g, false, true) : catchup(g);
9051
+ const body = tryInitialWs(g).pipe(flatMap((handled) => handled ? void_ : httpBody()));
8575
9052
  const first = yield* exit(body);
8576
9053
  if (isFailure(first)) {
8577
9054
  const found = findErrorOption(first.cause);
@@ -8592,7 +9069,7 @@ fnUntraced(function* (options) {
8592
9069
  g.readStatus = "joined";
8593
9070
  g.error = void 0;
8594
9071
  scheduleReadSnapshot(g);
8595
- yield* succeed$2(g.ready, void 0);
9072
+ yield* succeed$3(g.ready, void 0);
8596
9073
  yield* offer(g.wake, void 0);
8597
9074
  yield* notify();
8598
9075
  });
@@ -8620,43 +9097,67 @@ fnUntraced(function* (options) {
8620
9097
  while (g.online && g.blocked == null && spaceFenced == null) {
8621
9098
  const openedAtMs = yield* currentTimeMillis;
8622
9099
  let requestOffset = persistentRecovery.fencedTail ?? cursor.nextOffset;
9100
+ let handedOffSession = g.handedOffWsSession;
9101
+ g.handedOffWsSession = void 0;
9102
+ const closeHandedOff = () => {
9103
+ if (handedOffSession != null) {
9104
+ handedOffSession.close();
9105
+ handedOffSession = void 0;
9106
+ g.wsLiveHealthy = false;
9107
+ }
9108
+ };
8623
9109
  const ws = persistentRecovery.fencedTail == null && mode === "sse" && wsRoom?.readsAvailable ? wsRoom : void 0;
9110
+ if (ws == null || mode === "long-poll") {
9111
+ closeHandedOff();
9112
+ g.wsLiveHealthy = false;
9113
+ }
8624
9114
  let wsFellBack = false;
8625
9115
  const wsLive = (room) => gen(function* () {
8626
- if (!(yield* promise(() => room.probe()))) {
8627
- wsFellBack = true;
8628
- return;
9116
+ let session = handedOffSession != null && !handedOffSession.isClosed ? handedOffSession : void 0;
9117
+ handedOffSession = void 0;
9118
+ if (session == null) {
9119
+ g.wsLiveHealthy = false;
9120
+ if (!(yield* promise(() => room.probe()))) {
9121
+ wsFellBack = true;
9122
+ return;
9123
+ }
9124
+ session = room.openDurable(requestOffset);
8629
9125
  }
8630
- const session = room.openDurable(requestOffset);
8631
9126
  if (session == null) {
8632
9127
  wsFellBack = true;
8633
9128
  return;
8634
9129
  }
9130
+ const activeSession = session;
8635
9131
  yield* gen(function* () {
8636
9132
  let requested = requestOffset;
8637
9133
  while (g.online) {
8638
- const nextEvent = promise(() => session.next());
9134
+ const nextEvent = nextWsEvent(activeSession);
8639
9135
  const event = yield* dependencyWaiting && incompleteRecovery.exhausted ? nextEvent.pipe(timeoutOrElse({
8640
9136
  duration: incompleteRecovery.probeDelay(yield* currentTimeMillis),
8641
9137
  orElse: () => fail(project(fail$3(new CrdtApplyIncompleteError(unresolved ?? [], void 0, true)), "crdt", "crdt_apply"))
8642
9138
  })) : nextEvent;
8643
9139
  if (event.type === "open") {
8644
- streamObserved = true;
9140
+ noteWsOpenInfo(event.info);
9141
+ if (event.info.v11 && event.info.tailOffset != null && event.info.tailOffset === requested && complete && !recoveryTentative) g.wsLiveHealthy = true;
8645
9142
  continue;
8646
9143
  }
8647
9144
  if (event.type === "page") {
9145
+ if (!event.upToDate) g.wsLiveHealthy = false;
8648
9146
  const applied = yield* exit(gate.withPermit(applyRead(g, {
8649
9147
  updates: event.updates,
8650
9148
  nextOffset: event.nextOffset,
8651
9149
  upToDate: event.upToDate
8652
9150
  }, requested)));
8653
9151
  if (isFailure(applied)) {
9152
+ g.wsLiveHealthy = false;
8654
9153
  event.reject(/* @__PURE__ */ new Error("page apply failed"));
8655
9154
  return yield* failCause(applied.cause);
8656
9155
  }
8657
9156
  event.resolve();
8658
- requested = event.nextOffset;
9157
+ requested = cursor.nextOffset;
9158
+ g.wsLiveHealthy = event.upToDate && complete && !recoveryTentative;
8659
9159
  } else if (event.type === "catchup") {
9160
+ g.wsLiveHealthy = false;
8660
9161
  const caught = yield* exit(gate.withPermit(catchup(g)));
8661
9162
  if (isFailure(caught)) {
8662
9163
  event.reject(/* @__PURE__ */ new Error("catch-up failed"));
@@ -8664,12 +9165,16 @@ fnUntraced(function* (options) {
8664
9165
  }
8665
9166
  requested = cursor.nextOffset;
8666
9167
  event.resolve(requested);
8667
- } else if (event.type === "end") return;
8668
- else if (event.type === "fallback") {
8669
- room.disableReads();
9168
+ } else if (event.type === "end") {
9169
+ g.wsLiveHealthy = false;
9170
+ return;
9171
+ } else if (event.type === "fallback") {
9172
+ g.wsLiveHealthy = false;
9173
+ room.disableReads(event.reason);
8670
9174
  wsFellBack = true;
8671
9175
  return;
8672
9176
  } else {
9177
+ g.wsLiveHealthy = false;
8673
9178
  const classified = classifyWsReadError(event.error);
8674
9179
  return yield* fail(classified.kind === "gone" ? new HttpError("WebSocket subscription gone", 410) : classified.kind === "not-found" ? new HttpError("stream not found", 404) : classified.error);
8675
9180
  }
@@ -8679,16 +9184,24 @@ fnUntraced(function* (options) {
8679
9184
  recoveries = 0;
8680
9185
  yield* notify();
8681
9186
  }
8682
- }).pipe(ensuring(sync(() => session.close())));
9187
+ }).pipe(ensuring(sync(() => {
9188
+ g.wsLiveHealthy = false;
9189
+ activeSession.close();
9190
+ })));
8683
9191
  });
8684
9192
  const repair = gen(function* () {
8685
- if (incompleteProgress.needsReanchor && (persistentRecovery.fencedTail == null || !persistentRecovery.waiting(clock.currentTimeMillisUnsafe()))) yield* gate.withPermit(bootstrap(g, true, true));
8686
- else if (persistentRecovery.fencedTail != null) incompleteRecovery.shouldProbe(yield* currentTimeMillis);
9193
+ if (incompleteProgress.needsReanchor && (persistentRecovery.fencedTail == null || !persistentRecovery.waiting(clock.currentTimeMillisUnsafe()))) {
9194
+ closeHandedOff();
9195
+ yield* gate.withPermit(bootstrap(g, true, true));
9196
+ } else if (persistentRecovery.fencedTail != null) incompleteRecovery.shouldProbe(yield* currentTimeMillis);
8687
9197
  else if (incompleteRecovery.shouldProbe(yield* currentTimeMillis)) {
8688
9198
  const probe = yield* exit(boundary(g, "fetch", "bootstrap", protocol(g).snapshotOffset));
8689
9199
  if (isFailure(probe) && (g.blocked != null || spaceFenced != null)) return yield* failCause(probe.cause);
8690
9200
  const offset = isSuccess(probe) ? probe.value : null;
8691
- if (incompleteRecovery.hasNewSnapshot(offset)) yield* gate.withPermit(bootstrap(g, true, true));
9201
+ if (incompleteRecovery.hasNewSnapshot(offset)) {
9202
+ closeHandedOff();
9203
+ yield* gate.withPermit(bootstrap(g, true, true));
9204
+ }
8692
9205
  }
8693
9206
  });
8694
9207
  const result = yield* exit(repair.pipe(tap(() => sync(() => {
@@ -8747,6 +9260,8 @@ fnUntraced(function* (options) {
8747
9260
  yield* notify();
8748
9261
  }
8749
9262
  }))))));
9263
+ closeHandedOff();
9264
+ g.wsLiveHealthy = false;
8750
9265
  if (!g.online) return;
8751
9266
  if (wsFellBack && isSuccess(result)) continue;
8752
9267
  if (isSuccess(result)) {
@@ -8827,7 +9342,7 @@ fnUntraced(function* (options) {
8827
9342
  g.initialized = true;
8828
9343
  g.readRejoinPending = true;
8829
9344
  g.readStatus = "reconnecting";
8830
- yield* succeed$2(g.ready, void 0);
9345
+ yield* succeed$3(g.ready, void 0);
8831
9346
  yield* offer(g.wake, void 0);
8832
9347
  yield* notify();
8833
9348
  return;
@@ -8961,6 +9476,21 @@ fnUntraced(function* (options) {
8961
9476
  }
8962
9477
  }
8963
9478
  if (options.snapshotUpload != null && !(yield* observe("permission", boundary(g, "local", "crdt_export", fromMaybe(io(g), options.snapshotUpload.canUpload))))) return false;
9479
+ if (automatic && knownSnapshotOffset != null && durable != null) {
9480
+ const knownTail = parseSnapshotByteOffset(knownTailOffset);
9481
+ const durableTail = parseSnapshotByteOffset(durable.nextOffset);
9482
+ const effectiveTail = knownTail != null && durableTail != null ? knownTail > durableTail ? knownTail : durableTail : durableTail ?? knownTail;
9483
+ const lower = parseSnapshotByteOffset(knownSnapshotOffset);
9484
+ const minBytes = BigInt(Math.max(0, Math.floor(readTriggered ? Number(snapshotConfig?.maxBytesSinceRemoteSnapshot ?? 4n * 1024n * 1024n) : resolveSnapshotUploadMinBytes(options.snapshotUpload))));
9485
+ if (effectiveTail == null || lower == null || effectiveTail <= lower || effectiveTail - lower < minBytes) {
9486
+ emit({
9487
+ stage: "export",
9488
+ outcome: "skipped",
9489
+ elapsedMs: 0
9490
+ });
9491
+ return false;
9492
+ }
9493
+ }
8964
9494
  const remoteOffset = yield* boundary(g, "fetch", "bootstrap", protocol(g).readSnapshotOffset(requestDiagnostics("head")));
8965
9495
  knownSnapshotOffset = remoteOffset;
8966
9496
  if (adapter.flushLocalExports != null) yield* boundary(g, "crdt", "crdt_export", adapter.flushLocalExports(io(g)));
@@ -9079,6 +9609,10 @@ fnUntraced(function* (options) {
9079
9609
  });
9080
9610
  const networkCloseWork = fnUntraced(function* (g) {
9081
9611
  g.online = false;
9612
+ g.wsLiveHealthy = false;
9613
+ const handedOff = g.handedOffWsSession;
9614
+ g.handedOffWsSession = void 0;
9615
+ handedOff?.close();
9082
9616
  g.readStatus = "disconnected";
9083
9617
  yield* g.owner.shutdown;
9084
9618
  yield* fail$1(g.ready, new DurableClosed());
@@ -9102,7 +9636,7 @@ fnUntraced(function* (options) {
9102
9636
  const stopNetwork = (g) => uninterruptibleMask((restore) => gen(function* () {
9103
9637
  if (g.closeDone == null) {
9104
9638
  g.online = false;
9105
- yield* succeed$2(g.stopped, void 0);
9639
+ yield* succeed$3(g.stopped, void 0);
9106
9640
  g.readStatus = "disconnected";
9107
9641
  g.closeDone = makeUnsafe();
9108
9642
  yield* g.owner.shutdown;
@@ -9114,7 +9648,7 @@ fnUntraced(function* (options) {
9114
9648
  if (isFailure(exit2)) {
9115
9649
  g.blocked = receipt(g, exit2.cause);
9116
9650
  yield* fail$1(done2, g.blocked);
9117
- } else yield* succeed$2(done2, void 0);
9651
+ } else yield* succeed$3(done2, void 0);
9118
9652
  yield* notify();
9119
9653
  })))));
9120
9654
  }
@@ -9191,6 +9725,7 @@ fnUntraced(function* (options) {
9191
9725
  initialized: false,
9192
9726
  backlogInitialized: false,
9193
9727
  readRejoinPending: false,
9728
+ wsLiveHealthy: false,
9194
9729
  readStatus: "disconnected",
9195
9730
  writeFailed: false,
9196
9731
  releaseCause: empty
@@ -9248,7 +9783,8 @@ fnUntraced(function* (options) {
9248
9783
  if (incompleteRecovery.active && incompleteProgress.uploadBaseline == null) return fail(initialBaselineFailure());
9249
9784
  const target = {
9250
9785
  ticket: ++syncTicket,
9251
- revision: localRevision
9786
+ revision: localRevision,
9787
+ syncSeq: ++syncInvocationSeq
9252
9788
  };
9253
9789
  return _await(g.ready).pipe(flatMap(() => uninterruptibleMask((restore) => gen(function* () {
9254
9790
  while (true) {
@@ -9256,7 +9792,10 @@ fnUntraced(function* (options) {
9256
9792
  yield* check(g);
9257
9793
  let transaction2 = g.syncing;
9258
9794
  if (transaction2 == null) {
9259
- transaction2 = { done: yield* make$6() };
9795
+ transaction2 = {
9796
+ done: yield* make$6(),
9797
+ maxSyncSeq: target.syncSeq
9798
+ };
9260
9799
  g.syncing = transaction2;
9261
9800
  const admitted = transaction2;
9262
9801
  yield* forkIn(uninterruptibleMask((innerRestore) => innerRestore(gate.withPermit(syncExclusive(g, admitted))).pipe(exit, tap((exit2) => gen(function* () {
@@ -9270,7 +9809,7 @@ fnUntraced(function* (options) {
9270
9809
  if (g.syncing === admitted) g.syncing = void 0;
9271
9810
  yield* done(admitted.done, resolved);
9272
9811
  })), asVoid)), g.scope);
9273
- }
9812
+ } else transaction2.maxSyncSeq = Math.max(transaction2.maxSyncSeq ?? 0, target.syncSeq);
9274
9813
  return transaction2;
9275
9814
  }));
9276
9815
  const result = yield* restore(_await(transaction.done));
@@ -9351,7 +9890,7 @@ fnUntraced(function* (options) {
9351
9890
  if (!released) {
9352
9891
  released = true;
9353
9892
  if (epoch === leaseEpoch) leases--;
9354
- yield* succeed$2(stopped, void 0);
9893
+ yield* succeed$3(stopped, void 0);
9355
9894
  }
9356
9895
  return yield* epoch === leaseEpoch && leases === 0 ? close$1 : void_;
9357
9896
  });
@@ -9454,7 +9993,7 @@ fnUntraced(function* (options) {
9454
9993
  };
9455
9994
  yield* addFinalizer(() => gen(function* () {
9456
9995
  retired = true;
9457
- yield* succeed$2(retiredSignal, void 0);
9996
+ yield* succeed$3(retiredSignal, void 0);
9458
9997
  yield* close$1;
9459
9998
  retirementComplete = true;
9460
9999
  yield* close(supervisionScope, void_$1);
@@ -9535,9 +10074,9 @@ function removeRunDependency(id) {
9535
10074
  (_a = Module["monitorRunDependencies"]) === null || _a === void 0 || _a.call(Module, runDependencies);
9536
10075
  if (runDependencies == 0) {
9537
10076
  if (dependenciesFulfilled) {
9538
- var callback = dependenciesFulfilled;
10077
+ var callback2 = dependenciesFulfilled;
9539
10078
  dependenciesFulfilled = null;
9540
- callback();
10079
+ callback2();
9541
10080
  }
9542
10081
  }
9543
10082
  }
@@ -10287,4 +10826,4 @@ export {
10287
10826
  isValidRillId as i,
10288
10827
  makeEphemeralStream as m
10289
10828
  };
10290
- //# sourceMappingURL=vendor-@loro-dev-streams-crdt-BOuVa3yO.js.map
10829
+ //# sourceMappingURL=vendor-@loro-dev-streams-crdt-CsXRvQxK.js.map