← Back to Pull requests

[lexical-y][lexical-playground][lexical-website] Feature: Local persistence and edits that did not sync (@lexical/y/offline) #9899

Merged
zurfyx merged 31 files (9367 lines) on Nov 13, 2026 18:18 UTC
View on GitHub
zurfyx zurfyx commented on Nov 13, 2026 14:29 UTC
Author

Description

@lexical/y gives an app freeze() and describeUnsyncedEdits for a client whose room moved on, but nothing stores a Yjs 14 document on the device: y-indexeddb imports Yjs 13, and none keys by epoch or reports quota or damage. Edits that never reached a server live only in the tab.

This adds @lexical/y/offline, an experimental entry with two layers:

  • A local store on IndexedDB alone, with no new dependency (openYOfflineStore). A slot per document key and epoch holds a base (what the server is known to hold) and the updates since. Writes are incremental and compacted. Two tabs on one key keep each other's rows: each writing handle holds a Web Lock (navigator.locks by default) and writes the whole document as its first row, so its later rows build only on its own. A handle replaces or removes only the rows it wrote, or rows it loaded from a writer that is gone (a closed tab, an earlier page load). Storage failures come back as typed results, never throws: unavailable (also an open that does not answer within openTimeout), blocked, quota, corrupt (with the readable rows as salvage, and the slot's epoch), newer (a row a later release wrote: kept, never reported as damage), closed, limit and failed. Optional limits cap keys per group and bytes per key by refusing writes, never by evicting. store.keys() lists keys, so an app can clear by owner (another viewer at sign-in).

  • An offline session over any binding with binding, status and freeze() (attachYOfflineSession; a YCollabBinding is one, and an app with its own YBinding passes a freeze() over quiesce()). Stages are 'off', 'persist' and 'replay'. At 'persist' every edit is stored as it is made (persistEdits, default true). keep: 'unsynced' stores only while the server lacks edits and deletes them on markSynced(). writeDelay waits for updates to pause. One path serves every return:

  • - a reconnect at the same epoch syncs;
    - a replaced or upgraded room (a new epoch) freezes the client's copy, captures it into the same store, and describes it block by block;
    - so does a copy that a closed tab left at another epoch, or that never synced;
    - an app that syncs before it binds passes the server's epoch to loadYOffline, which loads only the slot at that epoch for it to merge, so the live binding never meets a moved epoch at attach;
    - session.freeze() covers a "replaced" signal that names no new epoch.

    recoverYOfflineEdits feeds an Offline edits panel and, at 'replay', reapplies the blocks nobody else touched as one undo step, at most once across tabs: a slot left at another epoch becomes a capture in one transaction over both stores, so two tabs recovering at once make one capture. It deletes a capture with nothing left only once the fresh document's session reports no unsynced edits, so a replay that has not synced keeps its capture. A replay or a read that fails comes back as that capture's typed error, never a rejection.

    The playground gets a "Collab Y Offline" mode with the panel and a "Simulate replaced" button, plus an e2e spec. y.md documents the layer. DECISIONS.md records D124 to D126.

    Changeset

    .changeset/lexical-y-offline.md (@lexical/y patch, [feature]).

    Test plan

    Before

    $ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline
    No test files found, exiting with code 1
    

    After

    Unit tests run over an in-repo fake IndexedDB (with a fake Web Locks), gc off and on (LEXICAL_Y_GC=1). Each fault and regression test fails on the code before its fix:

  • OfflineFaults.test.ts injects a failure between two specific transactions:

  • - a compaction while a confirmation is queued;
    - a merge that throws in the write queue;
    - a capture the store refuses after the freeze committed more;
    - a request callback that throws inside a transaction.
  • regressions/OfflineReviewFindings.test.ts covers what an independent review and the automated review found:

  • - a sync landing while a keep: 'unsynced' write is in flight;
    - a second recovery deleting a capture whose replay has not synced;
    - a moved or adopting tab removing or moving a live tab's rows (four cases);
    - a capture put again counting its bytes twice;
    - a replay with the caret inside the block it replaces;
    - a replay that throws during recovery;
    - a replay whose update fails under a non-throwing onError;
    - recovery capturing a live tab's rows on every call;
    - a document loaded with nothing unsynced being stored as unsynced;
    - two tabs recovering the same stale slot at once, which replayed it twice;
    - a moved epoch's capture counted against bytesPerKey together with the rows it replaces;
    - a corrupt stale slot that failed recovery with no epoch to clear.

    $ pnpm exec vitest run --project unit packages/lexical-y/src/__tests__/unit/Offline packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts
     ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineFaults.test.ts (4 tests)
     ✓ |unit| packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts (15 tests)
     ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineStore.test.ts (30 tests)
     ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineSession.test.ts (51 tests)
     ✓ |unit| packages/lexical-y/src/__tests__/unit/OfflineLayout3.test.ts (143 tests)
          Tests  243 passed (243)
    $ pnpm exec vitest run --project unit packages/lexical-y           # and with LEXICAL_Y_GC=1
          Tests  25027 passed | 387 expected fail | 154 skipped (25568)
    $ pnpm exec vitest run --project unit-size
          Tests  38 passed (38)
    $ pnpm exec vitest run --project scripts-unit
          Tests  3694 passed (3694)
    $ pnpm exec vitest run --project unit packages/lexical-playground
          Tests  396 passed (396)
    $ pnpm run tsc && pnpm run flow
    Found 0 errors
    

    Browser tests run against Chromium's real IndexedDB and Web Locks (src/__tests__/browser/Offline.test.ts). They cover reopen, compaction, confirm, discard, adopt, two connections, claim-once, damage, a throwing callback, limits, and an upgrade from another connection. They also run a session end to end through a reload and a moved epoch, two tabs where the one whose epoch moved leaves the live one's rows, and two connections recovering one stale slot at once:

    $ pnpm run test-browser                                            # Chromium
     Test Files  83 passed (83)
          Tests  1100 passed | 2 skipped (1102)
    

    The collab Y e2e ran with pnpm run start:y:

    $ pnpm run test-e2e-collab-y-chromium
      36 passed (43.7s)
    

    I also checked the playground by hand in Chromium: online, then disconnected with an edit, then "Simulate replaced". The page reopened at epoch 2 with the edit reapplied, and the panel read "1 reapplied (undo to revert)".

    Not exercised:

  • Firefox and WebKit browser runs. CI's default run is Chromium only; the extended suite (tests-extended.yml) runs the others;

  • a full quota on a real IndexedDB. Chromium's DevTools quota override did not make a write fail in Playwright's ephemeral context, so the fake covers quota.
  • Diff: 9367 lines (+9336 / -31) across 31 files Reviewer: zurfyx Review duration: 229m
    All Vouch review confidence checks passed
    Residual risk 0.27 = Change Risk (0.86) × (1 − Review Confidence (0.69)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.86 · 9367 lines diff across 31 files
    0.86
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.55 · 5 substantive comment(s)
    0.55
    Model 3 · Review Timing & Attention
    Session adequacy: 97% · Reviewer familiarity: 50%
    68%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    37 items
    vercel[bot] vercel[bot] commented on Nov 13, 2026 14:29 UTC
    Bot

    [vc]: #iqbFRRjpamABa4/DYZ5j8un8/tgeF6OC2x2vcFVmvFk=:eyJpc01vbm9yZXBvIjp0cnVlLCJ0eXBlIjoiZ2l0aHViIiwicHJvamVjdHMiOlt7Im5hbWUiOiJsZXhpY2FsIiwicHJvamVjdElkIjoicHJqX01SYU1PMzFlRklrWTYxU0JxcVBEUjJPank4cVAiLCJ2MCI6ZmFsc2UsInJvb3REaXJlY3RvcnkiOiJwYWNrYWdlcy9sZXhpY2FsLXdlYnNpdGUiLCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vZmJvcGVuc291cmNlL2xleGljYWwvRnlyRjV4TTNQMlJVc0pIaHJkOWNlcDFucFVZVSIsInByZXZpZXdVcmwiOiJsZXhpY2FsLWdpdC16dXJmeXgteS1vZmZsaW5lLWZib3BlbnNvdXJjZS52ZXJjZWwuYXBwIiwibmV4dENvbW1pdFN0YXR1cyI6IkRFUExPWUVEIn0seyJuYW1lIjoibGV4aWNhbC1wbGF5Z3JvdW5kIiwicHJvamVjdElkIjoicHJqX2VhODJ2TGo2ODRYelNSZGVPN0pTZDBRTmthd3MiLCJ2MCI6ZmFsc2UsInJvb3REaXJlY3RvcnkiOiJwYWNrYWdlcy9sZXhpY2FsLXBsYXlncm91bmQiLCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vZmJvcGVuc291cmNlL2xleGljYWwtcGxheWdyb3VuZC9BS29UMTJaRVljbUdXZWR5bVVrUjRmenA4VzVrIiwicHJldmlld1VybCI6ImxleGljYWwtcGxheWdyb3VuZC1naXQtenVyZnl4LXktb2ZmbGluZS1mYm9wZW5zb3VyY2UudmVyY2VsLmFwcCIsIm5leHRDb21taXRTdGF0dXMiOiJERVBMT1lFRCJ9XSwicmVxdWVzdFJldmlld1VybCI6Imh0dHBzOi8vdmVyY2VsLmNvbS92ZXJjZWwtYWdlbnQvcmVxdWVzdC1yZXZpZXc/b3duZXI9bWV0YSZyZXBvPWxleGljYWwmcHI9OTg5OSJ9
    The latest updates on your projects. Learn more about Vercel for GitHub.

    | Project | Deployment | Actions | Updated |
    | :--- | :----- | :------ | :------ |
    | <a href="https://vercel.com/fbopensource/lexical"><sup><img src="https://vercel.com/api/www/avatar?projectId=prj_MRaMO31eFIkY61SBqqPDR2Ojy8qP&teamId=team_QNIQyH5DJlqUjeCckcCcBEjE&s=32" width="16" height="16" align="middle" alt="" /></sup></a> lexical | !Ready Ready | Preview | <relative-time datetime="2026-11-13T17:07:12.768Z">Nov 13, 2026 5:07pm UTC</relative-time> |
    | <a href="https://vercel.com/fbopensource/lexical-playground"><sup><img src="https://vercel.com/api/www/avatar?projectId=prj_ea82vLj684XzSRdeO7JSd0QNkaws&teamId=team_QNIQyH5DJlqUjeCckcCcBEjE&s=32" width="16" height="16" align="middle" alt="" /></sup></a> lexical-playground | !Ready Ready | Preview | <relative-time datetime="2026-11-13T17:07:12.768Z">Nov 13, 2026 5:07pm UTC</relative-time> |

    <a href="https://vercel.com/vercel-agent/request-review?owner=meta&repo=lexical&pr=9899" rel="noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://agents-vade-review.vercel.sh/request-review-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://agents-vade-review.vercel.sh/request-review-light.svg"><img src="https://agents-vade-review.vercel.sh/request-review-light.svg" alt="Request Review"></picture></a>

    rootnode-bot[bot] rootnode-bot[bot] commented on Nov 13, 2026 14:29 UTC
    Bot

    AI review status for this pull request.

    | Review status | Updated |
    | :--- | :--- |
    | 🟢 Reviewed (for maintainers only) | <relative-time datetime="2026-11-13T17:34:49Z">Nov 13, 2026, 5:34 PM UTC</relative-time> |

    <!-- codebunny-status:1 r=318341089 p=9899 rv=2 -->

    pkg-pr-new[bot] pkg-pr-new[bot] commented on Nov 13, 2026 14:31 UTC
    Bot

    <details><summary><b>lexical</b></summary><p>

      npm i https://pkg.pr.new/lexical@9899
      


    </p></details>

    <details><summary><b>@lexical/a11y</b></summary><p>

      npm i https://pkg.pr.new/@lexical/a11y@9899
      


    </p></details>

    <details><summary><b>@lexical/clipboard</b></summary><p>

      npm i https://pkg.pr.new/@lexical/clipboard@9899
      


    </p></details>

    <details><summary><b>@lexical/code</b></summary><p>

      npm i https://pkg.pr.new/@lexical/code@9899
      


    </p></details>

    <details><summary><b>@lexical/code-core</b></summary><p>

      npm i https://pkg.pr.new/@lexical/code-core@9899
      


    </p></details>

    <details><summary><b>@lexical/code-prism</b></summary><p>

      npm i https://pkg.pr.new/@lexical/code-prism@9899
      


    </p></details>

    <details><summary><b>@lexical/code-shiki</b></summary><p>

      npm i https://pkg.pr.new/@lexical/code-shiki@9899
      


    </p></details>

    <details><summary><b>@lexical/compiler</b></summary><p>

      npm i https://pkg.pr.new/@lexical/compiler@9899
      


    </p></details>

    <details><summary><b>@lexical/devtools-core</b></summary><p>

      npm i https://pkg.pr.new/@lexical/devtools-core@9899
      


    </p></details>

    <details><summary><b>@lexical/dragon</b></summary><p>

      npm i https://pkg.pr.new/@lexical/dragon@9899
      


    </p></details>

    <details><summary><b>@lexical/eslint-plugin</b></summary><p>

      npm i https://pkg.pr.new/@lexical/eslint-plugin@9899
      


    </p></details>

    <details><summary><b>@lexical/extension</b></summary><p>

      npm i https://pkg.pr.new/@lexical/extension@9899
      


    </p></details>

    <details><summary><b>@lexical/fast-check</b></summary><p>

      npm i https://pkg.pr.new/@lexical/fast-check@9899
      


    </p></details>

    <details><summary><b>@lexical/file</b></summary><p>

      npm i https://pkg.pr.new/@lexical/file@9899
      


    </p></details>

    <details><summary><b>@lexical/hashtag</b></summary><p>

      npm i https://pkg.pr.new/@lexical/hashtag@9899
      


    </p></details>

    <details><summary><b>@lexical/headless</b></summary><p>

      npm i https://pkg.pr.new/@lexical/headless@9899
      


    </p></details>

    <details><summary><b>@lexical/history</b></summary><p>

      npm i https://pkg.pr.new/@lexical/history@9899
      


    </p></details>

    <details><summary><b>@lexical/html</b></summary><p>

      npm i https://pkg.pr.new/@lexical/html@9899
      


    </p></details>

    <details><summary><b>@lexical/internal</b></summary><p>

      npm i https://pkg.pr.new/@lexical/internal@9899
      


    </p></details>

    <details><summary><b>@lexical/link</b></summary><p>

      npm i https://pkg.pr.new/@lexical/link@9899
      


    </p></details>

    <details><summary><b>@lexical/list</b></summary><p>

      npm i https://pkg.pr.new/@lexical/list@9899
      


    </p></details>

    <details><summary><b>@lexical/mark</b></summary><p>

      npm i https://pkg.pr.new/@lexical/mark@9899
      


    </p></details>

    <details><summary><b>@lexical/markdown</b></summary><p>

      npm i https://pkg.pr.new/@lexical/markdown@9899
      


    </p></details>

    <details><summary><b>@lexical/mdast</b></summary><p>

      npm i https://pkg.pr.new/@lexical/mdast@9899
      


    </p></details>

    <details><summary><b>@lexical/offset</b></summary><p>

      npm i https://pkg.pr.new/@lexical/offset@9899
      


    </p></details>

    <details><summary><b>@lexical/overflow</b></summary><p>

      npm i https://pkg.pr.new/@lexical/overflow@9899
      


    </p></details>

    <details><summary><b>@lexical/plain-text</b></summary><p>

      npm i https://pkg.pr.new/@lexical/plain-text@9899
      


    </p></details>

    <details><summary><b>@lexical/react</b></summary><p>

      npm i https://pkg.pr.new/@lexical/react@9899
      


    </p></details>

    <details><summary><b>@lexical/rich-text</b></summary><p>

      npm i https://pkg.pr.new/@lexical/rich-text@9899
      


    </p></details>

    <details><summary><b>@lexical/selection</b></summary><p>

      npm i https://pkg.pr.new/@lexical/selection@9899
      


    </p></details>

    <details><summary><b>@lexical/table</b></summary><p>

      npm i https://pkg.pr.new/@lexical/table@9899
      


    </p></details>

    <details><summary><b>@lexical/tailwind</b></summary><p>

      npm i https://pkg.pr.new/@lexical/tailwind@9899
      


    </p></details>

    <details><summary><b>@lexical/text</b></summary><p>

      npm i https://pkg.pr.new/@lexical/text@9899
      


    </p></details>

    <details><summary><b>@lexical/utils</b></summary><p>

      npm i https://pkg.pr.new/@lexical/utils@9899
      


    </p></details>

    <details><summary><b>@lexical/y</b></summary><p>

      npm i https://pkg.pr.new/@lexical/y@9899
      


    </p></details>

    <details><summary><b>@lexical/yjs</b></summary><p>

      npm i https://pkg.pr.new/@lexical/yjs@9899
      


    </p></details>

    _commit: <a href="https://github.com/meta/lexical/runs/132038171308"><code>cec038b</code></a>_

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 14:50 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1366 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      if (
    +        (loaded === undefined || loaded.state === null) &&
    +        !this.keepUnsyncedOnly
    +      ) {
    +        // A document that did not come from the store: what it holds now
    +        // is stored first, so the slot is the whole document.
    +        if (doc.store.clients.size > 0) {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +          void this.write();
    +        }
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A state confirmed meanwhile holds the batch: it is not queued
    +          // again (it would be stored as edits the server lacks).
    +          if (this.confirmed === null) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    // Moved. Freeze first, synchronously: from here nothing is written to
    +    // the document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    // What a delay held back is stored now.
    +    if (this.timer !== null) {
    +      void this.write();
    +    }
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        throw error;
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          existing.replace(made);

    With the caret in this block's text, replace (no includeChildren) leaves the selection on the old text node, which is then garbage-collected, and the update fails with updateEditor: selection has been lost…. The replay throws and applies nothing (or, with a non-throwing onError, reports applied for a discarded update). Move the selection into made when it is inside existing, for example made.selectEnd() after the swap.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 14:50 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1366 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      if (
    +        (loaded === undefined || loaded.state === null) &&
    +        !this.keepUnsyncedOnly
    +      ) {
    +        // A document that did not come from the store: what it holds now
    +        // is stored first, so the slot is the whole document.
    +        if (doc.store.clients.size > 0) {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +          void this.write();
    +        }
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A state confirmed meanwhile holds the batch: it is not queued
    +          // again (it would be stored as edits the server lacks).
    +          if (this.confirmed === null) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    // Moved. Freeze first, synchronously: from here nothing is written to
    +    // the document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    // What a delay held back is stored now.
    +    if (this.timer !== null) {
    +      void this.write();
    +    }
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        throw error;
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          existing.replace(made);
    +          byId.set(block.id, made);
    +        } else {
    +          // After the nearest block before it that the document holds.
    +          let anchor: LexicalNode | undefined;
    +          for (let i = order.indexOf(block.id) - 1; i >= 0; i--) {
    +            anchor = byId.get(order[i]);
    +            if (anchor !== undefined) {
    +              break;
    +            }
    +          }
    +          if (anchor !== undefined) {
    +            anchor.insertAfter(made);
    +          } else {
    +            // None before it: before the nearest block after it, else (a
    +            // report without the user's order, or none of their blocks
    +            // left) at the end.
    +            const at = order.indexOf(block.id);
    +            for (let i = at + 1; at >= 0 && i < order.length; i++) {
    +              anchor = byId.get(order[i]);
    +              if (anchor !== undefined) {
    +                break;
    +              }
    +            }
    +            if (anchor !== undefined) {
    +              anchor.insertBefore(made);
    +            } else {
    +              $getRoot().append(made);
    +            }
    +          }
    +          byId.set(block.id, made);
    +        }
    +        applied.push(block.id);
    +      }
    +    },
    +    {discrete: true},
    +  );
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  return {applied, notApplied};
    +}
    +
    +/** @experimental One capture of {@link recoverYOfflineEdits}' result. */
    +export interface YOfflineRecovered {
    +  readonly capture: YOfflineCapture;
    +  /** What is left to show, or why the capture could not be read. */
    +  readonly report: YOfflineResult<YOfflineReport>;
    +  /** What the replay stage applied; null when it did not run for this capture. */
    +  readonly replay: YReplayResult | null;
    +}
    +
    +/**
    + * @experimental On a fresh document at the current epoch, after its first
    + * sync: gather what did not sync and, at stage `'replay'`, reapply what is
    + * safe. In order:
    + *
    + * 1. every slot of `key` left at another epoch (a tab that closed before it
    + *    could freeze), or never synced (edits made on this device that never
    + *    reached a server: their base is unknown, so nothing of them is
    + *    replayable), becomes a capture;
    + * 2. each capture is described against the document as it is now;
    + * 3. at stage `'replay'`, each capture this call claims (once, across tabs)
    + *    has its replayable blocks applied as one undo step;
    + * 4. a capture with nothing left to show is deleted (one this call
    + *    replayed, on the next call: until the page syncs, the capture is the
    + *    only stored copy of what was reapplied).
    + *
    + * The result is the Offline edits panel's content. Stage `'off'` returns an
    + * empty list and touches nothing.
    + */
    +export async function recoverYOfflineEdits(input: {
    +  /** The fresh document's binding: active, synced, at `epoch`. */
    +  readonly binding: YOfflineBinding;
    +  readonly store: YOfflineStore | null;
    +  readonly key: string;
    +  /** The epoch the fresh document is at. */
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly config: HeadlessYConfig;
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}): Promise<YOfflineResult<YOfflineRecovered[]>> {
    +  const entry = 'recoverYOfflineEdits';
    +  requireStage(entry, input.stage);
    +  const {binding, config, epoch, key, migrate, stage, store} = input;
    +  if (stage === 'off' || store === null) {
    +    return ok([]);
    +  }
    +  requireOption(
    +    typeof epoch === 'string' && epoch !== '',
    +    `${entry} needs epoch: the epoch the fresh document is at, as a non-empty string.`,
    +  );
    +  const now = input.now ?? Date.now;
    +  // 1. Slots left at another epoch.
    +  const slots = await store.slots(key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  for (const info of slots.value) {
    +    if (info.epoch === epoch) {
    +      continue;
    +    }
    +    // Through a handle, which then owns exactly the rows it read: what a
    +    // tab still open at that epoch writes afterwards is not removed.
    +    const stale = store.slot(key, info.epoch);
    +    const stored = await stale.load();
    +    if (!stored.ok) {
    +      // Left as it is, for the app to salvage or clear.
    +      return stored;
    +    }
    +    if (stored.value !== null && stored.value.hasUnsyncedEdits) {
    +      const saved = await store.putCapture({
    +        base: stored.value.base,
    +        capturedAt: now(),
    +        claimed: false,
    +        differs: false,
    +        epoch: info.epoch,
    +        id: newCaptureId(now()),
    +        json: null,
    +        key,
    +        reason: 'stale',
    +        state: stored.value.state,
    +        text: null,
    +      });
    +      if (!saved.ok) {
    +        return saved;
    +      }
    +    }
    +    const discarded = await stale.discard();
    +    if (!discarded.ok) {
    +      return discarded;
    +    }
    +  }
    +  // 2 to 4.
    +  const captures = await store.captures(key);
    +  if (!captures.ok) {
    +    return captures;
    +  }
    +  const doc = binding.binding.doc;
    +  const describe = (capture: YOfflineCapture) =>
    +    describeYOfflineCapture(capture, {
    +      config,
    +      current: encodeStateAsUpdate(doc),
    +      migrate,
    +    });
    +  const recovered: YOfflineRecovered[] = [];
    +  for (const capture of captures.value) {
    +    let report = describe(capture);
    +    let replay: YReplayResult | null = null;
    +    if (
    +      stage === 'replay' &&
    +      report.ok &&
    +      !capture.claimed &&
    +      binding.status.kind === 'active' &&
    +      report.value.blocks.some(block => block.replayable)
    +    ) {
    +      const claimed = await store.claimCapture(key, capture.id);
    +      if (!claimed.ok) {
    +        return claimed;
    +      }
    +      if (claimed.value) {
    +        // Described again: the claim was awaited.
    +        report = describe(capture);
    +        if (report.ok) {
    +          replay = replayUnsyncedEdits({binding, report: report.value});

    If the replay throws here (see the comment at line 1177), recoverYOfflineEdits rejects after claimCapture has already succeeded, so the capture stays claimed and is never replayed automatically again. Catch the failure and return it as a typed error, and consider releasing the claim.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 14:50 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1366 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      if (
    +        (loaded === undefined || loaded.state === null) &&
    +        !this.keepUnsyncedOnly
    +      ) {
    +        // A document that did not come from the store: what it holds now
    +        // is stored first, so the slot is the whole document.
    +        if (doc.store.clients.size > 0) {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +          void this.write();
    +        }
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A state confirmed meanwhile holds the batch: it is not queued
    +          // again (it would be stored as edits the server lacks).
    +          if (this.confirmed === null) {

    Optional: in keep: 'unsynced' mode, markSynced() sets clearing and leaves confirmed null, so a batch whose append fails while markSynced() runs is queued again and stored after the clear as a lone since row with no base. A per-sync counter checked here would cover both modes.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 14:50 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1366 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      if (
    +        (loaded === undefined || loaded.state === null) &&
    +        !this.keepUnsyncedOnly
    +      ) {
    +        // A document that did not come from the store: what it holds now
    +        // is stored first, so the slot is the whole document.
    +        if (doc.store.clients.size > 0) {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +          void this.write();
    +        }
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A state confirmed meanwhile holds the batch: it is not queued
    +          // again (it would be stored as edits the server lacks).
    +          if (this.confirmed === null) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    // Moved. Freeze first, synchronously: from here nothing is written to
    +    // the document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    // What a delay held back is stored now.
    +    if (this.timer !== null) {
    +      void this.write();
    +    }
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        throw error;

    Optional: this rethrows any headless error other than read only, so describeYOfflineCapture and recoverYOfflineEdits, which return YOfflineResult, can still reject. Return such a failure per capture, or document that these calls can throw.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 14:50 UTC
    Code Review
    packages/lexical-playground/__tests__/e2e/CollabYOffline.spec.mjs:1
    @@ -0,0 +1,141 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// Collab Y offline mode (`@lexical/y/offline`, the playground's "Collab Y
    +// Offline" setting): edits made with no connection are stored on the device,
    +// survive a reload, and sync on reconnect; when the room is replaced (the
    +// panel's "Simulate replaced" plays the server), the page's copy is captured
    +// and the Offline edits panel offers it back, reapplied at once at stage
    +// `replay` and on request at stage `capture`.

    Nit: there is no stage capture; this should say persist.

    rootnode-bot[bot] rootnode-bot[bot] requested changes on Nov 13, 2026 14:50 UTC
    Changes Requested Reviewer

    Thanks for the thorough work here: the store's ownership rules, the write queue and the stage gating read well, and the fault tests pin down several queue races. One defect in the replay should be fixed before this lands; the rest are optional suggestions.

    1. replayUnsyncedEdits throws when the caret is in a block it replaces

    packages/lexical-y/src/internal/OfflineSession.ts:1177 swaps a changed block with existing.replace(made). Without includeChildren, LexicalNode.replace moves a selection point only when the point sits on the replaced element itself, so a caret in the block's text keeps pointing at the old text node. Garbage collection removes that node, and the update fails with updateEditor: selection has been lost because the previously selected nodes have been removed…. A sketch, on the fresh document after a capture that changed b1:

    // $findBlock: any helper that finds the block with blockId 'b1'
    editor.update(() => $findBlock('b1').getFirstDescendant().select(1, 1), {discrete: true});
    replayUnsyncedEdits({binding, report}); // throws; nothing is applied
    

    What follows from it:

  • recoverYOfflineEdits at stage 'replay' rejects instead of returning a YOfflineResult. By then claimCapture has already marked the capture claimed (:1335-1343), so the automatic replay never runs for that capture again.

  • With an editor onError that logs instead of throwing, the update is discarded but applied still lists the blocks, because they are pushed inside the update (:1209), and the panel reports them as reapplied.

  • It is easy to reach. The playground focuses the editor at the end of the document once it is active, so an offline edit to the last paragraph leaves the caret in the block the replay replaces. Clicking into the block you edited and then pressing Reapply does the same. Deleting a block with the caret in it works.
  • Suggested fix: when the selection is inside existing, move it into made (for example made.selectEnd() after the swap). Push to applied only once the update has committed. Have recoverYOfflineEdits return a failed replay as a typed error, not a rejection that leaves the capture claimed. packages/lexical-y/AGENTS.md asks every bug fix to land with a regression test in src/__tests__/unit/regressions/. Here that means a replay with a selection inside the replaced block, which no editor in the current tests has.

    2. Optional: keep: 'unsynced' can store a fragment with no base

    When an append fails, the queue puts its batch back unless a confirmation is queued (OfflineSession.ts:556-561). In 'unsynced' mode, markSynced() sets clearing and never sets confirmed (:644-651). So an append that fails while markSynced() runs (a full quota, say) comes back after the clear as a lone since row. loadYOffline then returns hasUnsyncedEdits: true, base: null, and a document made from that state reads empty until the next local edit replaces the row. A per-sync counter checked when an append fails would cover both modes.

    3. Optional: result-typed calls that can still throw

    describeYOfflineCapture rethrows any headless error other than read only (OfflineSession.ts:938-941), and recoverYOfflineEdits calls it without a catch. The playground wraps the call in try/catch, but the y.md sample (if (recovered.ok) showOfflineEditsPanel(...)) does not. Either return these failures per capture, or say in the JSDoc and in y.md that the call can throw.

    4. Nit

    packages/lexical-playground/__tests__/e2e/CollabYOffline.spec.mjs:14 mentions a stage capture; the stage is 'persist'.

    Automated review (maintainer link)

    <!-- codebunny-pub:1 k=9e0745ad59a5c4d9323523ef3482ec9384d4e22722d3719bb1bb40729a368fb8 -->

    zurfyx zurfyx commented on code on Nov 13, 2026 15:12 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1366 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      if (
    +        (loaded === undefined || loaded.state === null) &&
    +        !this.keepUnsyncedOnly
    +      ) {
    +        // A document that did not come from the store: what it holds now
    +        // is stored first, so the slot is the whole document.
    +        if (doc.store.clients.size > 0) {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +          void this.write();
    +        }
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A state confirmed meanwhile holds the batch: it is not queued
    +          // again (it would be stored as edits the server lacks).
    +          if (this.confirmed === null) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    // Moved. Freeze first, synchronously: from here nothing is written to
    +    // the document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    // What a delay held back is stored now.
    +    if (this.timer !== null) {
    +      void this.write();
    +    }
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        throw error;
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          existing.replace(made);

    Fixed in e0495b466: when the selection is inside the replaced block, the caret moves to the end of the new block (made.selectEnd()). Blocks go to applied only once the update committed (onUpdate), else to notApplied with the new reason 'not-written'. Regression: regressions/OfflineReviewFindings.test.ts, case 6.

    zurfyx zurfyx commented on code on Nov 13, 2026 15:12 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1366 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      if (
    +        (loaded === undefined || loaded.state === null) &&
    +        !this.keepUnsyncedOnly
    +      ) {
    +        // A document that did not come from the store: what it holds now
    +        // is stored first, so the slot is the whole document.
    +        if (doc.store.clients.size > 0) {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +          void this.write();
    +        }
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A state confirmed meanwhile holds the batch: it is not queued
    +          // again (it would be stored as edits the server lacks).
    +          if (this.confirmed === null) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    // Moved. Freeze first, synchronously: from here nothing is written to
    +    // the document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    // What a delay held back is stored now.
    +    if (this.timer !== null) {
    +      void this.write();
    +    }
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        throw error;
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          existing.replace(made);
    +          byId.set(block.id, made);
    +        } else {
    +          // After the nearest block before it that the document holds.
    +          let anchor: LexicalNode | undefined;
    +          for (let i = order.indexOf(block.id) - 1; i >= 0; i--) {
    +            anchor = byId.get(order[i]);
    +            if (anchor !== undefined) {
    +              break;
    +            }
    +          }
    +          if (anchor !== undefined) {
    +            anchor.insertAfter(made);
    +          } else {
    +            // None before it: before the nearest block after it, else (a
    +            // report without the user's order, or none of their blocks
    +            // left) at the end.
    +            const at = order.indexOf(block.id);
    +            for (let i = at + 1; at >= 0 && i < order.length; i++) {
    +              anchor = byId.get(order[i]);
    +              if (anchor !== undefined) {
    +                break;
    +              }
    +            }
    +            if (anchor !== undefined) {
    +              anchor.insertBefore(made);
    +            } else {
    +              $getRoot().append(made);
    +            }
    +          }
    +          byId.set(block.id, made);
    +        }
    +        applied.push(block.id);
    +      }
    +    },
    +    {discrete: true},
    +  );
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  return {applied, notApplied};
    +}
    +
    +/** @experimental One capture of {@link recoverYOfflineEdits}' result. */
    +export interface YOfflineRecovered {
    +  readonly capture: YOfflineCapture;
    +  /** What is left to show, or why the capture could not be read. */
    +  readonly report: YOfflineResult<YOfflineReport>;
    +  /** What the replay stage applied; null when it did not run for this capture. */
    +  readonly replay: YReplayResult | null;
    +}
    +
    +/**
    + * @experimental On a fresh document at the current epoch, after its first
    + * sync: gather what did not sync and, at stage `'replay'`, reapply what is
    + * safe. In order:
    + *
    + * 1. every slot of `key` left at another epoch (a tab that closed before it
    + *    could freeze), or never synced (edits made on this device that never
    + *    reached a server: their base is unknown, so nothing of them is
    + *    replayable), becomes a capture;
    + * 2. each capture is described against the document as it is now;
    + * 3. at stage `'replay'`, each capture this call claims (once, across tabs)
    + *    has its replayable blocks applied as one undo step;
    + * 4. a capture with nothing left to show is deleted (one this call
    + *    replayed, on the next call: until the page syncs, the capture is the
    + *    only stored copy of what was reapplied).
    + *
    + * The result is the Offline edits panel's content. Stage `'off'` returns an
    + * empty list and touches nothing.
    + */
    +export async function recoverYOfflineEdits(input: {
    +  /** The fresh document's binding: active, synced, at `epoch`. */
    +  readonly binding: YOfflineBinding;
    +  readonly store: YOfflineStore | null;
    +  readonly key: string;
    +  /** The epoch the fresh document is at. */
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly config: HeadlessYConfig;
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}): Promise<YOfflineResult<YOfflineRecovered[]>> {
    +  const entry = 'recoverYOfflineEdits';
    +  requireStage(entry, input.stage);
    +  const {binding, config, epoch, key, migrate, stage, store} = input;
    +  if (stage === 'off' || store === null) {
    +    return ok([]);
    +  }
    +  requireOption(
    +    typeof epoch === 'string' && epoch !== '',
    +    `${entry} needs epoch: the epoch the fresh document is at, as a non-empty string.`,
    +  );
    +  const now = input.now ?? Date.now;
    +  // 1. Slots left at another epoch.
    +  const slots = await store.slots(key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  for (const info of slots.value) {
    +    if (info.epoch === epoch) {
    +      continue;
    +    }
    +    // Through a handle, which then owns exactly the rows it read: what a
    +    // tab still open at that epoch writes afterwards is not removed.
    +    const stale = store.slot(key, info.epoch);
    +    const stored = await stale.load();
    +    if (!stored.ok) {
    +      // Left as it is, for the app to salvage or clear.
    +      return stored;
    +    }
    +    if (stored.value !== null && stored.value.hasUnsyncedEdits) {
    +      const saved = await store.putCapture({
    +        base: stored.value.base,
    +        capturedAt: now(),
    +        claimed: false,
    +        differs: false,
    +        epoch: info.epoch,
    +        id: newCaptureId(now()),
    +        json: null,
    +        key,
    +        reason: 'stale',
    +        state: stored.value.state,
    +        text: null,
    +      });
    +      if (!saved.ok) {
    +        return saved;
    +      }
    +    }
    +    const discarded = await stale.discard();
    +    if (!discarded.ok) {
    +      return discarded;
    +    }
    +  }
    +  // 2 to 4.
    +  const captures = await store.captures(key);
    +  if (!captures.ok) {
    +    return captures;
    +  }
    +  const doc = binding.binding.doc;
    +  const describe = (capture: YOfflineCapture) =>
    +    describeYOfflineCapture(capture, {
    +      config,
    +      current: encodeStateAsUpdate(doc),
    +      migrate,
    +    });
    +  const recovered: YOfflineRecovered[] = [];
    +  for (const capture of captures.value) {
    +    let report = describe(capture);
    +    let replay: YReplayResult | null = null;
    +    if (
    +      stage === 'replay' &&
    +      report.ok &&
    +      !capture.claimed &&
    +      binding.status.kind === 'active' &&
    +      report.value.blocks.some(block => block.replayable)
    +    ) {
    +      const claimed = await store.claimCapture(key, capture.id);
    +      if (!claimed.ok) {
    +        return claimed;
    +      }
    +      if (claimed.value) {
    +        // Described again: the claim was awaited.
    +        report = describe(capture);
    +        if (report.ok) {
    +          replay = replayUnsyncedEdits({binding, report: report.value});

    Fixed: recoverYOfflineEdits catches a replay that throws, releases the claim (putCapture with claimed: false), and returns the failure as that capture's typed report, so a later call replays it. Regression: case 6b.

    zurfyx zurfyx commented on code on Nov 13, 2026 15:12 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1366 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      if (
    +        (loaded === undefined || loaded.state === null) &&
    +        !this.keepUnsyncedOnly
    +      ) {
    +        // A document that did not come from the store: what it holds now
    +        // is stored first, so the slot is the whole document.
    +        if (doc.store.clients.size > 0) {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +          void this.write();
    +        }
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A state confirmed meanwhile holds the batch: it is not queued
    +          // again (it would be stored as edits the server lacks).
    +          if (this.confirmed === null) {

    Done: a per-sync counter (markSynced increments it) decides whether a failed batch is queued again, in both modes, instead of the confirmed check.

    zurfyx zurfyx commented on code on Nov 13, 2026 15:12 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1366 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      if (
    +        (loaded === undefined || loaded.state === null) &&
    +        !this.keepUnsyncedOnly
    +      ) {
    +        // A document that did not come from the store: what it holds now
    +        // is stored first, so the slot is the whole document.
    +        if (doc.store.clients.size > 0) {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +          void this.write();
    +        }
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A state confirmed meanwhile holds the batch: it is not queued
    +          // again (it would be stored as edits the server lacks).
    +          if (this.confirmed === null) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    // Moved. Freeze first, synchronously: from here nothing is written to
    +    // the document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    // What a delay held back is stored now.
    +    if (this.timer !== null) {
    +      void this.write();
    +    }
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        throw error;

    Done: describeYOfflineCapture returns any other headless failure as a typed 'failed' result naming the config, so recoverYOfflineEdits returns it per capture and never rejects for it.

    zurfyx zurfyx commented on code on Nov 13, 2026 15:13 UTC
    Code Review
    packages/lexical-playground/__tests__/e2e/CollabYOffline.spec.mjs:1
    @@ -0,0 +1,141 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// Collab Y offline mode (`@lexical/y/offline`, the playground's "Collab Y
    +// Offline" setting): edits made with no connection are stored on the device,
    +// survive a reload, and sync on reconnect; when the room is replaced (the
    +// panel's "Simulate replaced" plays the server), the page's copy is captured
    +// and the Offline edits panel offers it back, reapplied at once at stage
    +// `replay` and on request at stage `capture`.

    Fixed: the header now says stage persist.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 15:50 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1452 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $getSelection,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      // This handle's first row is the whole document, so its later rows
    +      // build only on rows it wrote: another tab may replace the rows it
    +      // loaded. With keep 'unsynced', only when it loaded unsynced rows
    +      // (otherwise its first local edit stores the base and since).
    +      if (
    +        doc.store.clients.size > 0 &&
    +        (!this.keepUnsyncedOnly || this.started)
    +      ) {
    +        this.pending.push(encodeStateAsUpdate(doc));
    +        void this.write();
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.startGeneration++;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        // A sync and a new local edit while this writes start another
    +        // generation: its own start stays due.
    +        const generation = this.startGeneration;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok && generation === this.startGeneration) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        const syncs = this.syncs;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A sync meanwhile covers the batch: it is not queued again (it
    +          // would be stored as edits the server lacks, or, with keep
    +          // 'unsynced', as a row with no base after the clear).
    +          if (syncs === this.syncs) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** Counts markSynced() calls: a batch whose append failed across one is covered. */
    +  private syncs = 0;
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  /** keep 'unsynced': counts starts, so an old one's end clears no new one. */
    +  private startGeneration = 0;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    this.syncs++;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    // Moved. Freeze first, synchronously: from here nothing is written to
    +    // the document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +      this.slot.close();
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    const slot = this.slot;
    +    // What a delay held back is stored, then the writer lock goes (the
    +    // rows become the next handle's to replace).
    +    void (
    +      this.timer !== null || this.writing !== null
    +        ? this.flush()
    +        : Promise.resolve()
    +    ).then(() => {
    +      if (slot !== null) {
    +        slot.close();
    +      }
    +    });
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        return fail({
    +          cause: error,
    +          code: 'failed',
    +          message: `@lexical/y/offline: a state of this capture or the current document could not be read with options.config (${String(
    +            error,
    +          )}); the capture is kept. Check that config holds the editor's nodes and schemaVersion, and offer capture.text meanwhile.`,
    +        });
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report'
    +  /** The editor update failed (the editor's onError has the error). */
    +  | 'not-written';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  // Pushed to `applied` once the update has committed.
    +  const done: string[] = [];
    +  let committed = false;
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          // A caret inside the block would stay on its old nodes, which
    +          // the swap removes: it moves to the end of the new block.
    +          const selection = $getSelection();
    +          const inside =
    +            selection !== null &&
    +            selection
    +              .getNodes()
    +              .some(node => node.is(existing) || existing.isParentOf(node));
    +          existing.replace(made);
    +          if (inside) {
    +            made.selectEnd();
    +          }
    +          byId.set(block.id, made);
    +        } else {
    +          // After the nearest block before it that the document holds.
    +          let anchor: LexicalNode | undefined;
    +          for (let i = order.indexOf(block.id) - 1; i >= 0; i--) {
    +            anchor = byId.get(order[i]);
    +            if (anchor !== undefined) {
    +              break;
    +            }
    +          }
    +          if (anchor !== undefined) {
    +            anchor.insertAfter(made);
    +          } else {
    +            // None before it: before the nearest block after it, else (a
    +            // report without the user's order, or none of their blocks
    +            // left) at the end.
    +            const at = order.indexOf(block.id);
    +            for (let i = at + 1; at >= 0 && i < order.length; i++) {
    +              anchor = byId.get(order[i]);
    +              if (anchor !== undefined) {
    +                break;
    +              }
    +            }
    +            if (anchor !== undefined) {
    +              anchor.insertBefore(made);
    +            } else {
    +              $getRoot().append(made);
    +            }
    +          }
    +          byId.set(block.id, made);
    +        }
    +        done.push(block.id);
    +      }
    +    },
    +    {
    +      discrete: true,
    +      onUpdate: () => {
    +        committed = true;
    +      },
    +    },
    +  );
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  if (committed) {
    +    for (const id of done) {
    +      applied.push(id);
    +    }
    +  } else {
    +    for (const id of done) {
    +      notApplied.push({id, reason: 'not-written'});
    +    }
    +  }
    +  return {applied, notApplied};
    +}
    +
    +/** @experimental One capture of {@link recoverYOfflineEdits}' result. */
    +export interface YOfflineRecovered {
    +  readonly capture: YOfflineCapture;
    +  /** What is left to show, or why the capture could not be read. */
    +  readonly report: YOfflineResult<YOfflineReport>;
    +  /** What the replay stage applied; null when it did not run for this capture. */
    +  readonly replay: YReplayResult | null;
    +}
    +
    +/**
    + * @experimental On a fresh document at the current epoch, after its first
    + * sync: gather what did not sync and, at stage `'replay'`, reapply what is
    + * safe. In order:
    + *
    + * 1. every slot of `key` left at another epoch (a tab that closed before it
    + *    could freeze), or never synced (edits made on this device that never
    + *    reached a server: their base is unknown, so nothing of them is
    + *    replayable), becomes a capture;
    + * 2. each capture is described against the document as it is now;
    + * 3. at stage `'replay'`, each capture this call claims (once, across tabs)
    + *    has its replayable blocks applied as one undo step;
    + * 4. a capture with nothing left to show is deleted once the server holds
    + *    the document: only with `session`, the document's offline session,
    + *    reporting no unsynced edits (after its `markSynced()`). Without it,
    + *    or while the document holds edits the server lacks (a replay that has
    + *    not synced), such a capture is returned with no blocks, for the panel
    + *    to dismiss: until the server holds what was reapplied, the capture may
    + *    be its only stored copy.
    + *
    + * The result is the Offline edits panel's content. Stage `'off'` returns an
    + * empty list and touches nothing.
    + */
    +export async function recoverYOfflineEdits(input: {
    +  /** The fresh document's binding: active, synced, at `epoch`. */
    +  readonly binding: YOfflineBinding;
    +  readonly store: YOfflineStore | null;
    +  readonly key: string;
    +  /** The epoch the fresh document is at. */
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly config: HeadlessYConfig;
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +  /**
    +   * The fresh document's offline session: with it, a capture the server
    +   * already holds (its session reports no unsynced edits) is deleted.
    +   */
    +  readonly session?: YOfflineSession;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}): Promise<YOfflineResult<YOfflineRecovered[]>> {
    +  const entry = 'recoverYOfflineEdits';
    +  requireStage(entry, input.stage);
    +  const {binding, config, epoch, key, migrate, stage, store} = input;
    +  if (stage === 'off' || store === null) {
    +    return ok([]);
    +  }
    +  requireOption(
    +    typeof epoch === 'string' && epoch !== '',
    +    `${entry} needs epoch: the epoch the fresh document is at, as a non-empty string.`,
    +  );
    +  const now = input.now ?? Date.now;
    +  // 1. Slots left at another epoch.
    +  const slots = await store.slots(key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  for (const info of slots.value) {
    +    if (info.epoch === epoch) {
    +      continue;
    +    }
    +    // Through a handle, which then owns exactly the rows it read: what a
    +    // tab still open at that epoch writes afterwards is not removed.
    +    const stale = store.slot(key, info.epoch);
    +    const stored = await stale.load();
    +    if (!stored.ok) {
    +      // Left as it is, for the app to salvage or clear.
    +      return stored;
    +    }
    +    if (stored.value !== null && stored.value.hasUnsyncedEdits) {
    +      const saved = await store.putCapture({
    +        base: stored.value.base,
    +        capturedAt: now(),
    +        claimed: false,
    +        differs: false,
    +        epoch: info.epoch,
    +        id: newCaptureId(now()),
    +        json: null,
    +        key,
    +        reason: 'stale',
    +        state: stored.value.state,
    +        text: null,
    +      });
    +      if (!saved.ok) {
    +        return saved;
    +      }
    +    }
    +    const discarded = await stale.discard();
    +    if (!discarded.ok) {
    +      return discarded;
    +    }
    +  }
    +  // 2 to 4.
    +  const captures = await store.captures(key);
    +  if (!captures.ok) {
    +    return captures;
    +  }
    +  const doc = binding.binding.doc;
    +  const describe = (capture: YOfflineCapture) =>
    +    describeYOfflineCapture(capture, {
    +      config,
    +      current: encodeStateAsUpdate(doc),
    +      migrate,
    +    });
    +  const recovered: YOfflineRecovered[] = [];
    +  for (const capture of captures.value) {
    +    let report = describe(capture);
    +    let replay: YReplayResult | null = null;
    +    if (
    +      stage === 'replay' &&
    +      report.ok &&
    +      !capture.claimed &&
    +      binding.status.kind === 'active' &&
    +      report.value.blocks.some(block => block.replayable)
    +    ) {
    +      const claimed = await store.claimCapture(key, capture.id);
    +      if (!claimed.ok) {
    +        return claimed;
    +      }
    +      if (claimed.value) {
    +        // Described again: the claim was awaited.
    +        report = describe(capture);
    +        if (report.ok) {
    +          try {
    +            replay = replayUnsyncedEdits({binding, report: report.value});

    Optional: when the editor's onError does not rethrow, a failed update comes back here as 'not-written' with nothing applied, but the capture stays claimed, so later calls never replay it automatically (a probe: a second call after the fault cleared returned replay: null). Releasing the claim when nothing was applied and a block is 'not-written', as the catch below does, would cover it.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 15:50 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1452 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $getSelection,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      // This handle's first row is the whole document, so its later rows
    +      // build only on rows it wrote: another tab may replace the rows it
    +      // loaded. With keep 'unsynced', only when it loaded unsynced rows
    +      // (otherwise its first local edit stores the base and since).
    +      if (
    +        doc.store.clients.size > 0 &&
    +        (!this.keepUnsyncedOnly || this.started)
    +      ) {
    +        this.pending.push(encodeStateAsUpdate(doc));
    +        void this.write();
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.startGeneration++;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        // A sync and a new local edit while this writes start another
    +        // generation: its own start stays due.
    +        const generation = this.startGeneration;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok && generation === this.startGeneration) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        const syncs = this.syncs;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A sync meanwhile covers the batch: it is not queued again (it
    +          // would be stored as edits the server lacks, or, with keep
    +          // 'unsynced', as a row with no base after the clear).
    +          if (syncs === this.syncs) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** Counts markSynced() calls: a batch whose append failed across one is covered. */
    +  private syncs = 0;
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  /** keep 'unsynced': counts starts, so an old one's end clears no new one. */
    +  private startGeneration = 0;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    this.syncs++;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    // Moved. Freeze first, synchronously: from here nothing is written to
    +    // the document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +      this.slot.close();
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    const slot = this.slot;
    +    // What a delay held back is stored, then the writer lock goes (the
    +    // rows become the next handle's to replace).
    +    void (
    +      this.timer !== null || this.writing !== null
    +        ? this.flush()
    +        : Promise.resolve()
    +    ).then(() => {
    +      if (slot !== null) {
    +        slot.close();
    +      }
    +    });
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        return fail({
    +          cause: error,
    +          code: 'failed',
    +          message: `@lexical/y/offline: a state of this capture or the current document could not be read with options.config (${String(
    +            error,
    +          )}); the capture is kept. Check that config holds the editor's nodes and schemaVersion, and offer capture.text meanwhile.`,
    +        });
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report'
    +  /** The editor update failed (the editor's onError has the error). */
    +  | 'not-written';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  // Pushed to `applied` once the update has committed.
    +  const done: string[] = [];
    +  let committed = false;
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          // A caret inside the block would stay on its old nodes, which
    +          // the swap removes: it moves to the end of the new block.
    +          const selection = $getSelection();
    +          const inside =
    +            selection !== null &&
    +            selection
    +              .getNodes()
    +              .some(node => node.is(existing) || existing.isParentOf(node));
    +          existing.replace(made);
    +          if (inside) {
    +            made.selectEnd();
    +          }
    +          byId.set(block.id, made);
    +        } else {
    +          // After the nearest block before it that the document holds.
    +          let anchor: LexicalNode | undefined;
    +          for (let i = order.indexOf(block.id) - 1; i >= 0; i--) {
    +            anchor = byId.get(order[i]);
    +            if (anchor !== undefined) {
    +              break;
    +            }
    +          }
    +          if (anchor !== undefined) {
    +            anchor.insertAfter(made);
    +          } else {
    +            // None before it: before the nearest block after it, else (a
    +            // report without the user's order, or none of their blocks
    +            // left) at the end.
    +            const at = order.indexOf(block.id);
    +            for (let i = at + 1; at >= 0 && i < order.length; i++) {
    +              anchor = byId.get(order[i]);
    +              if (anchor !== undefined) {
    +                break;
    +              }
    +            }
    +            if (anchor !== undefined) {
    +              anchor.insertBefore(made);
    +            } else {
    +              $getRoot().append(made);
    +            }
    +          }
    +          byId.set(block.id, made);
    +        }
    +        done.push(block.id);
    +      }
    +    },
    +    {
    +      discrete: true,
    +      onUpdate: () => {
    +        committed = true;
    +      },
    +    },
    +  );
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  if (committed) {
    +    for (const id of done) {
    +      applied.push(id);
    +    }
    +  } else {
    +    for (const id of done) {
    +      notApplied.push({id, reason: 'not-written'});
    +    }
    +  }
    +  return {applied, notApplied};
    +}
    +
    +/** @experimental One capture of {@link recoverYOfflineEdits}' result. */
    +export interface YOfflineRecovered {
    +  readonly capture: YOfflineCapture;
    +  /** What is left to show, or why the capture could not be read. */
    +  readonly report: YOfflineResult<YOfflineReport>;
    +  /** What the replay stage applied; null when it did not run for this capture. */
    +  readonly replay: YReplayResult | null;
    +}
    +
    +/**
    + * @experimental On a fresh document at the current epoch, after its first
    + * sync: gather what did not sync and, at stage `'replay'`, reapply what is
    + * safe. In order:
    + *
    + * 1. every slot of `key` left at another epoch (a tab that closed before it
    + *    could freeze), or never synced (edits made on this device that never
    + *    reached a server: their base is unknown, so nothing of them is
    + *    replayable), becomes a capture;
    + * 2. each capture is described against the document as it is now;
    + * 3. at stage `'replay'`, each capture this call claims (once, across tabs)
    + *    has its replayable blocks applied as one undo step;
    + * 4. a capture with nothing left to show is deleted once the server holds
    + *    the document: only with `session`, the document's offline session,
    + *    reporting no unsynced edits (after its `markSynced()`). Without it,
    + *    or while the document holds edits the server lacks (a replay that has
    + *    not synced), such a capture is returned with no blocks, for the panel
    + *    to dismiss: until the server holds what was reapplied, the capture may
    + *    be its only stored copy.
    + *
    + * The result is the Offline edits panel's content. Stage `'off'` returns an
    + * empty list and touches nothing.
    + */
    +export async function recoverYOfflineEdits(input: {
    +  /** The fresh document's binding: active, synced, at `epoch`. */
    +  readonly binding: YOfflineBinding;
    +  readonly store: YOfflineStore | null;
    +  readonly key: string;
    +  /** The epoch the fresh document is at. */
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly config: HeadlessYConfig;
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +  /**
    +   * The fresh document's offline session: with it, a capture the server
    +   * already holds (its session reports no unsynced edits) is deleted.
    +   */
    +  readonly session?: YOfflineSession;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}): Promise<YOfflineResult<YOfflineRecovered[]>> {
    +  const entry = 'recoverYOfflineEdits';
    +  requireStage(entry, input.stage);
    +  const {binding, config, epoch, key, migrate, stage, store} = input;
    +  if (stage === 'off' || store === null) {
    +    return ok([]);
    +  }
    +  requireOption(
    +    typeof epoch === 'string' && epoch !== '',
    +    `${entry} needs epoch: the epoch the fresh document is at, as a non-empty string.`,
    +  );
    +  const now = input.now ?? Date.now;
    +  // 1. Slots left at another epoch.
    +  const slots = await store.slots(key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  for (const info of slots.value) {
    +    if (info.epoch === epoch) {
    +      continue;
    +    }
    +    // Through a handle, which then owns exactly the rows it read: what a
    +    // tab still open at that epoch writes afterwards is not removed.
    +    const stale = store.slot(key, info.epoch);
    +    const stored = await stale.load();
    +    if (!stored.ok) {
    +      // Left as it is, for the app to salvage or clear.
    +      return stored;
    +    }
    +    if (stored.value !== null && stored.value.hasUnsyncedEdits) {
    +      const saved = await store.putCapture({
    +        base: stored.value.base,
    +        capturedAt: now(),
    +        claimed: false,
    +        differs: false,
    +        epoch: info.epoch,
    +        id: newCaptureId(now()),
    +        json: null,
    +        key,
    +        reason: 'stale',
    +        state: stored.value.state,
    +        text: null,
    +      });
    +      if (!saved.ok) {
    +        return saved;
    +      }
    +    }
    +    const discarded = await stale.discard();

    Optional: discard() keeps a live tab's rows, which is right, but then each later call captures them again: three calls made three captures in a probe over the fake IndexedDB, and the playground calls recover() after every Dismiss and Reapply. Capturing only the rows whose writer is gone would leave the rest for that tab's own capture.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 15:50 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1452 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $getSelection,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      // This handle's first row is the whole document, so its later rows
    +      // build only on rows it wrote: another tab may replace the rows it
    +      // loaded. With keep 'unsynced', only when it loaded unsynced rows
    +      // (otherwise its first local edit stores the base and since).
    +      if (
    +        doc.store.clients.size > 0 &&
    +        (!this.keepUnsyncedOnly || this.started)
    +      ) {
    +        this.pending.push(encodeStateAsUpdate(doc));

    Optional: for a document loaded with nothing unsynced, this whole-document row is a since row, so the next load reports hasUnsyncedEdits: true with no edit (two offline reloads in a probe). When loaded.hasUnsyncedEdits is false, the document equals the base, so this row could be stored as a base (slot.confirm(state)).

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 15:50 UTC
    Code Review
    packages/lexical-website/docs/collaboration/y.md:1
    @@ -1267,6 +1269,278 @@ deleted while its changes did not reach the server (offline, a dropped
     connection, a reload from local storage), and that client then differs from
     everyone else for good, with no warning (fixed in yrs 0.26.0).
     
    +## Offline: local persistence and edits that did not sync
    +
    +`@lexical/y/offline` (experimental) keeps a document on the device and
    +looks after the edits a server never took. It has two layers, and an app can
    +use the first alone:
    +
    +- a **local store** for Yjs 14 documents on IndexedDB, keyed by a document
    +  key your app chooses and the **epoch** (generation) the document was made
    +  against. No IndexedDB provider exists for Yjs 14 (`y-indexeddb` imports
    +  Yjs 13), and none keys by epoch or reports quota and corruption, so the
    +  store is part of this package. It adds no dependency;
    +- an **offline session** attached to a binding: it stores edits as they are
    +  made, lets them sync on a reconnect at the same epoch, and on a moved epoch
    +  freezes the document (`binding.freeze()`), stores it with its base, and
    +  reports what changed block by block (`describeUnsyncedEdits`), with a
    +  replay of the blocks nobody else touched.
    +
    +One path serves every way a client comes back. A **reconnect** at the same
    +epoch syncs the stored document. A room that was **replaced** (reloaded,
    +restored) or **upgraded** (migrated to a newer layout by its server) has a
    +new epoch, so the client's copy is frozen, captured into the same store, and
    +described against the new room; the same happens to a copy a closed tab
    +left behind. Nothing stored at another epoch is ever merged.
    +
    +An epoch is whatever your server names a document's incarnation with: a
    +generation from `@lexical/y/server` (`getYGeneration`), or a relay's counter
    +that it bumps when it reloads or upgrades a document. It is an opaque string
    +here (`String(epoch)` for a number); two are compared, never parsed.
    +
    +### Start here
    +
    +1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`:
    +   once per page. A browser without IndexedDB returns `'unavailable'`.
    +2. `const loaded = await loadYOffline({store, key})`, and create the
    +   document from `loaded.state` when there is one.
    +3. `const session = attachYOfflineSession({binding, store, key, epoch:
    +   loaded.epoch, loaded, stage, onError})`. At `'persist'` and `'replay'`
    +   every edit is stored as it is made.
    +4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    +   before the provider syncs, on every connect and reconnect, and when the
    +   server says the room was replaced or upgraded. `'same'`: sync. `'moved'`:
    +   the document is frozen and captured.
    +5. `session.markSynced()` when the server holds everything the document
    +   holds.
    +6. On the document the page syncs (a fresh one after a `'moved'`):
    +   `await recoverYOfflineEdits({...})`, whose result is the Offline edits
    +   panel.
    +
    +Whether the editor is editable before the server answers (offline editing)
    +is your app's choice, made when it binds: `synced: true` on a stored
    +document makes it editable at once; `synced: false` waits for the
    +provider's sync, and the store still keeps what is typed after it.
    +
    +```ts
    +import {createYBinding, createYDoc} from '@lexical/y';
    +import {
    +  attachYOfflineSession,
    +  loadYOffline,
    +  openYOfflineStore,
    +  recoverYOfflineEdits,
    +  type YOfflineStage,
    +} from '@lexical/y/offline';
    +
    +// The rollout stage, from your feature flag: 'off', 'persist' or 'replay'.
    +const stage: YOfflineStage = 'replay';
    +const key = documentId;
    +
    +const opened = await openYOfflineStore({
    +  idb: {indexedDB: globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange},
    +});
    +const store = opened.ok ? opened.value : null; // null: tell the user, run at 'off'
    +const loaded = store === null ? null : await loadYOffline({key, store});
    +const stored = loaded !== null && loaded.ok ? loaded.value : undefined;
    +
    +// Start from the stored document; editable at once here (your choice).
    +const doc = createYDoc(stored?.state);
    +const binding = createYBinding(editor, {
    +  doc,
    +  onStatus: showStatus,
    +  schemaVersion: SCHEMA_VERSION,
    +  synced: stored != null && stored.state !== null,
    +});
    +const session = attachYOfflineSession({
    +  binding,
    +  epoch: stored?.epoch ?? null,
    +  key,
    +  loaded: stored,
    +  onError: error => showNotSavedOnThisDevice(error.message),
    +  stage: store === null ? 'off' : stage,
    +  store,
    +});
    +
    +// The server names its epoch (in your handshake, before any sync message,
    +// and again in a "replaced" event):
    +async function onServerEpoch(epoch: string) {
    +  const verdict = await session.serverEpoch(epoch);
    +  if (verdict.kind === 'moved') {
    +    // This document is frozen and stored as a capture. Never sync it: stop
    +    // its provider, open a fresh document at `epoch`, and recover there.
    +    openFreshDocument(epoch);
    +  } else {
    +    provider.connect(); // 'same' (or 'off': do what the app did before)
    +  }
    +}
    +provider.on('sync', () => binding.markSynced());
    +// When the server holds everything (an acknowledgement of every update):
    +provider.on('saved', () => session.markSynced());
    +
    +// On the fresh document, after its first sync:
    +const recovered = await recoverYOfflineEdits({
    +  binding: freshBinding,
    +  config: headlessConfig, // your nodes and schemaVersion, as for editYState
    +  epoch,
    +  key,
    +  session: freshSession, // lets it delete what the server already holds
    +  stage,
    +  store,
    +});
    +if (recovered.ok) showOfflineEditsPanel(recovered.value);
    +```
    +
    +### Stages
    +
    +Every call that acts takes the stage, so one flag rolls the feature out:
    +
    +| Stage       | The session                                                                                  | `recoverYOfflineEdits`                                                              |
    +| ----------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
    +| `'off'`     | Adds no listener, stores nothing; `serverEpoch` answers `{kind: 'off'}`                      | Returns an empty list and touches nothing                                           |
    +| `'persist'` | Stores every edit as it is made, and freezes and stores a capture when the epoch moved       | Lists each capture with its report: the panel's preview, Copy and Reapply per block |
    +| `'replay'`  | The same                                                                                     | Also applies each capture's replayable blocks, once across tabs, as one undo step   |
    +
    +Three options shape what `'persist'` stores:
    +
    +- `persistEdits` (default `true`): `false` stores only captures (a moved
    +  epoch while the tab is open), and adds no `update` listener;
    +- `keep` (default `'document'`): the whole document always, so the page can
    +  open it with no connection. `'unsynced'` stores only while the document
    +  holds edits the server lacks: nothing while synced, the base and what came
    +  since from the first local edit, deleted by `markSynced()`;
    +- `writeDelay` (default `0`): milliseconds to wait for updates to pause
    +  before storing them (at least every ten delays while they do not).
    +  `flush()` stores at once; call it on `pagehide`.
    +
    +An app that builds its own `YBinding` (not `createYBinding` or
    +`YCollabExtension`) passes `{binding, status, freeze}` as the binding
    +(`YOfflineBinding`): its `freeze()` stops the binding and returns its local
    +edits (`binding.quiesce()` has them), and `status` reads `{kind: 'active'}`
    +while the room is editable.
    +
    +### What is stored
    +
    +A slot per `(key, epoch)` holds a **base** (the state the server is known to
    +hold, written by `markSynced()`) and the updates **since**. The document is
    +their merge; `hasUnsyncedEdits` is true while anything is stored since the
    +base. Rows are written one per update (updates that arrive while a write is
    +in flight go in one row), compacted into one after
    +`Y_OFFLINE_DEFAULTS.compactAfter` (64), and replaced by a new base at each
    +`markSynced()`. A document that never synced is stored under a null epoch and
    +moves to the first epoch the server names.
    +
    +A key is any non-empty string your app chooses; put what separates
    +documents in it (`viewer|document|space`). `store.keys()` lists every key
    +stored, so an app clears another viewer's documents at sign-in with
    +`store.clear(key, {captures: true})` for each key that is not theirs.
    +`openYOfflineStore`'s `limits` cap the store by refusing writes, never by
    +evicting: `keys` per group (`group: key => key.split('|')[0]` counts per
    +viewer) and `bytesPerKey` (rows and captures). A write past one answers
    +`'limit'`, with `error.limit` naming which. Each connection counts a key's
    +bytes from its last read of the key plus what it wrote since, so tabs
    +writing at once can pass `bytesPerKey` by what the others wrote since.
    +
    +Two tabs on one key write side by side. Each writing handle holds a Web
    +Lock (`openYOfflineStore`'s `locks`, `navigator.locks` by default) and
    +writes rows under its own id, the first of them the whole document, so its
    +later rows build only on rows it wrote. A handle replaces or removes the
    +rows it wrote and the rows it loaded whose writer is gone (a closed tab, an
    +earlier page load), never a live tab's. The tabs do not exchange edits
    +through the store; a later load holds both. Without Web Locks (`locks:
    +null`) every other handle counts as live, so earlier page loads' rows stay
    +until the app clears them.
    +
    +Nothing here throws for a storage failure. Every call returns
    +`{ok: true, value}` or `{ok: false, error}`, and `error.code` says what
    +happened:
    +
    +| Code            | When                                                              | What to do                                                                                             |
    +| --------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
    +| `'unavailable'` | No IndexedDB (a private window, Node without a fake), or the open did not answer within `openTimeout` (10 s) | Run at stage `'off'` and tell the user edits live in this tab only                                     |
    +| `'blocked'`     | Another tab holds an older version of the database                | Ask the user to close the other tabs, then open the store again                                        |
    +| `'quota'`       | The origin's storage is full                                      | Tell the user edits are not saved on this device; editing goes on and the next write stores everything |
    +| `'corrupt'`     | A stored row is not what the store wrote, or does not decode      | Offer `error.salvage.state` (the readable rows), then `store.clear(key, {epoch, captures: false})`     |
    +| `'closed'`      | `store.close()` ran, or another tab deleted the database          | Open a new store                                                                                       |
    +| `'limit'`       | The write would pass one of the store's `limits` (`error.limit`)  | Tell the user edits are not saved on this device, or clear documents no longer needed                  |
    +| `'failed'`      | Any other IndexedDB failure (`error.cause`)                       | Retry, or tell the user                                                                                |
    +
    +The session passes each failure to `onError` and keeps what it could not
    +write queued, so nothing typed is dropped from the page.
    +`store.clear(key, {captures})` deletes a document's slots (and its captures
    +with `captures: true`).
    +
    +### The base, and what counts as unsynced
    +
    +A capture's report compares three documents: the user's, the **base** their
    +edits were made against, and the current one. The session's base is the
    +document at the last `markSynced()`: call it whenever the server is known to
    +hold everything the document holds (an acknowledgement of every update,
    +where your provider counts them; with a relay that acknowledges nothing,
    +the provider's sync on connect, which leaves a window: an edit sent in that
    +sync that never arrived is in the base, so a later capture does not list
    +it). A base that is older than it could be costs nothing but precision: an edit that did reach the server is in
    +the current document as the user had it, and such blocks are left out of the
    +report; a block someone else changed since is not replayable either way.
    +Without any `markSynced()` the base is unknown, the report judges against the
    +current document, and nothing is replayable.
    +
    +### The report and the replay
    +
    +`recoverYOfflineEdits` first turns every slot left at another epoch (a tab
    +that closed before it could freeze), or never synced (its base is unknown,
    +so its blocks are listed but not replayed), into a capture, then describes each
    +capture (`describeYOfflineCapture`, which is `describeUnsyncedEdits` without
    +the blocks the document already holds as the user had them). A capture with
    +nothing left to show is deleted once the server holds the document: pass
    +`session` (the fresh document's offline session), and a later call deletes
    +it when that session reports no unsynced edits (after its `markSynced()`).
    +Until then, or without `session`, it comes back with no blocks for the
    +panel to dismiss: a replay that has not synced exists only in this page,
    +and the capture may be its only stored copy. A block
    +the user only moved is in no entry; the report's `orderDiffers` says so, and
    +such a capture is kept until the user dismisses it (a move is not replayed). With
    +`BlockIdExtension` blocks are matched by id; without it they are matched by
    +position and nothing is replayable, so the panel offers Copy only.
    +
    +`replayUnsyncedEdits({binding, report, only})` applies the replayable blocks
    +in one editor update, which the binding writes as one undo step: a changed
    +block replaces the current one, an added block goes after the nearest block
    +before it that the document holds (before the nearest after it when none is
    +left), a deleted block is removed. Call it outside an editor update. Each block is
    +checked again against the editor as it is at that moment, so a block someone
    +changed after the report was made comes back in `notApplied`
    +(`'changed-since'`) instead of being overwritten. `only` limits it to the
    +ids given, for a Reapply button.
    +
    +### Layouts
    +
    +The store keeps bytes, so it holds a document of any layout. A report reads
    +its states with this release, which refuses one below `MIN_LAYOUT`: pass
    +`migrate` (`state => migrateYState(state, steps).state` with your steps from
    +`@lexical/y/migrate`) to `describeYOfflineCapture` or `recoverYOfflineEdits`
    +and such a base or capture is read after migrating. Without it, a base below
    +the floor is reported as gone (`baseAvailable: false`, nothing replayable)
    +and a capture that has no editor JSON returns an error that names `migrate`.
    +
    +### Limits of the offline layer
    +
    +- **A replayed block replaces the current one.** Formatting, comments and
    +  nested content come from the user's copy of the block; an edit a
    +  collaborator makes to that block in the instant between the check and the
    +  write is not merged into it (the check runs in the same task as the write,
    +  so this needs their update to arrive inside the editor update).
    +- **A node that serializes differently in a live editor than in a headless
    +  read** (a decorator whose nested editor fills in an empty paragraph
    +  locally) is never replayed: the check against the base fails
    +  (`'changed-since'`). Its text is in the panel.
    +- **A tab left open at an earlier epoch while another tab recovers** is
    +  captured twice: once from its stored slot and once when it freezes. The

    Nit: on this head the tab's slot is captured once per recoverYOfflineEdits call while that tab is open, not only twice.

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 13, 2026 15:50 UTC
    Approved Reviewer

    This looks good, and thanks for the quick turnaround on the earlier review. A replay now moves the caret out of a block it replaces instead of failing Lexical's selection invariant, and a replay that throws releases its claim. The new cases in packages/lexical-y/src/__tests__/unit/regressions/OfflineReviewFindings.test.ts cover both. The suggestions below are optional and non-blocking.

    Optional suggestions

    1. Release the claim after a 'not-written' replay (packages/lexical-y/src/internal/OfflineSession.ts, around line 1410). When an editor's onError does not rethrow, a failed update comes back as 'not-written', but the capture stays claimed, so later recoverYOfflineEdits calls never replay it automatically. Reapply still works. Releasing the claim when nothing was applied, as the catch just below does, would cover this. A regression test with a node transform that throws and an onError that records would pin it, following packages/lexical-y/AGENTS.md, which asks for a test in src/__tests__/unit/regressions/ with every fix.
    2. Don't capture a live tab's rows again (OfflineSession.ts, step 1 of recoverYOfflineEdits, around line 1373). discard() correctly keeps the rows of a tab still open at the old epoch, but that means every later call captures them again: three calls made three captures in a quick test over the fake IndexedDB. The playground calls recover() after every Dismiss and Reapply, so a dismissed entry comes back. Capturing only the rows whose writer is gone would leave the rest for that tab's own capture. It would also make the "captured twice" sentence in packages/lexical-website/docs/collaboration/y.md (Limits of the offline layer) accurate.
    3. Store a clean loaded document's first row as a base (OfflineSession.ts, line 375). For a document loaded with nothing unsynced, the whole-document first row is a since row, so the next offline reload reports hasUnsyncedEdits: true with no edit and keeps another full copy until a sync. When loaded.hasUnsyncedEdits is false, the document equals the base, so slot.confirm(state) would keep the "first row is the whole document" property without that side effect.

    The rest I checked holds up. The Flow declarations match the TypeScript exports, the changeset follows CONTRIBUTING.md, and the tree-shaking test keeps nothing from the new entry.

    Automated review (maintainer link)

    <!-- codebunny-pub:1 k=295e09a5e6a64dbd25a8e53a6c5cdf67dd943262f63726e8933aa11c6111ba24 -->

    zurfyx zurfyx commented on code on Nov 13, 2026 16:12 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1452 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $getSelection,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      // This handle's first row is the whole document, so its later rows
    +      // build only on rows it wrote: another tab may replace the rows it
    +      // loaded. With keep 'unsynced', only when it loaded unsynced rows
    +      // (otherwise its first local edit stores the base and since).
    +      if (
    +        doc.store.clients.size > 0 &&
    +        (!this.keepUnsyncedOnly || this.started)
    +      ) {
    +        this.pending.push(encodeStateAsUpdate(doc));
    +        void this.write();
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.startGeneration++;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        // A sync and a new local edit while this writes start another
    +        // generation: its own start stays due.
    +        const generation = this.startGeneration;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok && generation === this.startGeneration) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        const syncs = this.syncs;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A sync meanwhile covers the batch: it is not queued again (it
    +          // would be stored as edits the server lacks, or, with keep
    +          // 'unsynced', as a row with no base after the clear).
    +          if (syncs === this.syncs) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** Counts markSynced() calls: a batch whose append failed across one is covered. */
    +  private syncs = 0;
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  /** keep 'unsynced': counts starts, so an old one's end clears no new one. */
    +  private startGeneration = 0;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    this.syncs++;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    // Moved. Freeze first, synchronously: from here nothing is written to
    +    // the document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +      this.slot.close();
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    const slot = this.slot;
    +    // What a delay held back is stored, then the writer lock goes (the
    +    // rows become the next handle's to replace).
    +    void (
    +      this.timer !== null || this.writing !== null
    +        ? this.flush()
    +        : Promise.resolve()
    +    ).then(() => {
    +      if (slot !== null) {
    +        slot.close();
    +      }
    +    });
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        return fail({
    +          cause: error,
    +          code: 'failed',
    +          message: `@lexical/y/offline: a state of this capture or the current document could not be read with options.config (${String(
    +            error,
    +          )}); the capture is kept. Check that config holds the editor's nodes and schemaVersion, and offer capture.text meanwhile.`,
    +        });
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report'
    +  /** The editor update failed (the editor's onError has the error). */
    +  | 'not-written';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  // Pushed to `applied` once the update has committed.
    +  const done: string[] = [];
    +  let committed = false;
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          // A caret inside the block would stay on its old nodes, which
    +          // the swap removes: it moves to the end of the new block.
    +          const selection = $getSelection();
    +          const inside =
    +            selection !== null &&
    +            selection
    +              .getNodes()
    +              .some(node => node.is(existing) || existing.isParentOf(node));
    +          existing.replace(made);
    +          if (inside) {
    +            made.selectEnd();
    +          }
    +          byId.set(block.id, made);
    +        } else {
    +          // After the nearest block before it that the document holds.
    +          let anchor: LexicalNode | undefined;
    +          for (let i = order.indexOf(block.id) - 1; i >= 0; i--) {
    +            anchor = byId.get(order[i]);
    +            if (anchor !== undefined) {
    +              break;
    +            }
    +          }
    +          if (anchor !== undefined) {
    +            anchor.insertAfter(made);
    +          } else {
    +            // None before it: before the nearest block after it, else (a
    +            // report without the user's order, or none of their blocks
    +            // left) at the end.
    +            const at = order.indexOf(block.id);
    +            for (let i = at + 1; at >= 0 && i < order.length; i++) {
    +              anchor = byId.get(order[i]);
    +              if (anchor !== undefined) {
    +                break;
    +              }
    +            }
    +            if (anchor !== undefined) {
    +              anchor.insertBefore(made);
    +            } else {
    +              $getRoot().append(made);
    +            }
    +          }
    +          byId.set(block.id, made);
    +        }
    +        done.push(block.id);
    +      }
    +    },
    +    {
    +      discrete: true,
    +      onUpdate: () => {
    +        committed = true;
    +      },
    +    },
    +  );
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  if (committed) {
    +    for (const id of done) {
    +      applied.push(id);
    +    }
    +  } else {
    +    for (const id of done) {
    +      notApplied.push({id, reason: 'not-written'});
    +    }
    +  }
    +  return {applied, notApplied};
    +}
    +
    +/** @experimental One capture of {@link recoverYOfflineEdits}' result. */
    +export interface YOfflineRecovered {
    +  readonly capture: YOfflineCapture;
    +  /** What is left to show, or why the capture could not be read. */
    +  readonly report: YOfflineResult<YOfflineReport>;
    +  /** What the replay stage applied; null when it did not run for this capture. */
    +  readonly replay: YReplayResult | null;
    +}
    +
    +/**
    + * @experimental On a fresh document at the current epoch, after its first
    + * sync: gather what did not sync and, at stage `'replay'`, reapply what is
    + * safe. In order:
    + *
    + * 1. every slot of `key` left at another epoch (a tab that closed before it
    + *    could freeze), or never synced (edits made on this device that never
    + *    reached a server: their base is unknown, so nothing of them is
    + *    replayable), becomes a capture;
    + * 2. each capture is described against the document as it is now;
    + * 3. at stage `'replay'`, each capture this call claims (once, across tabs)
    + *    has its replayable blocks applied as one undo step;
    + * 4. a capture with nothing left to show is deleted once the server holds
    + *    the document: only with `session`, the document's offline session,
    + *    reporting no unsynced edits (after its `markSynced()`). Without it,
    + *    or while the document holds edits the server lacks (a replay that has
    + *    not synced), such a capture is returned with no blocks, for the panel
    + *    to dismiss: until the server holds what was reapplied, the capture may
    + *    be its only stored copy.
    + *
    + * The result is the Offline edits panel's content. Stage `'off'` returns an
    + * empty list and touches nothing.
    + */
    +export async function recoverYOfflineEdits(input: {
    +  /** The fresh document's binding: active, synced, at `epoch`. */
    +  readonly binding: YOfflineBinding;
    +  readonly store: YOfflineStore | null;
    +  readonly key: string;
    +  /** The epoch the fresh document is at. */
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly config: HeadlessYConfig;
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +  /**
    +   * The fresh document's offline session: with it, a capture the server
    +   * already holds (its session reports no unsynced edits) is deleted.
    +   */
    +  readonly session?: YOfflineSession;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}): Promise<YOfflineResult<YOfflineRecovered[]>> {
    +  const entry = 'recoverYOfflineEdits';
    +  requireStage(entry, input.stage);
    +  const {binding, config, epoch, key, migrate, stage, store} = input;
    +  if (stage === 'off' || store === null) {
    +    return ok([]);
    +  }
    +  requireOption(
    +    typeof epoch === 'string' && epoch !== '',
    +    `${entry} needs epoch: the epoch the fresh document is at, as a non-empty string.`,
    +  );
    +  const now = input.now ?? Date.now;
    +  // 1. Slots left at another epoch.
    +  const slots = await store.slots(key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  for (const info of slots.value) {
    +    if (info.epoch === epoch) {
    +      continue;
    +    }
    +    // Through a handle, which then owns exactly the rows it read: what a
    +    // tab still open at that epoch writes afterwards is not removed.
    +    const stale = store.slot(key, info.epoch);
    +    const stored = await stale.load();
    +    if (!stored.ok) {
    +      // Left as it is, for the app to salvage or clear.
    +      return stored;
    +    }
    +    if (stored.value !== null && stored.value.hasUnsyncedEdits) {
    +      const saved = await store.putCapture({
    +        base: stored.value.base,
    +        capturedAt: now(),
    +        claimed: false,
    +        differs: false,
    +        epoch: info.epoch,
    +        id: newCaptureId(now()),
    +        json: null,
    +        key,
    +        reason: 'stale',
    +        state: stored.value.state,
    +        text: null,
    +      });
    +      if (!saved.ok) {
    +        return saved;
    +      }
    +    }
    +    const discarded = await stale.discard();
    +    if (!discarded.ok) {
    +      return discarded;
    +    }
    +  }
    +  // 2 to 4.
    +  const captures = await store.captures(key);
    +  if (!captures.ok) {
    +    return captures;
    +  }
    +  const doc = binding.binding.doc;
    +  const describe = (capture: YOfflineCapture) =>
    +    describeYOfflineCapture(capture, {
    +      config,
    +      current: encodeStateAsUpdate(doc),
    +      migrate,
    +    });
    +  const recovered: YOfflineRecovered[] = [];
    +  for (const capture of captures.value) {
    +    let report = describe(capture);
    +    let replay: YReplayResult | null = null;
    +    if (
    +      stage === 'replay' &&
    +      report.ok &&
    +      !capture.claimed &&
    +      binding.status.kind === 'active' &&
    +      report.value.blocks.some(block => block.replayable)
    +    ) {
    +      const claimed = await store.claimCapture(key, capture.id);
    +      if (!claimed.ok) {
    +        return claimed;
    +      }
    +      if (claimed.value) {
    +        // Described again: the claim was awaited.
    +        report = describe(capture);
    +        if (report.ok) {
    +          try {
    +            replay = replayUnsyncedEdits({binding, report: report.value});

    Done in a02307972: when a replay applied nothing and a block is 'not-written', recovery releases the claim (putCapture with claimed: false). Regression: regressions/OfflineReviewFindings.test.ts case 7.

    zurfyx zurfyx commented on code on Nov 13, 2026 16:12 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1452 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $getSelection,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      // This handle's first row is the whole document, so its later rows
    +      // build only on rows it wrote: another tab may replace the rows it
    +      // loaded. With keep 'unsynced', only when it loaded unsynced rows
    +      // (otherwise its first local edit stores the base and since).
    +      if (
    +        doc.store.clients.size > 0 &&
    +        (!this.keepUnsyncedOnly || this.started)
    +      ) {
    +        this.pending.push(encodeStateAsUpdate(doc));
    +        void this.write();
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.startGeneration++;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        // A sync and a new local edit while this writes start another
    +        // generation: its own start stays due.
    +        const generation = this.startGeneration;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok && generation === this.startGeneration) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        const syncs = this.syncs;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A sync meanwhile covers the batch: it is not queued again (it
    +          // would be stored as edits the server lacks, or, with keep
    +          // 'unsynced', as a row with no base after the clear).
    +          if (syncs === this.syncs) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** Counts markSynced() calls: a batch whose append failed across one is covered. */
    +  private syncs = 0;
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  /** keep 'unsynced': counts starts, so an old one's end clears no new one. */
    +  private startGeneration = 0;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    this.syncs++;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    // Moved. Freeze first, synchronously: from here nothing is written to
    +    // the document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +      this.slot.close();
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    const slot = this.slot;
    +    // What a delay held back is stored, then the writer lock goes (the
    +    // rows become the next handle's to replace).
    +    void (
    +      this.timer !== null || this.writing !== null
    +        ? this.flush()
    +        : Promise.resolve()
    +    ).then(() => {
    +      if (slot !== null) {
    +        slot.close();
    +      }
    +    });
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        return fail({
    +          cause: error,
    +          code: 'failed',
    +          message: `@lexical/y/offline: a state of this capture or the current document could not be read with options.config (${String(
    +            error,
    +          )}); the capture is kept. Check that config holds the editor's nodes and schemaVersion, and offer capture.text meanwhile.`,
    +        });
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report'
    +  /** The editor update failed (the editor's onError has the error). */
    +  | 'not-written';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  // Pushed to `applied` once the update has committed.
    +  const done: string[] = [];
    +  let committed = false;
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          // A caret inside the block would stay on its old nodes, which
    +          // the swap removes: it moves to the end of the new block.
    +          const selection = $getSelection();
    +          const inside =
    +            selection !== null &&
    +            selection
    +              .getNodes()
    +              .some(node => node.is(existing) || existing.isParentOf(node));
    +          existing.replace(made);
    +          if (inside) {
    +            made.selectEnd();
    +          }
    +          byId.set(block.id, made);
    +        } else {
    +          // After the nearest block before it that the document holds.
    +          let anchor: LexicalNode | undefined;
    +          for (let i = order.indexOf(block.id) - 1; i >= 0; i--) {
    +            anchor = byId.get(order[i]);
    +            if (anchor !== undefined) {
    +              break;
    +            }
    +          }
    +          if (anchor !== undefined) {
    +            anchor.insertAfter(made);
    +          } else {
    +            // None before it: before the nearest block after it, else (a
    +            // report without the user's order, or none of their blocks
    +            // left) at the end.
    +            const at = order.indexOf(block.id);
    +            for (let i = at + 1; at >= 0 && i < order.length; i++) {
    +              anchor = byId.get(order[i]);
    +              if (anchor !== undefined) {
    +                break;
    +              }
    +            }
    +            if (anchor !== undefined) {
    +              anchor.insertBefore(made);
    +            } else {
    +              $getRoot().append(made);
    +            }
    +          }
    +          byId.set(block.id, made);
    +        }
    +        done.push(block.id);
    +      }
    +    },
    +    {
    +      discrete: true,
    +      onUpdate: () => {
    +        committed = true;
    +      },
    +    },
    +  );
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  if (committed) {
    +    for (const id of done) {
    +      applied.push(id);
    +    }
    +  } else {
    +    for (const id of done) {
    +      notApplied.push({id, reason: 'not-written'});
    +    }
    +  }
    +  return {applied, notApplied};
    +}
    +
    +/** @experimental One capture of {@link recoverYOfflineEdits}' result. */
    +export interface YOfflineRecovered {
    +  readonly capture: YOfflineCapture;
    +  /** What is left to show, or why the capture could not be read. */
    +  readonly report: YOfflineResult<YOfflineReport>;
    +  /** What the replay stage applied; null when it did not run for this capture. */
    +  readonly replay: YReplayResult | null;
    +}
    +
    +/**
    + * @experimental On a fresh document at the current epoch, after its first
    + * sync: gather what did not sync and, at stage `'replay'`, reapply what is
    + * safe. In order:
    + *
    + * 1. every slot of `key` left at another epoch (a tab that closed before it
    + *    could freeze), or never synced (edits made on this device that never
    + *    reached a server: their base is unknown, so nothing of them is
    + *    replayable), becomes a capture;
    + * 2. each capture is described against the document as it is now;
    + * 3. at stage `'replay'`, each capture this call claims (once, across tabs)
    + *    has its replayable blocks applied as one undo step;
    + * 4. a capture with nothing left to show is deleted once the server holds
    + *    the document: only with `session`, the document's offline session,
    + *    reporting no unsynced edits (after its `markSynced()`). Without it,
    + *    or while the document holds edits the server lacks (a replay that has
    + *    not synced), such a capture is returned with no blocks, for the panel
    + *    to dismiss: until the server holds what was reapplied, the capture may
    + *    be its only stored copy.
    + *
    + * The result is the Offline edits panel's content. Stage `'off'` returns an
    + * empty list and touches nothing.
    + */
    +export async function recoverYOfflineEdits(input: {
    +  /** The fresh document's binding: active, synced, at `epoch`. */
    +  readonly binding: YOfflineBinding;
    +  readonly store: YOfflineStore | null;
    +  readonly key: string;
    +  /** The epoch the fresh document is at. */
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly config: HeadlessYConfig;
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +  /**
    +   * The fresh document's offline session: with it, a capture the server
    +   * already holds (its session reports no unsynced edits) is deleted.
    +   */
    +  readonly session?: YOfflineSession;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}): Promise<YOfflineResult<YOfflineRecovered[]>> {
    +  const entry = 'recoverYOfflineEdits';
    +  requireStage(entry, input.stage);
    +  const {binding, config, epoch, key, migrate, stage, store} = input;
    +  if (stage === 'off' || store === null) {
    +    return ok([]);
    +  }
    +  requireOption(
    +    typeof epoch === 'string' && epoch !== '',
    +    `${entry} needs epoch: the epoch the fresh document is at, as a non-empty string.`,
    +  );
    +  const now = input.now ?? Date.now;
    +  // 1. Slots left at another epoch.
    +  const slots = await store.slots(key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  for (const info of slots.value) {
    +    if (info.epoch === epoch) {
    +      continue;
    +    }
    +    // Through a handle, which then owns exactly the rows it read: what a
    +    // tab still open at that epoch writes afterwards is not removed.
    +    const stale = store.slot(key, info.epoch);
    +    const stored = await stale.load();
    +    if (!stored.ok) {
    +      // Left as it is, for the app to salvage or clear.
    +      return stored;
    +    }
    +    if (stored.value !== null && stored.value.hasUnsyncedEdits) {
    +      const saved = await store.putCapture({
    +        base: stored.value.base,
    +        capturedAt: now(),
    +        claimed: false,
    +        differs: false,
    +        epoch: info.epoch,
    +        id: newCaptureId(now()),
    +        json: null,
    +        key,
    +        reason: 'stale',
    +        state: stored.value.state,
    +        text: null,
    +      });
    +      if (!saved.ok) {
    +        return saved;
    +      }
    +    }
    +    const discarded = await stale.discard();

    Done: recovery reads stale slots with load({writers: 'gone'}), so a live tab's rows are left to that tab (it captures them when it learns the epoch moved), and repeated calls make no repeat captures. Without Web Locks every row is read, as before (documented). Regression: case 8.

    zurfyx zurfyx commented on code on Nov 13, 2026 16:12 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1452 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $getSelection,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`, to start with no
    + * connection: the newest slot (a key has more than one only when a tab was
    + * left at an earlier epoch; {@link recoverYOfflineEdits} turns those into
    + * captures once the server's epoch is known). Create the document from
    + * `state` and pass the result to {@link attachYOfflineSession} as `loaded`.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  if (slots.value.length === 0) {
    +    return ok({
    +      base: null,
    +      epoch: null,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = slots.value[0];
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      // This handle's first row is the whole document, so its later rows
    +      // build only on rows it wrote: another tab may replace the rows it
    +      // loaded. With keep 'unsynced', only when it loaded unsynced rows
    +      // (otherwise its first local edit stores the base and since).
    +      if (
    +        doc.store.clients.size > 0 &&
    +        (!this.keepUnsyncedOnly || this.started)
    +      ) {
    +        this.pending.push(encodeStateAsUpdate(doc));

    Done: a document loaded with nothing unsynced queues its whole-document first row as a confirmation (a base), so a later load reports nothing unsynced. Regression: case 9.

    zurfyx zurfyx commented on code on Nov 13, 2026 16:12 UTC
    Code Review
    packages/lexical-website/docs/collaboration/y.md:1
    @@ -1267,6 +1269,278 @@ deleted while its changes did not reach the server (offline, a dropped
     connection, a reload from local storage), and that client then differs from
     everyone else for good, with no warning (fixed in yrs 0.26.0).
     
    +## Offline: local persistence and edits that did not sync
    +
    +`@lexical/y/offline` (experimental) keeps a document on the device and
    +looks after the edits a server never took. It has two layers, and an app can
    +use the first alone:
    +
    +- a **local store** for Yjs 14 documents on IndexedDB, keyed by a document
    +  key your app chooses and the **epoch** (generation) the document was made
    +  against. No IndexedDB provider exists for Yjs 14 (`y-indexeddb` imports
    +  Yjs 13), and none keys by epoch or reports quota and corruption, so the
    +  store is part of this package. It adds no dependency;
    +- an **offline session** attached to a binding: it stores edits as they are
    +  made, lets them sync on a reconnect at the same epoch, and on a moved epoch
    +  freezes the document (`binding.freeze()`), stores it with its base, and
    +  reports what changed block by block (`describeUnsyncedEdits`), with a
    +  replay of the blocks nobody else touched.
    +
    +One path serves every way a client comes back. A **reconnect** at the same
    +epoch syncs the stored document. A room that was **replaced** (reloaded,
    +restored) or **upgraded** (migrated to a newer layout by its server) has a
    +new epoch, so the client's copy is frozen, captured into the same store, and
    +described against the new room; the same happens to a copy a closed tab
    +left behind. Nothing stored at another epoch is ever merged.
    +
    +An epoch is whatever your server names a document's incarnation with: a
    +generation from `@lexical/y/server` (`getYGeneration`), or a relay's counter
    +that it bumps when it reloads or upgrades a document. It is an opaque string
    +here (`String(epoch)` for a number); two are compared, never parsed.
    +
    +### Start here
    +
    +1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`:
    +   once per page. A browser without IndexedDB returns `'unavailable'`.
    +2. `const loaded = await loadYOffline({store, key})`, and create the
    +   document from `loaded.state` when there is one.
    +3. `const session = attachYOfflineSession({binding, store, key, epoch:
    +   loaded.epoch, loaded, stage, onError})`. At `'persist'` and `'replay'`
    +   every edit is stored as it is made.
    +4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    +   before the provider syncs, on every connect and reconnect, and when the
    +   server says the room was replaced or upgraded. `'same'`: sync. `'moved'`:
    +   the document is frozen and captured.
    +5. `session.markSynced()` when the server holds everything the document
    +   holds.
    +6. On the document the page syncs (a fresh one after a `'moved'`):
    +   `await recoverYOfflineEdits({...})`, whose result is the Offline edits
    +   panel.
    +
    +Whether the editor is editable before the server answers (offline editing)
    +is your app's choice, made when it binds: `synced: true` on a stored
    +document makes it editable at once; `synced: false` waits for the
    +provider's sync, and the store still keeps what is typed after it.
    +
    +```ts
    +import {createYBinding, createYDoc} from '@lexical/y';
    +import {
    +  attachYOfflineSession,
    +  loadYOffline,
    +  openYOfflineStore,
    +  recoverYOfflineEdits,
    +  type YOfflineStage,
    +} from '@lexical/y/offline';
    +
    +// The rollout stage, from your feature flag: 'off', 'persist' or 'replay'.
    +const stage: YOfflineStage = 'replay';
    +const key = documentId;
    +
    +const opened = await openYOfflineStore({
    +  idb: {indexedDB: globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange},
    +});
    +const store = opened.ok ? opened.value : null; // null: tell the user, run at 'off'
    +const loaded = store === null ? null : await loadYOffline({key, store});
    +const stored = loaded !== null && loaded.ok ? loaded.value : undefined;
    +
    +// Start from the stored document; editable at once here (your choice).
    +const doc = createYDoc(stored?.state);
    +const binding = createYBinding(editor, {
    +  doc,
    +  onStatus: showStatus,
    +  schemaVersion: SCHEMA_VERSION,
    +  synced: stored != null && stored.state !== null,
    +});
    +const session = attachYOfflineSession({
    +  binding,
    +  epoch: stored?.epoch ?? null,
    +  key,
    +  loaded: stored,
    +  onError: error => showNotSavedOnThisDevice(error.message),
    +  stage: store === null ? 'off' : stage,
    +  store,
    +});
    +
    +// The server names its epoch (in your handshake, before any sync message,
    +// and again in a "replaced" event):
    +async function onServerEpoch(epoch: string) {
    +  const verdict = await session.serverEpoch(epoch);
    +  if (verdict.kind === 'moved') {
    +    // This document is frozen and stored as a capture. Never sync it: stop
    +    // its provider, open a fresh document at `epoch`, and recover there.
    +    openFreshDocument(epoch);
    +  } else {
    +    provider.connect(); // 'same' (or 'off': do what the app did before)
    +  }
    +}
    +provider.on('sync', () => binding.markSynced());
    +// When the server holds everything (an acknowledgement of every update):
    +provider.on('saved', () => session.markSynced());
    +
    +// On the fresh document, after its first sync:
    +const recovered = await recoverYOfflineEdits({
    +  binding: freshBinding,
    +  config: headlessConfig, // your nodes and schemaVersion, as for editYState
    +  epoch,
    +  key,
    +  session: freshSession, // lets it delete what the server already holds
    +  stage,
    +  store,
    +});
    +if (recovered.ok) showOfflineEditsPanel(recovered.value);
    +```
    +
    +### Stages
    +
    +Every call that acts takes the stage, so one flag rolls the feature out:
    +
    +| Stage       | The session                                                                                  | `recoverYOfflineEdits`                                                              |
    +| ----------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
    +| `'off'`     | Adds no listener, stores nothing; `serverEpoch` answers `{kind: 'off'}`                      | Returns an empty list and touches nothing                                           |
    +| `'persist'` | Stores every edit as it is made, and freezes and stores a capture when the epoch moved       | Lists each capture with its report: the panel's preview, Copy and Reapply per block |
    +| `'replay'`  | The same                                                                                     | Also applies each capture's replayable blocks, once across tabs, as one undo step   |
    +
    +Three options shape what `'persist'` stores:
    +
    +- `persistEdits` (default `true`): `false` stores only captures (a moved
    +  epoch while the tab is open), and adds no `update` listener;
    +- `keep` (default `'document'`): the whole document always, so the page can
    +  open it with no connection. `'unsynced'` stores only while the document
    +  holds edits the server lacks: nothing while synced, the base and what came
    +  since from the first local edit, deleted by `markSynced()`;
    +- `writeDelay` (default `0`): milliseconds to wait for updates to pause
    +  before storing them (at least every ten delays while they do not).
    +  `flush()` stores at once; call it on `pagehide`.
    +
    +An app that builds its own `YBinding` (not `createYBinding` or
    +`YCollabExtension`) passes `{binding, status, freeze}` as the binding
    +(`YOfflineBinding`): its `freeze()` stops the binding and returns its local
    +edits (`binding.quiesce()` has them), and `status` reads `{kind: 'active'}`
    +while the room is editable.
    +
    +### What is stored
    +
    +A slot per `(key, epoch)` holds a **base** (the state the server is known to
    +hold, written by `markSynced()`) and the updates **since**. The document is
    +their merge; `hasUnsyncedEdits` is true while anything is stored since the
    +base. Rows are written one per update (updates that arrive while a write is
    +in flight go in one row), compacted into one after
    +`Y_OFFLINE_DEFAULTS.compactAfter` (64), and replaced by a new base at each
    +`markSynced()`. A document that never synced is stored under a null epoch and
    +moves to the first epoch the server names.
    +
    +A key is any non-empty string your app chooses; put what separates
    +documents in it (`viewer|document|space`). `store.keys()` lists every key
    +stored, so an app clears another viewer's documents at sign-in with
    +`store.clear(key, {captures: true})` for each key that is not theirs.
    +`openYOfflineStore`'s `limits` cap the store by refusing writes, never by
    +evicting: `keys` per group (`group: key => key.split('|')[0]` counts per
    +viewer) and `bytesPerKey` (rows and captures). A write past one answers
    +`'limit'`, with `error.limit` naming which. Each connection counts a key's
    +bytes from its last read of the key plus what it wrote since, so tabs
    +writing at once can pass `bytesPerKey` by what the others wrote since.
    +
    +Two tabs on one key write side by side. Each writing handle holds a Web
    +Lock (`openYOfflineStore`'s `locks`, `navigator.locks` by default) and
    +writes rows under its own id, the first of them the whole document, so its
    +later rows build only on rows it wrote. A handle replaces or removes the
    +rows it wrote and the rows it loaded whose writer is gone (a closed tab, an
    +earlier page load), never a live tab's. The tabs do not exchange edits
    +through the store; a later load holds both. Without Web Locks (`locks:
    +null`) every other handle counts as live, so earlier page loads' rows stay
    +until the app clears them.
    +
    +Nothing here throws for a storage failure. Every call returns
    +`{ok: true, value}` or `{ok: false, error}`, and `error.code` says what
    +happened:
    +
    +| Code            | When                                                              | What to do                                                                                             |
    +| --------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
    +| `'unavailable'` | No IndexedDB (a private window, Node without a fake), or the open did not answer within `openTimeout` (10 s) | Run at stage `'off'` and tell the user edits live in this tab only                                     |
    +| `'blocked'`     | Another tab holds an older version of the database                | Ask the user to close the other tabs, then open the store again                                        |
    +| `'quota'`       | The origin's storage is full                                      | Tell the user edits are not saved on this device; editing goes on and the next write stores everything |
    +| `'corrupt'`     | A stored row is not what the store wrote, or does not decode      | Offer `error.salvage.state` (the readable rows), then `store.clear(key, {epoch, captures: false})`     |
    +| `'closed'`      | `store.close()` ran, or another tab deleted the database          | Open a new store                                                                                       |
    +| `'limit'`       | The write would pass one of the store's `limits` (`error.limit`)  | Tell the user edits are not saved on this device, or clear documents no longer needed                  |
    +| `'failed'`      | Any other IndexedDB failure (`error.cause`)                       | Retry, or tell the user                                                                                |
    +
    +The session passes each failure to `onError` and keeps what it could not
    +write queued, so nothing typed is dropped from the page.
    +`store.clear(key, {captures})` deletes a document's slots (and its captures
    +with `captures: true`).
    +
    +### The base, and what counts as unsynced
    +
    +A capture's report compares three documents: the user's, the **base** their
    +edits were made against, and the current one. The session's base is the
    +document at the last `markSynced()`: call it whenever the server is known to
    +hold everything the document holds (an acknowledgement of every update,
    +where your provider counts them; with a relay that acknowledges nothing,
    +the provider's sync on connect, which leaves a window: an edit sent in that
    +sync that never arrived is in the base, so a later capture does not list
    +it). A base that is older than it could be costs nothing but precision: an edit that did reach the server is in
    +the current document as the user had it, and such blocks are left out of the
    +report; a block someone else changed since is not replayable either way.
    +Without any `markSynced()` the base is unknown, the report judges against the
    +current document, and nothing is replayable.
    +
    +### The report and the replay
    +
    +`recoverYOfflineEdits` first turns every slot left at another epoch (a tab
    +that closed before it could freeze), or never synced (its base is unknown,
    +so its blocks are listed but not replayed), into a capture, then describes each
    +capture (`describeYOfflineCapture`, which is `describeUnsyncedEdits` without
    +the blocks the document already holds as the user had them). A capture with
    +nothing left to show is deleted once the server holds the document: pass
    +`session` (the fresh document's offline session), and a later call deletes
    +it when that session reports no unsynced edits (after its `markSynced()`).
    +Until then, or without `session`, it comes back with no blocks for the
    +panel to dismiss: a replay that has not synced exists only in this page,
    +and the capture may be its only stored copy. A block
    +the user only moved is in no entry; the report's `orderDiffers` says so, and
    +such a capture is kept until the user dismisses it (a move is not replayed). With
    +`BlockIdExtension` blocks are matched by id; without it they are matched by
    +position and nothing is replayable, so the panel offers Copy only.
    +
    +`replayUnsyncedEdits({binding, report, only})` applies the replayable blocks
    +in one editor update, which the binding writes as one undo step: a changed
    +block replaces the current one, an added block goes after the nearest block
    +before it that the document holds (before the nearest after it when none is
    +left), a deleted block is removed. Call it outside an editor update. Each block is
    +checked again against the editor as it is at that moment, so a block someone
    +changed after the report was made comes back in `notApplied`
    +(`'changed-since'`) instead of being overwritten. `only` limits it to the
    +ids given, for a Reapply button.
    +
    +### Layouts
    +
    +The store keeps bytes, so it holds a document of any layout. A report reads
    +its states with this release, which refuses one below `MIN_LAYOUT`: pass
    +`migrate` (`state => migrateYState(state, steps).state` with your steps from
    +`@lexical/y/migrate`) to `describeYOfflineCapture` or `recoverYOfflineEdits`
    +and such a base or capture is read after migrating. Without it, a base below
    +the floor is reported as gone (`baseAvailable: false`, nothing replayable)
    +and a capture that has no editor JSON returns an error that names `migrate`.
    +
    +### Limits of the offline layer
    +
    +- **A replayed block replaces the current one.** Formatting, comments and
    +  nested content come from the user's copy of the block; an edit a
    +  collaborator makes to that block in the instant between the check and the
    +  write is not merged into it (the check runs in the same task as the write,
    +  so this needs their update to arrive inside the editor update).
    +- **A node that serializes differently in a live editor than in a headless
    +  read** (a decorator whose nested editor fills in an empty paragraph
    +  locally) is never replayed: the check against the base fails
    +  (`'changed-since'`). Its text is in the panel.
    +- **A tab left open at an earlier epoch while another tab recovers** is
    +  captured twice: once from its stored slot and once when it freezes. The

    Fixed: the Limits entry now describes this behaviour (a live tab keeps its rows; without Web Locks each recovery captures them again, and the repeats show nothing once their blocks are in the document).

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 16:44 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1544 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $getSelection,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`. Pass the result to
    + * {@link attachYOfflineSession} as `loaded`, with `epoch: loaded.epoch`.
    + *
    + * - Without `epoch` (bind, then sync: the page starts from the store, with
    + *   no connection): the newest slot. Create the document from `state`, and
    + *   call `session.serverEpoch(epoch)` when the server names its epoch.
    + * - With `epoch`, the server's (sync, then bind: the page has the server's
    + *   document and epoch before it binds): only the slot at that epoch.
    + *   Apply its `state` to the server's document (the same lineage, so it
    + *   merges: the edits that did not sync go out on the next sync), and bind.
    + *   A slot at another epoch is never loaded: {@link recoverYOfflineEdits}
    + *   turns it into a capture. There is nothing to ask `serverEpoch` until
    + *   the server replaces the room.
    + *
    + * A key has more than one slot only when a tab was left at an earlier
    + * epoch.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +  /** The epoch the server's room is at, when the page knows it before binding. */
    +  readonly epoch?: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const wanted = input.epoch;
    +  requireOption(
    +    wanted === undefined || (typeof wanted === 'string' && wanted !== ''),
    +    `loadYOffline's epoch is the epoch your server's room is at, as a non-empty string (String(epoch) for a number), or left out to load the newest slot; got ${
    +      wanted === '' ? "''" : typeof wanted
    +    }.`,
    +  );
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  const found =
    +    wanted === undefined
    +      ? slots.value[0]
    +      : slots.value.find(info => info.epoch === wanted);
    +  if (found === undefined) {
    +    return ok({
    +      base: null,
    +      epoch: wanted === undefined ? null : wanted,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = found;
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server says the room was replaced, and the new epoch is not known
    +   * yet: the same as `serverEpoch` with a new epoch. The binding is frozen
    +   * before this returns its promise, what it holds is captured into the
    +   * store (for `recoverYOfflineEdits` on the new document), and the
    +   * session ends. Call it on the live session, before disposing it.
    +   */
    +  freeze(options?: {
    +    readonly reason?: YOfflineCapture['reason'];
    +  }): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      // This handle's first row is the whole document, so its later rows
    +      // build only on rows it wrote: another tab may replace the rows it
    +      // loaded. With keep 'unsynced', only when it loaded unsynced rows
    +      // (otherwise its first local edit stores the base and since).
    +      if (
    +        doc.store.clients.size > 0 &&
    +        (!this.keepUnsyncedOnly || this.started)
    +      ) {
    +        if (
    +          loaded !== undefined &&
    +          loaded.state !== null &&
    +          !loaded.hasUnsyncedEdits &&
    +          loaded.base !== null
    +        ) {
    +          // Loaded with nothing unsynced: the document is its base, stored
    +          // as one (a later load reports nothing unsynced).
    +          this.confirmed = {
    +            state: encodeStateAsUpdate(doc),
    +            vector: encodeStateVector(doc),
    +          };
    +        } else {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +        }
    +        void this.write();
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.startGeneration++;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        // A sync and a new local edit while this writes start another
    +        // generation: its own start stays due.
    +        const generation = this.startGeneration;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok && generation === this.startGeneration) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        const syncs = this.syncs;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A sync meanwhile covers the batch: it is not queued again (it
    +          // would be stored as edits the server lacks, or, with keep
    +          // 'unsynced', as a row with no base after the clear).
    +          if (syncs === this.syncs) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** Counts markSynced() calls: a batch whose append failed across one is covered. */
    +  private syncs = 0;
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  /** keep 'unsynced': counts starts, so an old one's end clears no new one. */
    +  private startGeneration = 0;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    this.syncs++;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    return this.moveOn(reason);
    +  }
    +
    +  async freeze(options?: {
    +    readonly reason?: YOfflineCapture['reason'];
    +  }): Promise<YOfflineVerdict> {
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `freeze's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed): freeze() runs on the live session, when the server says the room was replaced.',
    +      );
    +    }
    +    return this.moveOn(reason);
    +  }
    +
    +  /** The room moved on: freeze, capture into the store, end the session. */
    +  private async moveOn(
    +    reason: YOfflineCapture['reason'] | undefined,
    +  ): Promise<YOfflineVerdict> {
    +    // Freeze first, synchronously: from here nothing is written to the
    +    // document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +      this.slot.close();
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    const slot = this.slot;
    +    // What a delay held back is stored, then the writer lock goes (the
    +    // rows become the next handle's to replace).
    +    void (
    +      this.timer !== null || this.writing !== null
    +        ? this.flush()
    +        : Promise.resolve()
    +    ).then(() => {
    +      if (slot !== null) {
    +        slot.close();
    +      }
    +    });
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        return fail({
    +          cause: error,
    +          code: 'failed',
    +          message: `@lexical/y/offline: a state of this capture or the current document could not be read with options.config (${String(
    +            error,
    +          )}); the capture is kept. Check that config holds the editor's nodes and schemaVersion, and offer capture.text meanwhile.`,
    +        });
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report'
    +  /** The editor update failed (the editor's onError has the error). */
    +  | 'not-written';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  // Pushed to `applied` once the update has committed.
    +  const done: string[] = [];
    +  let committed = false;
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          // A caret inside the block would stay on its old nodes, which
    +          // the swap removes: it moves to the end of the new block.
    +          const selection = $getSelection();
    +          const inside =
    +            selection !== null &&
    +            selection
    +              .getNodes()
    +              .some(node => node.is(existing) || existing.isParentOf(node));
    +          existing.replace(made);
    +          if (inside) {
    +            made.selectEnd();
    +          }
    +          byId.set(block.id, made);
    +        } else {
    +          // After the nearest block before it that the document holds.
    +          let anchor: LexicalNode | undefined;
    +          for (let i = order.indexOf(block.id) - 1; i >= 0; i--) {
    +            anchor = byId.get(order[i]);
    +            if (anchor !== undefined) {
    +              break;
    +            }
    +          }
    +          if (anchor !== undefined) {
    +            anchor.insertAfter(made);
    +          } else {
    +            // None before it: before the nearest block after it, else (a
    +            // report without the user's order, or none of their blocks
    +            // left) at the end.
    +            const at = order.indexOf(block.id);
    +            for (let i = at + 1; at >= 0 && i < order.length; i++) {
    +              anchor = byId.get(order[i]);
    +              if (anchor !== undefined) {
    +                break;
    +              }
    +            }
    +            if (anchor !== undefined) {
    +              anchor.insertBefore(made);
    +            } else {
    +              $getRoot().append(made);
    +            }
    +          }
    +          byId.set(block.id, made);
    +        }
    +        done.push(block.id);
    +      }
    +    },
    +    {
    +      discrete: true,
    +      onUpdate: () => {
    +        committed = true;
    +      },
    +    },
    +  );
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  if (committed) {
    +    for (const id of done) {
    +      applied.push(id);
    +    }
    +  } else {
    +    for (const id of done) {
    +      notApplied.push({id, reason: 'not-written'});
    +    }
    +  }
    +  return {applied, notApplied};
    +}
    +
    +/** @experimental One capture of {@link recoverYOfflineEdits}' result. */
    +export interface YOfflineRecovered {
    +  readonly capture: YOfflineCapture;
    +  /** What is left to show, or why the capture could not be read. */
    +  readonly report: YOfflineResult<YOfflineReport>;
    +  /** What the replay stage applied; null when it did not run for this capture. */
    +  readonly replay: YReplayResult | null;
    +}
    +
    +/**
    + * @experimental On a fresh document at the current epoch, after its first
    + * sync: gather what did not sync and, at stage `'replay'`, reapply what is
    + * safe. In order:
    + *
    + * 1. every slot of `key` left at another epoch (a tab that closed before it
    + *    could freeze), or never synced (edits made on this device that never
    + *    reached a server: their base is unknown, so nothing of them is
    + *    replayable), becomes a capture;
    + * 2. each capture is described against the document as it is now;
    + * 3. at stage `'replay'`, each capture this call claims (once, across tabs)
    + *    has its replayable blocks applied as one undo step;
    + * 4. a capture with nothing left to show is deleted once the server holds
    + *    the document: only with `session`, the document's offline session,
    + *    reporting no unsynced edits (after its `markSynced()`). Without it,
    + *    or while the document holds edits the server lacks (a replay that has
    + *    not synced), such a capture is returned with no blocks, for the panel
    + *    to dismiss: until the server holds what was reapplied, the capture may
    + *    be its only stored copy.
    + *
    + * The result is the Offline edits panel's content. Stage `'off'` returns an
    + * empty list and touches nothing.
    + */
    +export async function recoverYOfflineEdits(input: {
    +  /** The fresh document's binding: active, synced, at `epoch`. */
    +  readonly binding: YOfflineBinding;
    +  readonly store: YOfflineStore | null;
    +  readonly key: string;
    +  /** The epoch the fresh document is at. */
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly config: HeadlessYConfig;
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +  /**
    +   * The fresh document's offline session: with it, a capture the server
    +   * already holds (its session reports no unsynced edits) is deleted.
    +   */
    +  readonly session?: YOfflineSession;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}): Promise<YOfflineResult<YOfflineRecovered[]>> {
    +  const entry = 'recoverYOfflineEdits';
    +  requireStage(entry, input.stage);
    +  const {binding, config, epoch, key, migrate, stage, store} = input;
    +  if (stage === 'off' || store === null) {
    +    return ok([]);
    +  }
    +  requireOption(
    +    typeof epoch === 'string' && epoch !== '',
    +    `${entry} needs epoch: the epoch the fresh document is at, as a non-empty string.`,
    +  );
    +  const now = input.now ?? Date.now;
    +  // 1. Slots left at another epoch.
    +  const slots = await store.slots(key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  for (const info of slots.value) {
    +    if (info.epoch === epoch) {
    +      continue;
    +    }
    +    // Through a handle, which then owns exactly the rows it read: only
    +    // rows whose writer is gone. A tab still open at that epoch keeps its
    +    // rows, and captures them itself when it learns the epoch moved.
    +    const stale = store.slot(key, info.epoch);
    +    const stored = await stale.load({writers: 'gone'});
    +    if (!stored.ok) {
    +      // Left as it is, for the app to salvage or clear.
    +      return stored;
    +    }
    +    if (stored.value !== null && stored.value.hasUnsyncedEdits) {
    +      const saved = await store.putCapture({
    +        base: stored.value.base,
    +        capturedAt: now(),
    +        claimed: false,
    +        differs: false,
    +        epoch: info.epoch,
    +        id: newCaptureId(now()),
    +        json: null,
    +        key,
    +        reason: 'stale',
    +        state: stored.value.state,
    +        text: null,
    +      });
    +      if (!saved.ok) {
    +        return saved;
    +      }
    +    }
    +    const discarded = await stale.discard();
    +    if (!discarded.ok) {
    +      return discarded;
    +    }

    Optional: this load, putCapture and discard are three separate transactions, so two tabs that recover at the same moment can both read the slot before either deletes it and make two captures with different ids. claimCapture then gives each tab one of them, and each replays the same blocks into its own document before they sync (over the fake IndexedDB, b1 ends as one, mineone, mine in both). Doing this step in one readwrite transaction over both stores (live writers queried just before), or under a per-key Web Lock, would keep the "at most once across tabs" guarantee in D124.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 16:44 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1544 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $getSelection,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`. Pass the result to
    + * {@link attachYOfflineSession} as `loaded`, with `epoch: loaded.epoch`.
    + *
    + * - Without `epoch` (bind, then sync: the page starts from the store, with
    + *   no connection): the newest slot. Create the document from `state`, and
    + *   call `session.serverEpoch(epoch)` when the server names its epoch.
    + * - With `epoch`, the server's (sync, then bind: the page has the server's
    + *   document and epoch before it binds): only the slot at that epoch.
    + *   Apply its `state` to the server's document (the same lineage, so it
    + *   merges: the edits that did not sync go out on the next sync), and bind.
    + *   A slot at another epoch is never loaded: {@link recoverYOfflineEdits}
    + *   turns it into a capture. There is nothing to ask `serverEpoch` until
    + *   the server replaces the room.
    + *
    + * A key has more than one slot only when a tab was left at an earlier
    + * epoch.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +  /** The epoch the server's room is at, when the page knows it before binding. */
    +  readonly epoch?: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const wanted = input.epoch;
    +  requireOption(
    +    wanted === undefined || (typeof wanted === 'string' && wanted !== ''),
    +    `loadYOffline's epoch is the epoch your server's room is at, as a non-empty string (String(epoch) for a number), or left out to load the newest slot; got ${
    +      wanted === '' ? "''" : typeof wanted
    +    }.`,
    +  );
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  const found =
    +    wanted === undefined
    +      ? slots.value[0]
    +      : slots.value.find(info => info.epoch === wanted);
    +  if (found === undefined) {
    +    return ok({
    +      base: null,
    +      epoch: wanted === undefined ? null : wanted,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = found;
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server says the room was replaced, and the new epoch is not known
    +   * yet: the same as `serverEpoch` with a new epoch. The binding is frozen
    +   * before this returns its promise, what it holds is captured into the
    +   * store (for `recoverYOfflineEdits` on the new document), and the
    +   * session ends. Call it on the live session, before disposing it.
    +   */
    +  freeze(options?: {
    +    readonly reason?: YOfflineCapture['reason'];
    +  }): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      // This handle's first row is the whole document, so its later rows
    +      // build only on rows it wrote: another tab may replace the rows it
    +      // loaded. With keep 'unsynced', only when it loaded unsynced rows
    +      // (otherwise its first local edit stores the base and since).
    +      if (
    +        doc.store.clients.size > 0 &&
    +        (!this.keepUnsyncedOnly || this.started)
    +      ) {
    +        if (
    +          loaded !== undefined &&
    +          loaded.state !== null &&
    +          !loaded.hasUnsyncedEdits &&
    +          loaded.base !== null
    +        ) {
    +          // Loaded with nothing unsynced: the document is its base, stored
    +          // as one (a later load reports nothing unsynced).
    +          this.confirmed = {
    +            state: encodeStateAsUpdate(doc),
    +            vector: encodeStateVector(doc),
    +          };
    +        } else {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +        }
    +        void this.write();
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.startGeneration++;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        // A sync and a new local edit while this writes start another
    +        // generation: its own start stays due.
    +        const generation = this.startGeneration;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok && generation === this.startGeneration) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        const syncs = this.syncs;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A sync meanwhile covers the batch: it is not queued again (it
    +          // would be stored as edits the server lacks, or, with keep
    +          // 'unsynced', as a row with no base after the clear).
    +          if (syncs === this.syncs) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** Counts markSynced() calls: a batch whose append failed across one is covered. */
    +  private syncs = 0;
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  /** keep 'unsynced': counts starts, so an old one's end clears no new one. */
    +  private startGeneration = 0;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    this.syncs++;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    return this.moveOn(reason);
    +  }
    +
    +  async freeze(options?: {
    +    readonly reason?: YOfflineCapture['reason'];
    +  }): Promise<YOfflineVerdict> {
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `freeze's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed): freeze() runs on the live session, when the server says the room was replaced.',
    +      );
    +    }
    +    return this.moveOn(reason);
    +  }
    +
    +  /** The room moved on: freeze, capture into the store, end the session. */
    +  private async moveOn(
    +    reason: YOfflineCapture['reason'] | undefined,
    +  ): Promise<YOfflineVerdict> {
    +    // Freeze first, synchronously: from here nothing is written to the
    +    // document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +      this.slot.close();
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    const slot = this.slot;
    +    // What a delay held back is stored, then the writer lock goes (the
    +    // rows become the next handle's to replace).
    +    void (
    +      this.timer !== null || this.writing !== null
    +        ? this.flush()
    +        : Promise.resolve()
    +    ).then(() => {
    +      if (slot !== null) {
    +        slot.close();
    +      }
    +    });
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        return fail({
    +          cause: error,
    +          code: 'failed',
    +          message: `@lexical/y/offline: a state of this capture or the current document could not be read with options.config (${String(
    +            error,
    +          )}); the capture is kept. Check that config holds the editor's nodes and schemaVersion, and offer capture.text meanwhile.`,
    +        });
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report'
    +  /** The editor update failed (the editor's onError has the error). */
    +  | 'not-written';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  // Pushed to `applied` once the update has committed.
    +  const done: string[] = [];
    +  let committed = false;
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          // A caret inside the block would stay on its old nodes, which
    +          // the swap removes: it moves to the end of the new block.
    +          const selection = $getSelection();
    +          const inside =
    +            selection !== null &&
    +            selection
    +              .getNodes()
    +              .some(node => node.is(existing) || existing.isParentOf(node));
    +          existing.replace(made);
    +          if (inside) {
    +            made.selectEnd();
    +          }
    +          byId.set(block.id, made);
    +        } else {
    +          // After the nearest block before it that the document holds.
    +          let anchor: LexicalNode | undefined;
    +          for (let i = order.indexOf(block.id) - 1; i >= 0; i--) {
    +            anchor = byId.get(order[i]);
    +            if (anchor !== undefined) {
    +              break;
    +            }
    +          }
    +          if (anchor !== undefined) {
    +            anchor.insertAfter(made);
    +          } else {
    +            // None before it: before the nearest block after it, else (a
    +            // report without the user's order, or none of their blocks
    +            // left) at the end.
    +            const at = order.indexOf(block.id);
    +            for (let i = at + 1; at >= 0 && i < order.length; i++) {
    +              anchor = byId.get(order[i]);
    +              if (anchor !== undefined) {
    +                break;
    +              }
    +            }
    +            if (anchor !== undefined) {
    +              anchor.insertBefore(made);
    +            } else {
    +              $getRoot().append(made);
    +            }
    +          }
    +          byId.set(block.id, made);
    +        }
    +        done.push(block.id);
    +      }
    +    },
    +    {
    +      discrete: true,
    +      onUpdate: () => {
    +        committed = true;
    +      },
    +    },
    +  );
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  if (committed) {
    +    for (const id of done) {
    +      applied.push(id);
    +    }
    +  } else {
    +    for (const id of done) {
    +      notApplied.push({id, reason: 'not-written'});
    +    }
    +  }
    +  return {applied, notApplied};
    +}
    +
    +/** @experimental One capture of {@link recoverYOfflineEdits}' result. */
    +export interface YOfflineRecovered {
    +  readonly capture: YOfflineCapture;
    +  /** What is left to show, or why the capture could not be read. */
    +  readonly report: YOfflineResult<YOfflineReport>;
    +  /** What the replay stage applied; null when it did not run for this capture. */
    +  readonly replay: YReplayResult | null;
    +}
    +
    +/**
    + * @experimental On a fresh document at the current epoch, after its first
    + * sync: gather what did not sync and, at stage `'replay'`, reapply what is
    + * safe. In order:
    + *
    + * 1. every slot of `key` left at another epoch (a tab that closed before it
    + *    could freeze), or never synced (edits made on this device that never
    + *    reached a server: their base is unknown, so nothing of them is
    + *    replayable), becomes a capture;
    + * 2. each capture is described against the document as it is now;
    + * 3. at stage `'replay'`, each capture this call claims (once, across tabs)
    + *    has its replayable blocks applied as one undo step;
    + * 4. a capture with nothing left to show is deleted once the server holds
    + *    the document: only with `session`, the document's offline session,
    + *    reporting no unsynced edits (after its `markSynced()`). Without it,
    + *    or while the document holds edits the server lacks (a replay that has
    + *    not synced), such a capture is returned with no blocks, for the panel
    + *    to dismiss: until the server holds what was reapplied, the capture may
    + *    be its only stored copy.
    + *
    + * The result is the Offline edits panel's content. Stage `'off'` returns an
    + * empty list and touches nothing.
    + */
    +export async function recoverYOfflineEdits(input: {
    +  /** The fresh document's binding: active, synced, at `epoch`. */
    +  readonly binding: YOfflineBinding;
    +  readonly store: YOfflineStore | null;
    +  readonly key: string;
    +  /** The epoch the fresh document is at. */
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly config: HeadlessYConfig;
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +  /**
    +   * The fresh document's offline session: with it, a capture the server
    +   * already holds (its session reports no unsynced edits) is deleted.
    +   */
    +  readonly session?: YOfflineSession;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}): Promise<YOfflineResult<YOfflineRecovered[]>> {
    +  const entry = 'recoverYOfflineEdits';
    +  requireStage(entry, input.stage);
    +  const {binding, config, epoch, key, migrate, stage, store} = input;
    +  if (stage === 'off' || store === null) {
    +    return ok([]);
    +  }
    +  requireOption(
    +    typeof epoch === 'string' && epoch !== '',
    +    `${entry} needs epoch: the epoch the fresh document is at, as a non-empty string.`,
    +  );
    +  const now = input.now ?? Date.now;
    +  // 1. Slots left at another epoch.
    +  const slots = await store.slots(key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  for (const info of slots.value) {
    +    if (info.epoch === epoch) {
    +      continue;
    +    }
    +    // Through a handle, which then owns exactly the rows it read: only
    +    // rows whose writer is gone. A tab still open at that epoch keeps its
    +    // rows, and captures them itself when it learns the epoch moved.
    +    const stale = store.slot(key, info.epoch);
    +    const stored = await stale.load({writers: 'gone'});
    +    if (!stored.ok) {
    +      // Left as it is, for the app to salvage or clear.
    +      return stored;

    Optional: a corrupt slot at another epoch ends the whole call here, so healthy captures of the key are not described or replayed on this or any later call, and YOfflineError has no epoch for the store.clear(key, {epoch, captures: false}) y.md recommends. Skipping and reporting this slot, or adding epoch to the error, would let the app act on it.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 16:44 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineStore.ts:1
    @@ -0,0 +1,1408 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// Local persistence for Yjs 14 documents (`@lexical/y/offline`): a document's
    +// updates in IndexedDB, by an app-chosen key and the epoch (generation) the
    +// document was made against. No provider for Yjs 14 exists (`y-indexeddb`
    +// imports Yjs 13), and none keys by epoch or reports quota and corruption, so
    +// this one is written here on IndexedDB alone, with `@y/y` used only to merge
    +// updates.
    +//
    +// A slot (key, epoch) holds rows of two kinds:
    +//
    +// - `base`: a state the server is known to hold (written by `confirm`);
    +// - `since`: every update the document made or received after it.
    +//
    +// The document is their merge; what the server may lack is in `since`. Rows
    +// are keyed `[key, epoch, kind, writer, n]` with a random `writer` per slot
    +// handle, so two tabs on one key never overwrite each other. A handle only
    +// replaces rows it owns (the ones it loaded or wrote, all of which its
    +// document holds): another tab's rows stay until that tab, or a later load,
    +// replaces them.
    +
    +import {mergeUpdates} from '@y/y';
    +
    +/**
    + * @experimental The defaults of the optional fields of `@lexical/y/offline`,
    + * by name, so code can say which it relies on.
    + */
    +export const Y_OFFLINE_DEFAULTS: {
    +  readonly databaseName: string;
    +  readonly compactAfter: number;
    +  readonly openTimeout: number;
    +} = /* @__PURE__ */ Object.freeze({
    +  /** `since` rows a slot handle writes before it compacts them into one. */
    +  compactAfter: 64,
    +  databaseName: 'lexical-y-offline',
    +  /** Milliseconds openYOfflineStore waits for the database to open. */
    +  openTimeout: 10000,
    +});
    +
    +/** @experimental What failed (see {@link YOfflineError}). */
    +export type YOfflineErrorCode =
    +  /** There is no IndexedDB here (a private window, Node without a fake). */
    +  | 'unavailable'
    +  /** Another tab holds an older version of the database open. */
    +  | 'blocked'
    +  /** The browser refused the write: the origin's storage quota is full. */
    +  | 'quota'
    +  /** A stored row is not what this module wrote, or does not decode. */
    +  | 'corrupt'
    +  /** The store was closed (`store.close()`, or the database was deleted). */
    +  | 'closed'
    +  /**
    +   * The write would pass one of the store's `limits` (see `limit`): it was
    +   * refused, and nothing was evicted.
    +   */
    +  | 'limit'
    +  /** Any other IndexedDB failure; `cause` holds it. */
    +  | 'failed';
    +
    +/**
    + * @experimental A failure of the local store. Nothing here throws for a
    + * storage failure: every call returns a {@link YOfflineResult}, and
    + * `message` says what to do.
    + */
    +export interface YOfflineError {
    +  readonly code: YOfflineErrorCode;
    +  /** What happened and what the app can do about it. */
    +  readonly message: string;
    +  /** The underlying error, when there is one. */
    +  readonly cause?: unknown;
    +  /**
    +   * With `'corrupt'`: what the readable rows hold (their merge, the base
    +   * apart), so the app can offer it before clearing the slot.
    +   */
    +  readonly salvage?: YOfflineSalvage;
    +  /** With `'limit'`: which limit (see {@link YOfflineLimits}). */
    +  readonly limit?: 'keys' | 'bytes';
    +}
    +
    +/**
    + * @experimental Caps a store keeps by refusing writes (`'limit'`), never by
    + * evicting: what is stored stays until the app clears it.
    + */
    +export interface YOfflineLimits {
    +  /** Most keys stored per group (a new key past it is refused). */
    +  readonly keys?: number;
    +  /**
    +   * Most bytes stored per key: its rows' updates and its captures' states
    +   * and bases (a capture's JSON and text are not counted). Each connection
    +   * counts what it last read of the key plus what it wrote since; another
    +   * tab's writes count from its next read (a compaction, a confirmation, a
    +   * capture), so tabs writing at once can pass it by what they wrote since.
    +   */
    +  readonly bytesPerKey?: number;
    +  /**
    +   * The group a key counts in for `keys`, e.g. its viewer for keys
    +   * `viewer|doc`: `key => key.split('|')[0]`. Default: one group.
    +   */
    +  readonly group?: (key: string) => string;
    +}
    +
    +/** @experimental What a corrupt slot still holds (see {@link YOfflineError}). */
    +export interface YOfflineSalvage {
    +  /** The merge of every readable row, or null when none is. */
    +  readonly state: Uint8Array | null;
    +  readonly readableRows: number;
    +  readonly unreadableRows: number;
    +}
    +
    +/** @experimental A value, or the error that kept it from being made. */
    +export type YOfflineResult<T> =
    +  | {readonly ok: true; readonly value: T}
    +  | {readonly ok: false; readonly error: YOfflineError};
    +
    +/** @experimental What a slot holds (see {@link YOfflineSlot.load}). */
    +export interface YOfflineStored {
    +  /** The whole document: `base` and `since` merged (a Yjs update). */
    +  readonly state: Uint8Array;
    +  /** The state the server is known to hold, or null when none was confirmed. */
    +  readonly base: Uint8Array | null;
    +  /** Whether updates were stored after `base`: the server may lack them. */
    +  readonly hasUnsyncedEdits: boolean;
    +}
    +
    +/** @experimental One slot of a key (see {@link YOfflineStore.slots}). */
    +export interface YOfflineSlotInfo {
    +  readonly key: string;
    +  /** The epoch the slot's document was made against; null: never synced. */
    +  readonly epoch: string | null;
    +  /** When its newest row was written (Unix ms). */
    +  readonly updatedAt: number;
    +  readonly hasUnsyncedEdits: boolean;
    +  readonly rows: number;
    +}
    +
    +/**
    + * @experimental A frozen copy of a client's document that did not sync,
    + * with the base it was made against: what the Offline edits panel shows.
    + */
    +export interface YOfflineCapture {
    +  /** Unique per key. */
    +  readonly id: string;
    +  readonly key: string;
    +  /** The epoch the edits were made against; null: never synced. */
    +  readonly epoch: string | null;
    +  readonly reason: 'stale' | 'legacy' | 'expired';
    +  /** When it was captured (Unix ms). */
    +  readonly capturedAt: number;
    +  /** The whole document as the client held it (a Yjs update). */
    +  readonly state: Uint8Array;
    +  /**
    +   * The editor's content as Lexical JSON (`freeze()`'s), or null for a
    +   * capture made from storage alone (a tab that closed before it could
    +   * freeze).
    +   */
    +  readonly json: unknown | null;
    +  /** The plain text of the editor, for Copy; null as `json` is. */
    +  readonly text: string | null;
    +  /**
    +   * Whether the editor held edits the document did not (`freeze()`'s
    +   * `differs`): the report then reads `json`, else `state`.
    +   */
    +  readonly differs: boolean;
    +  /** The document the edits were made against, or null when unknown. */
    +  readonly base: Uint8Array | null;
    +  /** Set once a replay stage took the capture (see claimCapture). */
    +  readonly claimed: boolean;
    +}
    +
    +/** @experimental One (key, epoch) of a {@link YOfflineStore}. */
    +export interface YOfflineSlot {
    +  readonly key: string;
    +  /** Changes with {@link YOfflineSlot.adopt}. */
    +  readonly epoch: string | null;
    +  /**
    +   * Read the slot: null when it holds nothing. The rows read become this
    +   * handle's (create the document from `state`, so it holds them). With
    +   * `{writers: 'gone'}`, only rows whose writer is gone (no live tab holds
    +   * them): what recovery captures, leaving a live tab's rows to that tab.
    +   * Without Web Locks (`locks: null`) that is every row.
    +   */
    +  load(options?: {
    +    readonly writers?: 'all' | 'gone';
    +  }): Promise<YOfflineResult<YOfflineStored | null>>;
    +  /** Store one update the document made or received. */
    +  append(update: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * The server holds `state` (the whole document, which holds every row of
    +   * this handle): it becomes the base and this handle's rows are removed.
    +   */
    +  confirm(state: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * Replace this handle's `since` rows by one: `since` when given (what the
    +   * document holds beyond the base), else their merge.
    +   */
    +  compact(since?: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * Delete this handle's rows (the ones it loaded or wrote), and no other:
    +   * for a document that was captured, whose rows another tab at the same
    +   * epoch may still be adding to.
    +   */
    +  discard(): Promise<YOfflineResult<void>>;
    +  /** `since` rows this handle wrote since it last compacted or confirmed. */
    +  readonly rowsSinceCompaction: number;
    +  /**
    +   * Release the handle's writer lock (see `locks`): its rows become another
    +   * handle's to replace. Call it when the document is closed; a closed tab
    +   * releases it on its own.
    +   */
    +  close(): void;
    +  /**
    +   * Move a slot that never synced (`epoch` null) to the epoch the server
    +   * gave it: this handle's rows, and those it loaded whose writer is gone.
    +   * A live tab's rows stay for that tab to move.
    +   */
    +  adopt(epoch: string): Promise<YOfflineResult<void>>;
    +}
    +
    +/** @experimental The local store (see {@link openYOfflineStore}). */
    +export interface YOfflineStore {
    +  /** A handle on one slot; nothing is read or written until it is used. */
    +  slot(key: string, epoch: string | null): YOfflineSlot;
    +  /** The slots stored for `key`, newest first. */
    +  slots(key: string): Promise<YOfflineResult<YOfflineSlotInfo[]>>;
    +  /** The captures stored for `key`, oldest first. */
    +  captures(key: string): Promise<YOfflineResult<YOfflineCapture[]>>;
    +  putCapture(capture: YOfflineCapture): Promise<YOfflineResult<void>>;
    +  /**
    +   * Mark a capture as taken by a replay: true for the one caller that gets
    +   * it (a second tab, or a second call, gets false), so a capture is
    +   * replayed automatically at most once.
    +   */
    +  claimCapture(key: string, id: string): Promise<YOfflineResult<boolean>>;
    +  deleteCapture(key: string, id: string): Promise<YOfflineResult<void>>;
    +  /**
    +   * Delete what is stored for `key`: one slot when `what.epoch` is given
    +   * (null names the never-synced slot), else every slot; its captures too
    +   * with `what.captures`.
    +   */
    +  clear(
    +    key: string,
    +    what: {readonly epoch?: string | null; readonly captures: boolean},
    +  ): Promise<YOfflineResult<void>>;
    +  /** Every key that holds a slot or a capture (for clearing by owner). */
    +  keys(): Promise<YOfflineResult<string[]>>;
    +  /** Close the database: later calls return `'closed'`. */
    +  close(): void;
    +}
    +
    +/** @experimental Options of {@link openYOfflineStore}. */
    +export interface YOfflineStoreOptions {
    +  /**
    +   * The IndexedDB to use. Required, so every caller decides: pass
    +   * `{indexedDB, IDBKeyRange}` from `globalThis` in a browser, or a fake's
    +   * in Node (the store works without a DOM).
    +   */
    +  readonly idb: {
    +    readonly indexedDB: IDBFactory | undefined;
    +    readonly IDBKeyRange: typeof IDBKeyRange | undefined;
    +  };
    +  /**
    +   * The database's name: one per app.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.databaseName`
    +   */
    +  readonly databaseName?: string;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +  /**
    +   * Milliseconds to wait for the database to open before answering
    +   * `'unavailable'` (some browsers never answer an open in some states).
    +   * A connection that opens later is closed.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.openTimeout`
    +   */
    +  readonly openTimeout?: number;
    +  /** Caps kept by refusing writes, never by evicting. Default: none. */
    +  readonly limits?: YOfflineLimits;
    +  /**
    +   * The Web Locks the store tells live tabs by: each writing handle holds a
    +   * lock, and no handle removes rows a live handle wrote (they may be what
    +   * that tab's later rows build on). Rows of a handle that is gone (a
    +   * closed tab, an earlier page load) are replaced by the next handle that
    +   * loads them. Null: every other handle counts as live, so rows of earlier
    +   * page loads are kept until the app clears them.
    +   * @defaultValue `navigator.locks`, where there is one, else null
    +   */
    +  readonly locks?: YOfflineLocks | null;
    +}
    +
    +/** @experimental The part of the Web Locks API the store uses. */
    +export interface YOfflineLocks {
    +  request(
    +    name: string,
    +    callback: (lock: unknown) => Promise<unknown>,
    +  ): Promise<unknown>;
    +  query(): Promise<{readonly held?: readonly {readonly name?: string}[]}>;
    +}
    +
    +/** Wraps a request callback so that what it throws fails the transaction. */
    +type Guard = (fn: () => void) => () => void;
    +
    +const UPDATES = 'updates';
    +const CAPTURES = 'captures';
    +const DB_VERSION = 1;
    +const ROW_VERSION = 1;
    +
    +type RowKind = 'b' | 's';
    +/** `[key, epoch (0 for null), kind, writer, n]`. */
    +type RowKey = [string, string | 0, RowKind, string, number];
    +
    +interface Row {
    +  readonly v: number;
    +  /** The update. */
    +  readonly u: Uint8Array;
    +  /** FNV-1a of `u`: a row cut short or changed does not read as an update. */
    +  readonly h: number;
    +  /** When it was written (Unix ms). */
    +  readonly t: number;
    +}
    +
    +const ok = <T>(value: T): YOfflineResult<T> => ({ok: true, value});
    +const fail = <T>(error: YOfflineError): YOfflineResult<T> => ({
    +  error,
    +  ok: false,
    +});
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +function checksum(bytes: Uint8Array): number {
    +  let h = 0x811c9dc5;
    +  for (let i = 0; i < bytes.length; i++) {
    +    h ^= bytes[i];
    +    h = Math.imul(h, 0x01000193);
    +  }
    +  return h >>> 0;
    +}
    +
    +/**
    + * A Uint8Array of any realm: a value read back from IndexedDB in an iframe,
    + * or under a test runner's VM, is not `instanceof` this realm's.
    + */
    +function isBytes(value: unknown): value is Uint8Array {
    +  return (
    +    ArrayBuffer.isView(value) &&
    +    Object.prototype.toString.call(value) === '[object Uint8Array]'
    +  );
    +}
    +
    +/**
    + * `bytes` with a buffer of its own size: IndexedDB stores a view's whole
    + * buffer, and an update can be a short view of an encoder's long one.
    + */
    +function exact(bytes: Uint8Array): Uint8Array {
    +  return bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
    +}
    +
    +function isRow(value: unknown): value is Row {
    +  if (typeof value !== 'object' || value === null) {
    +    return false;
    +  }
    +  const row = value as Partial<Row>;
    +  return (
    +    row.v === ROW_VERSION &&
    +    isBytes(row.u) &&
    +    row.u.length > 0 &&
    +    typeof row.t === 'number' &&
    +    row.h === checksum(row.u)
    +  );
    +}
    +
    +function merge(updates: readonly Uint8Array[]): Uint8Array | null {
    +  return updates.length === 0
    +    ? null
    +    : updates.length === 1
    +      ? updates[0]
    +      : mergeUpdates(updates as Parameters<typeof mergeUpdates>[0]);
    +}
    +
    +const epochKey = (epoch: string | null): string | 0 =>
    +  epoch === null ? 0 : epoch;
    +const epochOf = (key: string | 0): string | null => (key === 0 ? null : key);
    +
    +function errorName(error: unknown): string {
    +  return typeof error === 'object' && error !== null && 'name' in error
    +    ? String((error as {name: unknown}).name)
    +    : '';
    +}
    +
    +/** A limit a write would pass, thrown inside a transaction to abort it. */
    +class LimitReached {
    +  constructor(readonly error: YOfflineError) {}
    +}
    +
    +/** The typed error of an IndexedDB failure. */
    +function storageError(cause: unknown, doing: string): YOfflineError {
    +  if (cause instanceof LimitReached) {
    +    return cause.error;
    +  }
    +  const name = errorName(cause);
    +  if (name === 'QuotaExceededError') {
    +    return {
    +      cause,
    +      code: 'quota',
    +      message: `@lexical/y/offline: the browser's storage quota is full, so ${doing} was not stored. The edits are still in the page: tell the user they are not saved on this device, free space (store.clear(key, {captures: true}) for documents no longer needed) and the next write retries.`,
    +    };
    +  }
    +  if (name === 'InvalidStateError' || name === 'TransactionInactiveError') {
    +    return {
    +      cause,
    +      code: 'closed',
    +      message: `@lexical/y/offline: the store is closed, so ${doing} did not run; open a new one with openYOfflineStore().`,
    +    };
    +  }
    +  return {
    +    cause,
    +    code: 'failed',
    +    message: `@lexical/y/offline: IndexedDB failed while ${doing} (${
    +      name || String(cause)
    +    }); the edits are still in the page. Retry, or tell the user they are not saved on this device.`,
    +  };
    +}
    +
    +class Store implements YOfflineStore {
    +  private closed = false;
    +  /**
    +   * Bytes stored per key, as this store last read them plus what it wrote
    +   * since (only with `limits.bytesPerKey`, so an append reads nothing). A
    +   * write that removes rows forgets the key: the next write reads it again.
    +   */
    +  private readonly sizes = new Map<string, number>();
    +  constructor(
    +    private readonly db: IDBDatabase,
    +    private readonly range: typeof IDBKeyRange,
    +    readonly now: () => number,
    +    private readonly limits: YOfflineLimits | null,
    +    private readonly locks: YOfflineLocks | null,
    +    private readonly name: string,
    +  ) {
    +    // Another tab upgrades or deletes the database: let it.
    +    db.onversionchange = () => this.close();
    +  }
    +
    +  close(): void {
    +    if (!this.closed) {
    +      this.closed = true;
    +      this.db.close();
    +      for (const release of this.held) {
    +        release();
    +      }
    +      this.held.clear();
    +    }
    +  }
    +
    +  /** Releases of the writer locks this store's handles hold. */
    +  private readonly held = new Set<() => void>();
    +
    +  private lockName(writer: string): string {
    +    return `lexical-y-offline:${this.name}:${writer}`;
    +  }
    +
    +  /**
    +   * Hold `writer`'s lock: resolves once it is held (a row of a writer only
    +   * exists while its lock is held, or after its handle is gone). Returns
    +   * its release.
    +   */
    +  async hold(writer: string): Promise<() => void> {
    +    const locks = this.locks;
    +    if (locks === null) {
    +      return () => {};
    +    }
    +    let release = () => {};
    +    await new Promise<void>(granted => {
    +      void locks.request(this.lockName(writer), () => {
    +        granted();
    +        return new Promise<void>(done => {
    +          release = () => {
    +            this.held.delete(release);
    +            done();
    +          };
    +          this.held.add(release);
    +        });
    +      });
    +    });
    +    return release;
    +  }
    +
    +  /** The writers whose handles are live, or null when that is unknown. */
    +  async liveWriters(): Promise<ReadonlySet<string> | null> {
    +    if (this.locks === null) {
    +      return null;
    +    }
    +    const prefix = this.lockName('');
    +    const {held = []} = await this.locks.query();
    +    const live = new Set<string>();
    +    for (const lock of held) {
    +      if (typeof lock.name === 'string' && lock.name.startsWith(prefix)) {
    +        live.add(lock.name.slice(prefix.length));
    +      }
    +    }
    +    return live;
    +  }
    +
    +  /** Every key that starts with `prefix` (arrays sort after every string and number). */
    +  prefix(prefix: readonly (string | number)[]): IDBKeyRange {
    +    return this.range.bound(prefix, [...prefix, []]);
    +  }
    +
    +  /**
    +   * One transaction: `work` issues its requests (more from their callbacks)
    +   * and the result is what it left in `out` once the transaction commits.
    +   */
    +  run<T>(
    +    stores: string[],
    +    mode: IDBTransactionMode,
    +    doing: string,
    +    work: (tx: IDBTransaction, out: {value: T}, guard: Guard) => void,
    +    initial: T,
    +  ): Promise<YOfflineResult<T>> {
    +    if (this.closed) {
    +      return Promise.resolve(
    +        fail(storageError({name: 'InvalidStateError'}, doing)),
    +      );
    +    }
    +    return new Promise(resolve => {
    +      const out = {value: initial};
    +      let tx: IDBTransaction;
    +      try {
    +        tx = this.db.transaction(stores, mode);
    +      } catch (error) {
    +        resolve(fail(storageError(error, doing)));
    +        return;
    +      }
    +      let failure: unknown = null;
    +      tx.oncomplete = () => resolve(ok(out.value));
    +      tx.onabort = () =>
    +        resolve(fail(storageError(failure ?? tx.error, doing)));
    +      tx.onerror = event => {
    +        // The request's error (a quota failure arrives here, or as the
    +        // transaction's own error on abort).
    +        const target = event.target as IDBRequest | null;
    +        failure = failure ?? (target === null ? null : target.error);
    +      };
    +      const abort = (error: unknown) => {
    +        failure = failure ?? error;
    +        try {
    +          tx.abort();
    +        } catch {
    +          resolve(fail(storageError(error, doing)));
    +        }
    +      };
    +      // A request callback that throws would abort the transaction with no
    +      // error to report (and throw at the window): it is reported instead.
    +      const guard: Guard = fn => () => {
    +        try {
    +          fn();
    +        } catch (error) {
    +          abort(error);
    +        }
    +      };
    +      try {
    +        work(tx, out, guard);
    +      } catch (error) {
    +        abort(error);
    +      }
    +    });
    +  }
    +
    +  slot(key: string, epoch: string | null): YOfflineSlot {
    +    requireKey(key);
    +    requireEpoch(epoch);
    +    return new Slot(this, key, epoch);
    +  }
    +
    +  keys(): Promise<YOfflineResult<string[]>> {
    +    return this.run<string[]>(
    +      [UPDATES, CAPTURES],
    +      'readonly',
    +      'listing the keys',
    +      (tx, out, guard) => {
    +        const keys = new Set<string>();
    +        const updates = tx.objectStore(UPDATES).getAllKeys();
    +        updates.onsuccess = guard(() => {
    +          for (const k of updates.result as RowKey[]) {
    +            keys.add(k[0]);
    +          }
    +          const captures = tx.objectStore(CAPTURES).getAllKeys();
    +          captures.onsuccess = guard(() => {
    +            for (const k of captures.result as [string, string][]) {
    +              keys.add(k[0]);
    +            }
    +            out.value = [...keys].sort();
    +          });
    +        });
    +      },
    +      [],
    +    );
    +  }
    +
    +  /**
    +   * The object stores a write needs: with limits, both (the check reads
    +   * the key's rows and captures).
    +   */
    +  stores(store: string): string[] {
    +    return this.limits === null ? [store] : [UPDATES, CAPTURES];
    +  }
    +
    +  /** The store forgets what it knew of `key`'s size (rows were removed). */
    +  forget(key: string): void {
    +    this.sizes.delete(key);
    +  }
    +
    +  /**
    +   * Inside a write transaction, before it writes `adding` bytes for `key`
    +   * (and removes the rows `removing`, whose bytes then do not count): run
    +   * `then`, or abort with `'limit'` when the write would pass a limit.
    +   * Reads nothing without limits, nor for an append whose key's size is
    +   * known.
    +   */
    +  withinLimits(
    +    tx: IDBTransaction,
    +    guard: Guard,
    +    key: string,
    +    adding: number,
    +    removing: ReadonlySet<string> | null,
    +    then: () => void,
    +    replacingCapture: string | null = null,
    +  ): void {
    +    const limits = this.limits;
    +    if (limits === null) {
    +      then();
    +      return;
    +    }
    +    const known = this.sizes.get(key);
    +    if (removing === null && known !== undefined) {
    +      this.check(key, known + adding, false, limits);
    +      this.sizes.set(key, known + adding);
    +      then();
    +      return;
    +    }
    +    // Read the key's rows and captures (a first write, or one that removes).
    +    readRows(tx, this.prefix([key]), guard, rows => {
    +      const captures = tx.objectStore(CAPTURES).getAll(this.prefix([key]));
    +      captures.onsuccess = guard(() => {
    +        let bytes = 0;
    +        for (const [rowKey, value] of rows) {
    +          if (
    +            (removing === null || !removing.has(JSON.stringify(rowKey))) &&
    +            isRow(value)
    +          ) {
    +            bytes += value.u.byteLength;
    +          }
    +        }
    +        for (const capture of captures.result as unknown[]) {
    +          // A capture put again under its id replaces itself.
    +          if (
    +            replacingCapture === null ||
    +            (capture as {id?: unknown}).id !== replacingCapture
    +          ) {
    +            bytes += captureBytes(capture);
    +          }
    +        }
    +        const isNew = rows.length === 0 && captures.result.length === 0;
    +        const finish = () => {
    +          this.check(key, bytes + adding, false, limits);
    +          this.sizes.set(key, bytes + adding);
    +          then();
    +        };
    +        if (!isNew || limits.keys === undefined) {
    +          finish();
    +          return;
    +        }
    +        // A new key: count its group's keys.
    +        const group = limits.group ?? (() => '');
    +        const mine = group(key);
    +        const updates = tx.objectStore(UPDATES).getAllKeys();
    +        updates.onsuccess = guard(() => {
    +          const all = tx.objectStore(CAPTURES).getAllKeys();
    +          all.onsuccess = guard(() => {
    +            const keys = new Set<string>();
    +            for (const k of updates.result as RowKey[]) {
    +              keys.add(k[0]);
    +            }
    +            for (const k of all.result as [string, string][]) {
    +              keys.add(k[0]);
    +            }
    +            let inGroup = 0;
    +            for (const k of keys) {
    +              if (group(k) === mine) {
    +                inGroup++;
    +              }
    +            }
    +            this.check(key, inGroup + 1, true, limits);
    +            finish();
    +          });
    +        });
    +      });
    +    });
    +  }
    +
    +  /** Throws (aborting the transaction) when `amount` passes a limit. */
    +  private check(
    +    key: string,
    +    amount: number,
    +    isKeys: boolean,
    +    limits: YOfflineLimits,
    +  ): void {
    +    const max = isKeys ? limits.keys : limits.bytesPerKey;
    +    if (max !== undefined && amount > max) {
    +      this.forget(key);
    +      throw new LimitReached({
    +        code: 'limit',
    +        limit: isKeys ? 'keys' : 'bytes',
    +        message: isKeys
    +          ? `@lexical/y/offline: storing '${key}' would make ${amount} keys in its group, past limits.keys (${max}); it was refused and nothing was evicted. The edits are still in the page: tell the user they are not saved on this device, or clear documents no longer needed (store.clear(key, {captures: true})).`
    +          : `@lexical/y/offline: storing '${key}' would hold ${amount} bytes, past limits.bytesPerKey (${max}); it was refused and nothing was evicted. The edits are still in the page: tell the user they are not saved on this device.`,
    +      });
    +    }
    +  }
    +
    +  async slots(key: string): Promise<YOfflineResult<YOfflineSlotInfo[]>> {
    +    requireKey(key);
    +    const read = await this.rows([key], 'listing the slots');
    +    if (!read.ok) {
    +      return read;
    +    }
    +    const byEpoch = new Map<string | 0, YOfflineSlotInfo>();
    +    for (const [rowKey, value] of read.value) {
    +      const before = byEpoch.get(rowKey[1]);
    +      const t = isRow(value) ? value.t : 0;
    +      byEpoch.set(rowKey[1], {
    +        epoch: epochOf(rowKey[1]),
    +        hasUnsyncedEdits:
    +          (before !== undefined && before.hasUnsyncedEdits) ||
    +          rowKey[2] === 's',
    +        key,
    +        rows: (before === undefined ? 0 : before.rows) + 1,
    +        updatedAt: Math.max(before === undefined ? 0 : before.updatedAt, t),
    +      });
    +    }
    +    return ok([...byEpoch.values()].sort((a, b) => b.updatedAt - a.updatedAt));
    +  }
    +
    +  /** The rows under a key prefix, with their keys, in key order. */
    +  rows(
    +    prefix: readonly (string | number)[],
    +    doing: string,
    +  ): Promise<YOfflineResult<[RowKey, unknown][]>> {
    +    return this.run<[RowKey, unknown][]>(
    +      [UPDATES],
    +      'readonly',
    +      doing,
    +      (tx, out, guard) =>
    +        readRows(tx, this.prefix(prefix), guard, rows => (out.value = rows)),
    +      [],
    +    );
    +  }
    +
    +  async captures(key: string): Promise<YOfflineResult<YOfflineCapture[]>> {
    +    requireKey(key);
    +    const read = await this.run<unknown[]>(
    +      [CAPTURES],
    +      'readonly',
    +      'reading the captures',
    +      (tx, out) => {
    +        const request = tx.objectStore(CAPTURES).getAll(this.prefix([key]));
    +        request.onsuccess = () => (out.value = request.result);
    +      },
    +      [],
    +    );
    +    if (!read.ok) {
    +      return read;
    +    }
    +    const captures = read.value.filter(isCapture);
    +    if (captures.length !== read.value.length) {
    +      return fail({
    +        code: 'corrupt',
    +        message: `@lexical/y/offline: ${
    +          read.value.length - captures.length
    +        } stored capture(s) of '${key}' are not readable. Call store.clear(key, {captures: true}) to drop them.`,
    +      });
    +    }
    +    return ok(captures.sort((a, b) => a.capturedAt - b.capturedAt));
    +  }
    +
    +  putCapture(capture: YOfflineCapture): Promise<YOfflineResult<void>> {
    +    return this.run<void>(
    +      this.stores(CAPTURES),
    +      'readwrite',
    +      'storing a capture',
    +      (tx, _out, guard) => {
    +        // A capture replaces any of the same id: forget the key's size so
    +        // the check reads it.
    +        this.forget(capture.key);
    +        this.withinLimits(
    +          tx,
    +          guard,
    +          capture.key,
    +          captureBytes(capture),
    +          new Set(),
    +          () => {
    +            tx.objectStore(CAPTURES).put(
    +              {
    +                ...capture,
    +                base: capture.base === null ? null : exact(capture.base),
    +                state: exact(capture.state),
    +              },
    +              [capture.key, capture.id],
    +            );
    +          },
    +          capture.id,
    +        );

    Optional: the capture is checked with every row of the key still counted, and both callers put it before discarding the rows it replaces, so a key needs about three documents of room (rows + state + base). With bytesPerKey at 2.5x a document, serverEpoch returned saved: {code: 'limit'} and each later recoverYOfflineEdits returned the same, so the edits are never shown. Passing the replaced rows as removing (one transaction), or documenting the headroom, would fix it.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 16:44 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineStore.ts:1
    @@ -0,0 +1,1408 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// Local persistence for Yjs 14 documents (`@lexical/y/offline`): a document's
    +// updates in IndexedDB, by an app-chosen key and the epoch (generation) the
    +// document was made against. No provider for Yjs 14 exists (`y-indexeddb`
    +// imports Yjs 13), and none keys by epoch or reports quota and corruption, so
    +// this one is written here on IndexedDB alone, with `@y/y` used only to merge
    +// updates.
    +//
    +// A slot (key, epoch) holds rows of two kinds:
    +//
    +// - `base`: a state the server is known to hold (written by `confirm`);
    +// - `since`: every update the document made or received after it.
    +//
    +// The document is their merge; what the server may lack is in `since`. Rows
    +// are keyed `[key, epoch, kind, writer, n]` with a random `writer` per slot
    +// handle, so two tabs on one key never overwrite each other. A handle only
    +// replaces rows it owns (the ones it loaded or wrote, all of which its
    +// document holds): another tab's rows stay until that tab, or a later load,
    +// replaces them.
    +
    +import {mergeUpdates} from '@y/y';
    +
    +/**
    + * @experimental The defaults of the optional fields of `@lexical/y/offline`,
    + * by name, so code can say which it relies on.
    + */
    +export const Y_OFFLINE_DEFAULTS: {
    +  readonly databaseName: string;
    +  readonly compactAfter: number;
    +  readonly openTimeout: number;
    +} = /* @__PURE__ */ Object.freeze({
    +  /** `since` rows a slot handle writes before it compacts them into one. */
    +  compactAfter: 64,
    +  databaseName: 'lexical-y-offline',
    +  /** Milliseconds openYOfflineStore waits for the database to open. */
    +  openTimeout: 10000,
    +});
    +
    +/** @experimental What failed (see {@link YOfflineError}). */
    +export type YOfflineErrorCode =
    +  /** There is no IndexedDB here (a private window, Node without a fake). */
    +  | 'unavailable'
    +  /** Another tab holds an older version of the database open. */
    +  | 'blocked'
    +  /** The browser refused the write: the origin's storage quota is full. */
    +  | 'quota'
    +  /** A stored row is not what this module wrote, or does not decode. */
    +  | 'corrupt'
    +  /** The store was closed (`store.close()`, or the database was deleted). */
    +  | 'closed'
    +  /**
    +   * The write would pass one of the store's `limits` (see `limit`): it was
    +   * refused, and nothing was evicted.
    +   */
    +  | 'limit'
    +  /** Any other IndexedDB failure; `cause` holds it. */
    +  | 'failed';
    +
    +/**
    + * @experimental A failure of the local store. Nothing here throws for a
    + * storage failure: every call returns a {@link YOfflineResult}, and
    + * `message` says what to do.
    + */
    +export interface YOfflineError {
    +  readonly code: YOfflineErrorCode;
    +  /** What happened and what the app can do about it. */
    +  readonly message: string;
    +  /** The underlying error, when there is one. */
    +  readonly cause?: unknown;
    +  /**
    +   * With `'corrupt'`: what the readable rows hold (their merge, the base
    +   * apart), so the app can offer it before clearing the slot.
    +   */
    +  readonly salvage?: YOfflineSalvage;
    +  /** With `'limit'`: which limit (see {@link YOfflineLimits}). */
    +  readonly limit?: 'keys' | 'bytes';
    +}
    +
    +/**
    + * @experimental Caps a store keeps by refusing writes (`'limit'`), never by
    + * evicting: what is stored stays until the app clears it.
    + */
    +export interface YOfflineLimits {
    +  /** Most keys stored per group (a new key past it is refused). */
    +  readonly keys?: number;
    +  /**
    +   * Most bytes stored per key: its rows' updates and its captures' states
    +   * and bases (a capture's JSON and text are not counted). Each connection
    +   * counts what it last read of the key plus what it wrote since; another
    +   * tab's writes count from its next read (a compaction, a confirmation, a
    +   * capture), so tabs writing at once can pass it by what they wrote since.
    +   */
    +  readonly bytesPerKey?: number;
    +  /**
    +   * The group a key counts in for `keys`, e.g. its viewer for keys
    +   * `viewer|doc`: `key => key.split('|')[0]`. Default: one group.
    +   */
    +  readonly group?: (key: string) => string;
    +}
    +
    +/** @experimental What a corrupt slot still holds (see {@link YOfflineError}). */
    +export interface YOfflineSalvage {
    +  /** The merge of every readable row, or null when none is. */
    +  readonly state: Uint8Array | null;
    +  readonly readableRows: number;
    +  readonly unreadableRows: number;
    +}
    +
    +/** @experimental A value, or the error that kept it from being made. */
    +export type YOfflineResult<T> =
    +  | {readonly ok: true; readonly value: T}
    +  | {readonly ok: false; readonly error: YOfflineError};
    +
    +/** @experimental What a slot holds (see {@link YOfflineSlot.load}). */
    +export interface YOfflineStored {
    +  /** The whole document: `base` and `since` merged (a Yjs update). */
    +  readonly state: Uint8Array;
    +  /** The state the server is known to hold, or null when none was confirmed. */
    +  readonly base: Uint8Array | null;
    +  /** Whether updates were stored after `base`: the server may lack them. */
    +  readonly hasUnsyncedEdits: boolean;
    +}
    +
    +/** @experimental One slot of a key (see {@link YOfflineStore.slots}). */
    +export interface YOfflineSlotInfo {
    +  readonly key: string;
    +  /** The epoch the slot's document was made against; null: never synced. */
    +  readonly epoch: string | null;
    +  /** When its newest row was written (Unix ms). */
    +  readonly updatedAt: number;
    +  readonly hasUnsyncedEdits: boolean;
    +  readonly rows: number;
    +}
    +
    +/**
    + * @experimental A frozen copy of a client's document that did not sync,
    + * with the base it was made against: what the Offline edits panel shows.
    + */
    +export interface YOfflineCapture {
    +  /** Unique per key. */
    +  readonly id: string;
    +  readonly key: string;
    +  /** The epoch the edits were made against; null: never synced. */
    +  readonly epoch: string | null;
    +  readonly reason: 'stale' | 'legacy' | 'expired';
    +  /** When it was captured (Unix ms). */
    +  readonly capturedAt: number;
    +  /** The whole document as the client held it (a Yjs update). */
    +  readonly state: Uint8Array;
    +  /**
    +   * The editor's content as Lexical JSON (`freeze()`'s), or null for a
    +   * capture made from storage alone (a tab that closed before it could
    +   * freeze).
    +   */
    +  readonly json: unknown | null;
    +  /** The plain text of the editor, for Copy; null as `json` is. */
    +  readonly text: string | null;
    +  /**
    +   * Whether the editor held edits the document did not (`freeze()`'s
    +   * `differs`): the report then reads `json`, else `state`.
    +   */
    +  readonly differs: boolean;
    +  /** The document the edits were made against, or null when unknown. */
    +  readonly base: Uint8Array | null;
    +  /** Set once a replay stage took the capture (see claimCapture). */
    +  readonly claimed: boolean;
    +}
    +
    +/** @experimental One (key, epoch) of a {@link YOfflineStore}. */
    +export interface YOfflineSlot {
    +  readonly key: string;
    +  /** Changes with {@link YOfflineSlot.adopt}. */
    +  readonly epoch: string | null;
    +  /**
    +   * Read the slot: null when it holds nothing. The rows read become this
    +   * handle's (create the document from `state`, so it holds them). With
    +   * `{writers: 'gone'}`, only rows whose writer is gone (no live tab holds
    +   * them): what recovery captures, leaving a live tab's rows to that tab.
    +   * Without Web Locks (`locks: null`) that is every row.
    +   */
    +  load(options?: {
    +    readonly writers?: 'all' | 'gone';
    +  }): Promise<YOfflineResult<YOfflineStored | null>>;
    +  /** Store one update the document made or received. */
    +  append(update: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * The server holds `state` (the whole document, which holds every row of
    +   * this handle): it becomes the base and this handle's rows are removed.
    +   */
    +  confirm(state: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * Replace this handle's `since` rows by one: `since` when given (what the
    +   * document holds beyond the base), else their merge.
    +   */
    +  compact(since?: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * Delete this handle's rows (the ones it loaded or wrote), and no other:
    +   * for a document that was captured, whose rows another tab at the same
    +   * epoch may still be adding to.
    +   */
    +  discard(): Promise<YOfflineResult<void>>;
    +  /** `since` rows this handle wrote since it last compacted or confirmed. */
    +  readonly rowsSinceCompaction: number;
    +  /**
    +   * Release the handle's writer lock (see `locks`): its rows become another
    +   * handle's to replace. Call it when the document is closed; a closed tab
    +   * releases it on its own.
    +   */
    +  close(): void;
    +  /**
    +   * Move a slot that never synced (`epoch` null) to the epoch the server
    +   * gave it: this handle's rows, and those it loaded whose writer is gone.
    +   * A live tab's rows stay for that tab to move.
    +   */
    +  adopt(epoch: string): Promise<YOfflineResult<void>>;
    +}
    +
    +/** @experimental The local store (see {@link openYOfflineStore}). */
    +export interface YOfflineStore {
    +  /** A handle on one slot; nothing is read or written until it is used. */
    +  slot(key: string, epoch: string | null): YOfflineSlot;
    +  /** The slots stored for `key`, newest first. */
    +  slots(key: string): Promise<YOfflineResult<YOfflineSlotInfo[]>>;
    +  /** The captures stored for `key`, oldest first. */
    +  captures(key: string): Promise<YOfflineResult<YOfflineCapture[]>>;
    +  putCapture(capture: YOfflineCapture): Promise<YOfflineResult<void>>;
    +  /**
    +   * Mark a capture as taken by a replay: true for the one caller that gets
    +   * it (a second tab, or a second call, gets false), so a capture is
    +   * replayed automatically at most once.
    +   */
    +  claimCapture(key: string, id: string): Promise<YOfflineResult<boolean>>;
    +  deleteCapture(key: string, id: string): Promise<YOfflineResult<void>>;
    +  /**
    +   * Delete what is stored for `key`: one slot when `what.epoch` is given
    +   * (null names the never-synced slot), else every slot; its captures too
    +   * with `what.captures`.
    +   */
    +  clear(
    +    key: string,
    +    what: {readonly epoch?: string | null; readonly captures: boolean},
    +  ): Promise<YOfflineResult<void>>;
    +  /** Every key that holds a slot or a capture (for clearing by owner). */
    +  keys(): Promise<YOfflineResult<string[]>>;
    +  /** Close the database: later calls return `'closed'`. */
    +  close(): void;
    +}
    +
    +/** @experimental Options of {@link openYOfflineStore}. */
    +export interface YOfflineStoreOptions {
    +  /**
    +   * The IndexedDB to use. Required, so every caller decides: pass
    +   * `{indexedDB, IDBKeyRange}` from `globalThis` in a browser, or a fake's
    +   * in Node (the store works without a DOM).
    +   */
    +  readonly idb: {
    +    readonly indexedDB: IDBFactory | undefined;
    +    readonly IDBKeyRange: typeof IDBKeyRange | undefined;
    +  };
    +  /**
    +   * The database's name: one per app.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.databaseName`
    +   */
    +  readonly databaseName?: string;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +  /**
    +   * Milliseconds to wait for the database to open before answering
    +   * `'unavailable'` (some browsers never answer an open in some states).
    +   * A connection that opens later is closed.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.openTimeout`
    +   */
    +  readonly openTimeout?: number;
    +  /** Caps kept by refusing writes, never by evicting. Default: none. */
    +  readonly limits?: YOfflineLimits;
    +  /**
    +   * The Web Locks the store tells live tabs by: each writing handle holds a
    +   * lock, and no handle removes rows a live handle wrote (they may be what
    +   * that tab's later rows build on). Rows of a handle that is gone (a
    +   * closed tab, an earlier page load) are replaced by the next handle that
    +   * loads them. Null: every other handle counts as live, so rows of earlier
    +   * page loads are kept until the app clears them.
    +   * @defaultValue `navigator.locks`, where there is one, else null
    +   */
    +  readonly locks?: YOfflineLocks | null;
    +}
    +
    +/** @experimental The part of the Web Locks API the store uses. */
    +export interface YOfflineLocks {
    +  request(
    +    name: string,
    +    callback: (lock: unknown) => Promise<unknown>,
    +  ): Promise<unknown>;
    +  query(): Promise<{readonly held?: readonly {readonly name?: string}[]}>;
    +}
    +
    +/** Wraps a request callback so that what it throws fails the transaction. */
    +type Guard = (fn: () => void) => () => void;
    +
    +const UPDATES = 'updates';
    +const CAPTURES = 'captures';
    +const DB_VERSION = 1;
    +const ROW_VERSION = 1;
    +
    +type RowKind = 'b' | 's';
    +/** `[key, epoch (0 for null), kind, writer, n]`. */
    +type RowKey = [string, string | 0, RowKind, string, number];
    +
    +interface Row {
    +  readonly v: number;
    +  /** The update. */
    +  readonly u: Uint8Array;
    +  /** FNV-1a of `u`: a row cut short or changed does not read as an update. */
    +  readonly h: number;
    +  /** When it was written (Unix ms). */
    +  readonly t: number;
    +}
    +
    +const ok = <T>(value: T): YOfflineResult<T> => ({ok: true, value});
    +const fail = <T>(error: YOfflineError): YOfflineResult<T> => ({
    +  error,
    +  ok: false,
    +});
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +function checksum(bytes: Uint8Array): number {
    +  let h = 0x811c9dc5;
    +  for (let i = 0; i < bytes.length; i++) {
    +    h ^= bytes[i];
    +    h = Math.imul(h, 0x01000193);
    +  }
    +  return h >>> 0;
    +}
    +
    +/**
    + * A Uint8Array of any realm: a value read back from IndexedDB in an iframe,
    + * or under a test runner's VM, is not `instanceof` this realm's.
    + */
    +function isBytes(value: unknown): value is Uint8Array {
    +  return (
    +    ArrayBuffer.isView(value) &&
    +    Object.prototype.toString.call(value) === '[object Uint8Array]'
    +  );
    +}
    +
    +/**
    + * `bytes` with a buffer of its own size: IndexedDB stores a view's whole
    + * buffer, and an update can be a short view of an encoder's long one.
    + */
    +function exact(bytes: Uint8Array): Uint8Array {
    +  return bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
    +}
    +
    +function isRow(value: unknown): value is Row {
    +  if (typeof value !== 'object' || value === null) {
    +    return false;
    +  }
    +  const row = value as Partial<Row>;
    +  return (
    +    row.v === ROW_VERSION &&

    Optional: a row from a later release (v > ROW_VERSION) reads as corrupt here, and the corrupt advice is to clear the slot, so a tab still on this release would be told to delete newer rows. A distinct non-destructive outcome for a newer format is cheap to add before old clients exist.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 16:44 UTC
    Code Review
    packages/lexical-playground/src/collaborationYOffline.tsx:1
    @@ -0,0 +1,523 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// Collab Y offline mode (`@lexical/y/offline`), on with the "Collab Y
    +// Offline" setting (`?collabYOffline=true`):
    +//
    +// - the document is stored in IndexedDB as it is edited, so the page opens
    +//   with no connection and keeps what was typed (the toolbar's connect
    +//   button takes the page offline);
    +// - on reconnect at the same epoch it syncs as usual;
    +// - when the epoch moved, the page's copy is frozen and captured, the page
    +//   opens the room's new document, and the Offline edits panel shows what
    +//   did not sync, block by block, with Copy and Reapply (at stage `replay`,
    +//   the default, the replayable blocks are reapplied at once).
    +//
    +// The playground's relay has no epochs, so `?collabYEpoch=<n>` stands in for
    +// what a server would say: each epoch is its own room, and the panel's
    +// "Simulate replaced" button plays the server (it copies the document the
    +// server holds into the next epoch's room, then tells this page the room was
    +// replaced). `?collabYOfflineStage=persist` turns the automatic replay off.
    +
    +import {type Signal, signal} from '@lexical/extension';
    +import {useSignalValue} from '@lexical/react/useExtensionSignalValue';
    +import {createYDoc, type YCollabBinding} from '@lexical/y';
    +import {type HeadlessYConfig} from '@lexical/y/headless';
    +import {
    +  attachYOfflineSession,
    +  loadYOffline,
    +  openYOfflineStore,
    +  recoverYOfflineEdits,
    +  replayUnsyncedEdits,
    +  Y_OFFLINE_STAGES,
    +  type YOfflineCapture,
    +  type YOfflineLoaded,
    +  type YOfflineRecovered,
    +  type YOfflineSession,
    +  type YOfflineStage,
    +  type YOfflineStore,
    +} from '@lexical/y/offline';
    +import {WebsocketProvider} from '@y/websocket';
    +import {encodeStateAsUpdate} from '@y/y';
    +import {type JSX, useCallback} from 'react';
    +
    +const params = new URLSearchParams(window.location.search);
    +
    +/** The epoch the playground's "server" is at (see the note above). */
    +export const COLLAB_Y_EPOCH = params.get('collabYEpoch') || '1';
    +
    +const requestedStage = params.get('collabYOfflineStage');
    +/** The rollout stage: `replay` unless the URL says otherwise. */
    +export const COLLAB_Y_OFFLINE_STAGE: YOfflineStage = Y_OFFLINE_STAGES.includes(
    +  requestedStage as YOfflineStage,
    +)
    +  ? (requestedStage as YOfflineStage)
    +  : 'replay';
    +
    +/** The room of a document at an epoch: epoch 1 is the room without it. */
    +export function roomAtEpoch(room: string, epoch: string): string {
    +  return epoch === '1' ? room : `${room}@${epoch}`;
    +}
    +
    +/** What was read from the local store before the document is made. */
    +export interface CollabYOfflinePrepared {
    +  /** Null when there is no local store here (it says why in `problem`). */
    +  store: YOfflineStore | null;
    +  loaded: YOfflineLoaded | null;
    +  problem: string | null;
    +}
    +
    +const prepared = new Map<string, Promise<CollabYOfflinePrepared | null>>();
    +
    +/**
    + * Open the local store and read the document stored for `key`; null with
    + * offline mode off. One promise per key, so React's `use` can wait on it.
    + */
    +export function prepareCollabYOffline(
    +  key: string,
    +  enabled: boolean,
    +): Promise<CollabYOfflinePrepared | null> {
    +  const id = `${enabled}:${key}`;
    +  let promise = prepared.get(id);
    +  if (promise === undefined) {
    +    promise = enabled ? prepare(key) : Promise.resolve(null);
    +    prepared.set(id, promise);
    +  }
    +  return promise;
    +}
    +
    +async function prepare(key: string): Promise<CollabYOfflinePrepared> {
    +  const opened = await openYOfflineStore({
    +    idb: {
    +      IDBKeyRange: globalThis.IDBKeyRange,
    +      indexedDB: globalThis.indexedDB,
    +    },
    +  });
    +  if (!opened.ok) {
    +    return {loaded: null, problem: opened.error.message, store: null};
    +  }
    +  const loaded = await loadYOffline({key, store: opened.value});
    +  if (!loaded.ok) {
    +    return {loaded: null, problem: loaded.error.message, store: opened.value};
    +  }
    +  return {loaded: loaded.value, problem: null, store: opened.value};
    +}
    +
    +export interface CollabYOfflineStatus {
    +  hasUnsyncedEdits: boolean;
    +  persisted: boolean;
    +  problem: string | null;
    +}
    +
    +/** The page's offline mode: the session, and what the panel shows. */
    +export interface CollabYOffline {
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly status: Signal<CollabYOfflineStatus>;
    +  /** What did not sync, per capture (null until the first sync). */
    +  readonly recovered: Signal<YOfflineRecovered[] | null>;
    +  /** The provider finished a sync: confirm it, then gather what did not sync. */
    +  onSynced(): void;
    +  reapply(captureId: string, blockId: string): Promise<void>;
    +  dismiss(captureId: string): Promise<void>;
    +  /** Play the server: move the room to the next epoch (see the note above). */
    +  simulateReplaced(): Promise<void>;
    +  /** True once the epoch moved: this document is never synced again. */
    +  frozen(): boolean;
    +  dispose(): void;
    +}
    +
    +/**
    + * The stored document to start from, when it belongs to the epoch the
    + * room is at; otherwise the page starts from the server (and a document
    + * stored at another epoch becomes a capture after the first sync).
    + */
    +export function storedStateFor(
    +  from: CollabYOfflinePrepared | null,
    +): Uint8Array | null {
    +  return from !== null &&
    +    from.loaded !== null &&
    +    from.loaded.epoch === COLLAB_Y_EPOCH
    +    ? from.loaded.state
    +    : null;
    +}
    +
    +export function createCollabYOffline(input: {
    +  binding: YCollabBinding;
    +  from: CollabYOfflinePrepared;
    +  key: string;
    +  /** The headless configuration of the same editor, for the reports. */
    +  config: HeadlessYConfig;
    +  /** The relay, and this document's room without its epoch. */
    +  endpoint: string;
    +  room: string;
    +  /** Stop syncing the page's document for good (its provider). */
    +  stopSync: () => void;
    +}): CollabYOffline {
    +  const {binding, config, from, key} = input;
    +  const {store} = from;
    +  const stage = store === null ? 'off' : COLLAB_Y_OFFLINE_STAGE;
    +  const status = signal<CollabYOfflineStatus>({
    +    hasUnsyncedEdits: false,
    +    persisted: store !== null,
    +    problem: from.problem,
    +  });
    +  const recovered = signal<YOfflineRecovered[] | null>(null);
    +  const useStored = storedStateFor(from) !== null;
    +  const session: YOfflineSession = attachYOfflineSession({
    +    binding,
    +    epoch: COLLAB_Y_EPOCH,
    +    key,
    +    loaded: useStored && from.loaded !== null ? from.loaded : undefined,
    +    onError: error => {
    +      status.value = {
    +        ...status.peek(),
    +        persisted: false,
    +        problem: error.message,
    +      };
    +    },
    +    stage,
    +    store,
    +  });
    +  const doc = binding.binding.doc;
    +  const refreshStatus = () => {
    +    const before = status.peek();
    +    const next = {
    +      hasUnsyncedEdits: session.hasUnsyncedEdits,
    +      persisted: session.persisted,
    +      problem: session.persisted ? from.problem : before.problem,
    +    };
    +    if (
    +      next.hasUnsyncedEdits !== before.hasUnsyncedEdits ||
    +      next.persisted !== before.persisted ||
    +      next.problem !== before.problem
    +    ) {
    +      status.value = next;
    +    }
    +  };
    +  const onTransaction = () => {
    +    refreshStatus();
    +    void session.flush().then(refreshStatus);
    +  };
    +  doc.on('afterTransaction', onTransaction);
    +  refreshStatus();
    +
    +  const recover = async () => {
    +    if (binding.status.kind !== 'active') {
    +      return;
    +    }
    +    try {
    +      const result = await recoverYOfflineEdits({
    +        binding,
    +        config,
    +        epoch: COLLAB_Y_EPOCH,
    +        key,
    +        session,
    +        stage,
    +        store,
    +      });
    +      if (result.ok) {
    +        recovered.value = result.value;
    +      } else {
    +        status.value = {...status.peek(), problem: result.error.message};
    +      }
    +    } catch (error) {
    +      // The reports could not be made (the headless editor): the captures
    +      // are still stored, and the panel offers their text.
    +      const captures = store === null ? null : await store.captures(key);
    +      recovered.value =
    +        captures !== null && captures.ok
    +          ? captures.value.map(capture => ({
    +              capture,
    +              replay: null,
    +              report: {
    +                error: {code: 'failed', message: String(error)},
    +                ok: false,
    +              },
    +            }))
    +          : [];
    +    }
    +  };
    +  let recovering: Promise<void> | null = null;
    +
    +  return {
    +    dismiss: async captureId => {
    +      if (store !== null) {
    +        await store.deleteCapture(key, captureId);
    +      }
    +      await recover();
    +    },
    +    dispose: () => {
    +      doc.off('afterTransaction', onTransaction);
    +      session.dispose();
    +    },
    +    epoch: COLLAB_Y_EPOCH,
    +    frozen: () => session.ended,
    +    onSynced: () => {
    +      if (session.ended) {
    +        return;
    +      }
    +      // The epoch is the room's (the provider is connected to it).
    +      void session.serverEpoch(COLLAB_Y_EPOCH).then(verdict => {
    +        if (verdict.kind === 'same' && !session.ended) {
    +          session.markSynced();
    +          refreshStatus();
    +          recovering ??= recover();
    +        }
    +      });
    +    },
    +    reapply: async (captureId, blockId) => {
    +      const entry = (recovered.peek() ?? []).find(
    +        r => r.capture.id === captureId,
    +      );
    +      if (entry !== undefined && entry.report.ok) {
    +        replayUnsyncedEdits({
    +          binding,
    +          only: [blockId],
    +          report: entry.report.value,
    +        });
    +      }
    +      await recover();
    +    },
    +    recovered,
    +    simulateReplaced: async () => {
    +      const next = String((Number(COLLAB_Y_EPOCH) || 1) + 1);
    +      // Stop syncing this document for good, then freeze and capture it:
    +      // nothing of it may reach the old room again (a reconnect included;
    +      // the toolbar's Connect does nothing once it is frozen).
    +      input.stopSync();
    +      const verdict = await session.serverEpoch(next);
    +      if (verdict.kind !== 'moved') {
    +        return;
    +      }
    +      // The server reloads the room from what it holds (the relay's room at
    +      // this epoch), as a real replace or upgrade would.
    +      const oldRoom = roomAtEpoch(input.room, COLLAB_Y_EPOCH);
    +      const serverState = await readRoom(input.endpoint, oldRoom);
    +      const seeded =
    +        serverState === null
    +          ? false
    +          : await seedRoom(
    +              input.endpoint,
    +              roomAtEpoch(input.room, next),
    +              serverState,
    +            );
    +      if (!seeded) {
    +        status.value = {
    +          ...status.peek(),
    +          problem:
    +            'The relay did not answer, so the room was not replaced. This page is frozen and its edits are stored on this device: reload when the relay is back.',
    +        };
    +        return;
    +      }
    +      const url = new URL(window.location.href);
    +      url.searchParams.set('collabYEpoch', next);
    +      window.location.href = url.toString();
    +    },
    +    stage,
    +    status,
    +  };
    +}
    +
    +/** What a room holds on the relay, or null when the relay does not answer. */
    +function readRoom(endpoint: string, room: string): Promise<Uint8Array | null> {
    +  return new Promise(resolve => {
    +    const doc = createYDoc(null);
    +    const provider = new WebsocketProvider(endpoint, room, doc, {
    +      disableBc: true,
    +    });
    +    const finish = (state: Uint8Array | null) => {
    +      clearTimeout(timer);
    +      provider.destroy();
    +      resolve(state);
    +    };
    +    const timer = setTimeout(() => finish(null), 3000);
    +    provider.on('sync', (isSynced: boolean) => {
    +      if (isSynced) {
    +        finish(encodeStateAsUpdate(doc));
    +      }
    +    });
    +  });
    +}
    +
    +/**
    + * Put `state` into a room, as a server that reloaded a document would.
    + * False when the relay does not answer.
    + */
    +function seedRoom(
    +  endpoint: string,
    +  room: string,
    +  state: Uint8Array,
    +): Promise<boolean> {
    +  return new Promise(resolve => {
    +    const provider = new WebsocketProvider(endpoint, room, createYDoc(state), {
    +      disableBc: true,
    +    });
    +    let settled = false;
    +    const finish = (seeded: boolean) => {
    +      if (!settled) {
    +        settled = true;
    +        clearTimeout(timer);
    +        // Sync step 2 (this document's content) was sent with step 1.
    +        setTimeout(() => {
    +          provider.destroy();
    +          resolve(seeded);
    +        }, 200);
    +      }
    +    };
    +    const timer = setTimeout(() => finish(false), 3000);
    +    provider.on('sync', (isSynced: boolean) => {
    +      if (isSynced) {
    +        finish(true);
    +      }
    +    });
    +  });
    +}
    +
    +/** The plain text of a serialized block. */
    +function previewOf(node: unknown): string {
    +  if (typeof node !== 'object' || node === null) {
    +    return '';
    +  }
    +  const {children, text} = node as {children?: unknown; text?: unknown};
    +  if (typeof text === 'string') {
    +    return text;
    +  }
    +  return Array.isArray(children) ? children.map(previewOf).join('') : '';
    +}
    +
    +function copy(text: string): void {
    +  void navigator.clipboard.writeText(text);
    +}
    +
    +const CHANGE_LABEL = {
    +  added: 'Added',
    +  changed: 'Changed',
    +  deleted: 'Deleted',
    +} as const;
    +
    +function CaptureView({
    +  entry,
    +  offline,
    +}: {
    +  entry: YOfflineRecovered;
    +  offline: CollabYOffline;
    +}): JSX.Element {
    +  const capture: YOfflineCapture = entry.capture;
    +  const blocks = entry.report.ok ? entry.report.value.blocks : [];
    +  const applied = entry.replay === null ? 0 : entry.replay.applied.length;
    +  return (
    +    <section
    +      className="collab-y-offline-capture"
    +      data-test-id="collab-y-offline-capture">
    +      <div className="collab-y-offline-capture-title">
    +        <strong>Offline edits</strong> from epoch {capture.epoch ?? 'none'}
    +        {applied > 0 ? ` · ${applied} reapplied (undo to revert)` : ''}
    +        {capture.text !== null ? (
    +          <button
    +            type="button"
    +            onClick={() => copy(capture.text ?? '')}
    +            title="Copy the whole document as you had it">
    +            Copy all
    +          </button>
    +        ) : null}
    +        <button
    +          type="button"
    +          data-test-id="collab-y-offline-dismiss"
    +          onClick={() => void offline.dismiss(capture.id)}>
    +          Dismiss
    +        </button>
    +      </div>
    +      {!entry.report.ok ? (
    +        <div className="collab-y-offline-problem">
    +          These edits could not be compared with the document; their text is
    +          kept (Copy all).
    +        </div>
    +      ) : blocks.length === 0 ? (
    +        <div className="collab-y-offline-empty">
    +          {entry.report.value.orderDiffers
    +            ? 'Your copy has its blocks in another order; the rest is in the document.'
    +            : 'Everything is in the document.'}
    +        </div>
    +      ) : (
    +        blocks.map(block => {
    +          const preview = previewOf(block.yours ?? block.base);
    +          return (
    +            <div
    +              key={block.id}
    +              className="collab-y-offline-block"
    +              data-test-id="collab-y-offline-block"
    +              data-change={block.change}
    +              data-replayable={block.replayable}>
    +              <span className="collab-y-offline-change">
    +                {CHANGE_LABEL[block.change]}
    +              </span>
    +              <span className="collab-y-offline-preview">{preview}</span>
    +              <button type="button" onClick={() => copy(preview)}>
    +                Copy
    +              </button>
    +              <button
    +                type="button"
    +                data-test-id="collab-y-offline-reapply"
    +                disabled={!block.replayable}
    +                title={
    +                  block.replayable
    +                    ? 'Put this block back as you had it'
    +                    : 'Someone changed this block since: copy your text instead'
    +                }
    +                onClick={() => void offline.reapply(capture.id, block.id)}>
    +                Reapply
    +              </button>
    +            </div>
    +          );
    +        })
    +      )}
    +    </section>
    +  );
    +}
    +
    +/** The status line and the Offline edits panel. */
    +export function CollabYOfflinePanel({
    +  offline,
    +}: {
    +  offline: CollabYOffline;
    +}): JSX.Element {
    +  const status = useSignalValue(offline.status);
    +  const recovered = useSignalValue(offline.recovered);
    +  const simulate = useCallback(
    +    () => void offline.simulateReplaced(),
    +    [offline],
    +  );
    +  return (
    +    <div className="collab-y-offline" data-test-id="collab-y-offline">
    +      <div
    +        className="collab-y-offline-status"
    +        role="status"

    Nit: this live region's text flips between "edits waiting to sync" and "synced" each time typing pauses, so a screen reader repeats it while the user types. Moving role="status" to the problem line would keep the announcements to failures.

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 13, 2026 16:44 UTC
    Approved Reviewer

    Thanks, this looks good. @lexical/y/offline is cleanly layered (typed store results, epochs, writer locks, rollout stages), y.md and DECISIONS.md (D124 to D126) explain the model, and the earlier review findings come with regression cases. Everything below is optional and non-blocking.

    Suggestions (optional)

    1. Two tabs recovering the same stale slot can replay it twice (packages/lexical-y/src/internal/OfflineSession.ts, lines 1426-1453). Turning a slot left at another epoch into a capture takes three separate IndexedDB transactions: load the gone writers' rows, putCapture with a new random id, then discard. Two tabs that recover at the same moment can both read the slot before either deletes it, so it becomes two captures; each tab then claims one and replays the same blocks before the documents sync. Over the PR's own fake IndexedDB this ends with block b1 reading one, mineone, mine in both documents. Doing that step in one readwrite transaction across both object stores (querying the live writers just before it), or under a per-key Web Lock, would keep the "at most once across tabs" guarantee that D124 and y.md state.
    2. limits.bytesPerKey counts the rows a capture replaces (packages/lexical-y/src/internal/OfflineStore.ts, lines 798-815). The capture is checked while the slot's rows are still counted, and both callers put the capture before discarding those rows, so a key needs roughly three documents of room (rows, capture state, base). With bytesPerKey at 2.5x a document, serverEpoch returned saved with code: 'limit', and every later recoverYOfflineEdits returned the same error: the edits stay stored but are never shown or replayed. Checking the capture with those rows as removed (in one transaction), or documenting the headroom bytesPerKey needs, would fix it.
    3. A corrupt slot at another epoch fails the whole recovery (OfflineSession.ts, lines 1427-1431). Its corrupt result becomes the call's result, so healthy captures of the key are not shown either, and YOfflineError has no epoch for the store.clear(key, {epoch, captures: false}) that y.md's error table recommends. Skipping and reporting that slot, or adding epoch to the error, would let an app act on it.
    4. A row of a newer format reads as corrupt (OfflineStore.ts, line 367). isRow accepts only v === ROW_VERSION, and the advice for corrupt is to clear the slot, so a tab still on this release that meets a future row format would be told to delete it. A distinct, non-destructive outcome for v > ROW_VERSION is cheap to add now, before old clients exist.
    5. Tests. A case for each of the above would pin the fixes; the package's AGENTS.md asks for regression tests under src/__tests__/unit/regressions/. Nit: OfflineSession.test.ts, OfflineFaults.test.ts and regressions/OfflineReviewFindings.test.ts build headless editors only, so the repository AGENTS.md's // @vitest-environment node applies to them as it does to OfflineStore.test.ts.
    6. Playground nit. collab-y-offline-status is a role="status" live region (packages/lexical-playground/src/collaborationYOffline.tsx, line 500) whose text flips between "edits waiting to sync" and "synced" each time typing pauses, so a screen reader repeats it while the user types.

    The changeset ('@lexical/y': patch, [feature]) follows CONTRIBUTING.md.

    Automated review (maintainer link)

    <!-- codebunny-pub:1 k=fcc90b370f1af290daf61f4dc5b2ca87fe550bbf7a87600cb0a7fe7bca67e389 -->

    zurfyx zurfyx commented on code on Nov 13, 2026 17:05 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1544 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $getSelection,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`. Pass the result to
    + * {@link attachYOfflineSession} as `loaded`, with `epoch: loaded.epoch`.
    + *
    + * - Without `epoch` (bind, then sync: the page starts from the store, with
    + *   no connection): the newest slot. Create the document from `state`, and
    + *   call `session.serverEpoch(epoch)` when the server names its epoch.
    + * - With `epoch`, the server's (sync, then bind: the page has the server's
    + *   document and epoch before it binds): only the slot at that epoch.
    + *   Apply its `state` to the server's document (the same lineage, so it
    + *   merges: the edits that did not sync go out on the next sync), and bind.
    + *   A slot at another epoch is never loaded: {@link recoverYOfflineEdits}
    + *   turns it into a capture. There is nothing to ask `serverEpoch` until
    + *   the server replaces the room.
    + *
    + * A key has more than one slot only when a tab was left at an earlier
    + * epoch.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +  /** The epoch the server's room is at, when the page knows it before binding. */
    +  readonly epoch?: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const wanted = input.epoch;
    +  requireOption(
    +    wanted === undefined || (typeof wanted === 'string' && wanted !== ''),
    +    `loadYOffline's epoch is the epoch your server's room is at, as a non-empty string (String(epoch) for a number), or left out to load the newest slot; got ${
    +      wanted === '' ? "''" : typeof wanted
    +    }.`,
    +  );
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  const found =
    +    wanted === undefined
    +      ? slots.value[0]
    +      : slots.value.find(info => info.epoch === wanted);
    +  if (found === undefined) {
    +    return ok({
    +      base: null,
    +      epoch: wanted === undefined ? null : wanted,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = found;
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server says the room was replaced, and the new epoch is not known
    +   * yet: the same as `serverEpoch` with a new epoch. The binding is frozen
    +   * before this returns its promise, what it holds is captured into the
    +   * store (for `recoverYOfflineEdits` on the new document), and the
    +   * session ends. Call it on the live session, before disposing it.
    +   */
    +  freeze(options?: {
    +    readonly reason?: YOfflineCapture['reason'];
    +  }): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      // This handle's first row is the whole document, so its later rows
    +      // build only on rows it wrote: another tab may replace the rows it
    +      // loaded. With keep 'unsynced', only when it loaded unsynced rows
    +      // (otherwise its first local edit stores the base and since).
    +      if (
    +        doc.store.clients.size > 0 &&
    +        (!this.keepUnsyncedOnly || this.started)
    +      ) {
    +        if (
    +          loaded !== undefined &&
    +          loaded.state !== null &&
    +          !loaded.hasUnsyncedEdits &&
    +          loaded.base !== null
    +        ) {
    +          // Loaded with nothing unsynced: the document is its base, stored
    +          // as one (a later load reports nothing unsynced).
    +          this.confirmed = {
    +            state: encodeStateAsUpdate(doc),
    +            vector: encodeStateVector(doc),
    +          };
    +        } else {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +        }
    +        void this.write();
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.startGeneration++;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        // A sync and a new local edit while this writes start another
    +        // generation: its own start stays due.
    +        const generation = this.startGeneration;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok && generation === this.startGeneration) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        const syncs = this.syncs;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A sync meanwhile covers the batch: it is not queued again (it
    +          // would be stored as edits the server lacks, or, with keep
    +          // 'unsynced', as a row with no base after the clear).
    +          if (syncs === this.syncs) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** Counts markSynced() calls: a batch whose append failed across one is covered. */
    +  private syncs = 0;
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  /** keep 'unsynced': counts starts, so an old one's end clears no new one. */
    +  private startGeneration = 0;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    this.syncs++;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    return this.moveOn(reason);
    +  }
    +
    +  async freeze(options?: {
    +    readonly reason?: YOfflineCapture['reason'];
    +  }): Promise<YOfflineVerdict> {
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `freeze's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed): freeze() runs on the live session, when the server says the room was replaced.',
    +      );
    +    }
    +    return this.moveOn(reason);
    +  }
    +
    +  /** The room moved on: freeze, capture into the store, end the session. */
    +  private async moveOn(
    +    reason: YOfflineCapture['reason'] | undefined,
    +  ): Promise<YOfflineVerdict> {
    +    // Freeze first, synchronously: from here nothing is written to the
    +    // document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +      this.slot.close();
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    const slot = this.slot;
    +    // What a delay held back is stored, then the writer lock goes (the
    +    // rows become the next handle's to replace).
    +    void (
    +      this.timer !== null || this.writing !== null
    +        ? this.flush()
    +        : Promise.resolve()
    +    ).then(() => {
    +      if (slot !== null) {
    +        slot.close();
    +      }
    +    });
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        return fail({
    +          cause: error,
    +          code: 'failed',
    +          message: `@lexical/y/offline: a state of this capture or the current document could not be read with options.config (${String(
    +            error,
    +          )}); the capture is kept. Check that config holds the editor's nodes and schemaVersion, and offer capture.text meanwhile.`,
    +        });
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report'
    +  /** The editor update failed (the editor's onError has the error). */
    +  | 'not-written';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  // Pushed to `applied` once the update has committed.
    +  const done: string[] = [];
    +  let committed = false;
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          // A caret inside the block would stay on its old nodes, which
    +          // the swap removes: it moves to the end of the new block.
    +          const selection = $getSelection();
    +          const inside =
    +            selection !== null &&
    +            selection
    +              .getNodes()
    +              .some(node => node.is(existing) || existing.isParentOf(node));
    +          existing.replace(made);
    +          if (inside) {
    +            made.selectEnd();
    +          }
    +          byId.set(block.id, made);
    +        } else {
    +          // After the nearest block before it that the document holds.
    +          let anchor: LexicalNode | undefined;
    +          for (let i = order.indexOf(block.id) - 1; i >= 0; i--) {
    +            anchor = byId.get(order[i]);
    +            if (anchor !== undefined) {
    +              break;
    +            }
    +          }
    +          if (anchor !== undefined) {
    +            anchor.insertAfter(made);
    +          } else {
    +            // None before it: before the nearest block after it, else (a
    +            // report without the user's order, or none of their blocks
    +            // left) at the end.
    +            const at = order.indexOf(block.id);
    +            for (let i = at + 1; at >= 0 && i < order.length; i++) {
    +              anchor = byId.get(order[i]);
    +              if (anchor !== undefined) {
    +                break;
    +              }
    +            }
    +            if (anchor !== undefined) {
    +              anchor.insertBefore(made);
    +            } else {
    +              $getRoot().append(made);
    +            }
    +          }
    +          byId.set(block.id, made);
    +        }
    +        done.push(block.id);
    +      }
    +    },
    +    {
    +      discrete: true,
    +      onUpdate: () => {
    +        committed = true;
    +      },
    +    },
    +  );
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  if (committed) {
    +    for (const id of done) {
    +      applied.push(id);
    +    }
    +  } else {
    +    for (const id of done) {
    +      notApplied.push({id, reason: 'not-written'});
    +    }
    +  }
    +  return {applied, notApplied};
    +}
    +
    +/** @experimental One capture of {@link recoverYOfflineEdits}' result. */
    +export interface YOfflineRecovered {
    +  readonly capture: YOfflineCapture;
    +  /** What is left to show, or why the capture could not be read. */
    +  readonly report: YOfflineResult<YOfflineReport>;
    +  /** What the replay stage applied; null when it did not run for this capture. */
    +  readonly replay: YReplayResult | null;
    +}
    +
    +/**
    + * @experimental On a fresh document at the current epoch, after its first
    + * sync: gather what did not sync and, at stage `'replay'`, reapply what is
    + * safe. In order:
    + *
    + * 1. every slot of `key` left at another epoch (a tab that closed before it
    + *    could freeze), or never synced (edits made on this device that never
    + *    reached a server: their base is unknown, so nothing of them is
    + *    replayable), becomes a capture;
    + * 2. each capture is described against the document as it is now;
    + * 3. at stage `'replay'`, each capture this call claims (once, across tabs)
    + *    has its replayable blocks applied as one undo step;
    + * 4. a capture with nothing left to show is deleted once the server holds
    + *    the document: only with `session`, the document's offline session,
    + *    reporting no unsynced edits (after its `markSynced()`). Without it,
    + *    or while the document holds edits the server lacks (a replay that has
    + *    not synced), such a capture is returned with no blocks, for the panel
    + *    to dismiss: until the server holds what was reapplied, the capture may
    + *    be its only stored copy.
    + *
    + * The result is the Offline edits panel's content. Stage `'off'` returns an
    + * empty list and touches nothing.
    + */
    +export async function recoverYOfflineEdits(input: {
    +  /** The fresh document's binding: active, synced, at `epoch`. */
    +  readonly binding: YOfflineBinding;
    +  readonly store: YOfflineStore | null;
    +  readonly key: string;
    +  /** The epoch the fresh document is at. */
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly config: HeadlessYConfig;
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +  /**
    +   * The fresh document's offline session: with it, a capture the server
    +   * already holds (its session reports no unsynced edits) is deleted.
    +   */
    +  readonly session?: YOfflineSession;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}): Promise<YOfflineResult<YOfflineRecovered[]>> {
    +  const entry = 'recoverYOfflineEdits';
    +  requireStage(entry, input.stage);
    +  const {binding, config, epoch, key, migrate, stage, store} = input;
    +  if (stage === 'off' || store === null) {
    +    return ok([]);
    +  }
    +  requireOption(
    +    typeof epoch === 'string' && epoch !== '',
    +    `${entry} needs epoch: the epoch the fresh document is at, as a non-empty string.`,
    +  );
    +  const now = input.now ?? Date.now;
    +  // 1. Slots left at another epoch.
    +  const slots = await store.slots(key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  for (const info of slots.value) {
    +    if (info.epoch === epoch) {
    +      continue;
    +    }
    +    // Through a handle, which then owns exactly the rows it read: only
    +    // rows whose writer is gone. A tab still open at that epoch keeps its
    +    // rows, and captures them itself when it learns the epoch moved.
    +    const stale = store.slot(key, info.epoch);
    +    const stored = await stale.load({writers: 'gone'});
    +    if (!stored.ok) {
    +      // Left as it is, for the app to salvage or clear.
    +      return stored;
    +    }
    +    if (stored.value !== null && stored.value.hasUnsyncedEdits) {
    +      const saved = await store.putCapture({
    +        base: stored.value.base,
    +        capturedAt: now(),
    +        claimed: false,
    +        differs: false,
    +        epoch: info.epoch,
    +        id: newCaptureId(now()),
    +        json: null,
    +        key,
    +        reason: 'stale',
    +        state: stored.value.state,
    +        text: null,
    +      });
    +      if (!saved.ok) {
    +        return saved;
    +      }
    +    }
    +    const discarded = await stale.discard();
    +    if (!discarded.ok) {
    +      return discarded;
    +    }

    Fixed: a slot left at another epoch now becomes a capture in one readwrite transaction over both stores (store.captureSlot, live writers queried just before), so a second tab finds no rows. Regression: regressions/OfflineReviewFindings.test.ts case 10, and a browser test with two real connections.

    zurfyx zurfyx commented on code on Nov 13, 2026 17:05 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1544 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $getSelection,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`. Pass the result to
    + * {@link attachYOfflineSession} as `loaded`, with `epoch: loaded.epoch`.
    + *
    + * - Without `epoch` (bind, then sync: the page starts from the store, with
    + *   no connection): the newest slot. Create the document from `state`, and
    + *   call `session.serverEpoch(epoch)` when the server names its epoch.
    + * - With `epoch`, the server's (sync, then bind: the page has the server's
    + *   document and epoch before it binds): only the slot at that epoch.
    + *   Apply its `state` to the server's document (the same lineage, so it
    + *   merges: the edits that did not sync go out on the next sync), and bind.
    + *   A slot at another epoch is never loaded: {@link recoverYOfflineEdits}
    + *   turns it into a capture. There is nothing to ask `serverEpoch` until
    + *   the server replaces the room.
    + *
    + * A key has more than one slot only when a tab was left at an earlier
    + * epoch.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +  /** The epoch the server's room is at, when the page knows it before binding. */
    +  readonly epoch?: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const wanted = input.epoch;
    +  requireOption(
    +    wanted === undefined || (typeof wanted === 'string' && wanted !== ''),
    +    `loadYOffline's epoch is the epoch your server's room is at, as a non-empty string (String(epoch) for a number), or left out to load the newest slot; got ${
    +      wanted === '' ? "''" : typeof wanted
    +    }.`,
    +  );
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  const found =
    +    wanted === undefined
    +      ? slots.value[0]
    +      : slots.value.find(info => info.epoch === wanted);
    +  if (found === undefined) {
    +    return ok({
    +      base: null,
    +      epoch: wanted === undefined ? null : wanted,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = found;
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server says the room was replaced, and the new epoch is not known
    +   * yet: the same as `serverEpoch` with a new epoch. The binding is frozen
    +   * before this returns its promise, what it holds is captured into the
    +   * store (for `recoverYOfflineEdits` on the new document), and the
    +   * session ends. Call it on the live session, before disposing it.
    +   */
    +  freeze(options?: {
    +    readonly reason?: YOfflineCapture['reason'];
    +  }): Promise<YOfflineVerdict>;
    +  /**
    +   * The server holds everything this document holds: the document becomes
    +   * the base later edits are judged against, and what is stored since is
    +   * replaced by it. Call it when the server acknowledged every update (a
    +   * provider that counts unsynced changes reports none), or, with a relay
    +   * that acknowledges nothing, when the provider has synced. That leaves a
    +   * window: an edit sent in the sync that never arrived is in the base, so
    +   * a capture made later does not list it. Never call it for a document
    +   * the server has not received.
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      // This handle's first row is the whole document, so its later rows
    +      // build only on rows it wrote: another tab may replace the rows it
    +      // loaded. With keep 'unsynced', only when it loaded unsynced rows
    +      // (otherwise its first local edit stores the base and since).
    +      if (
    +        doc.store.clients.size > 0 &&
    +        (!this.keepUnsyncedOnly || this.started)
    +      ) {
    +        if (
    +          loaded !== undefined &&
    +          loaded.state !== null &&
    +          !loaded.hasUnsyncedEdits &&
    +          loaded.base !== null
    +        ) {
    +          // Loaded with nothing unsynced: the document is its base, stored
    +          // as one (a later load reports nothing unsynced).
    +          this.confirmed = {
    +            state: encodeStateAsUpdate(doc),
    +            vector: encodeStateVector(doc),
    +          };
    +        } else {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +        }
    +        void this.write();
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.startGeneration++;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        // A sync and a new local edit while this writes start another
    +        // generation: its own start stays due.
    +        const generation = this.startGeneration;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok && generation === this.startGeneration) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        const syncs = this.syncs;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A sync meanwhile covers the batch: it is not queued again (it
    +          // would be stored as edits the server lacks, or, with keep
    +          // 'unsynced', as a row with no base after the clear).
    +          if (syncs === this.syncs) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** Counts markSynced() calls: a batch whose append failed across one is covered. */
    +  private syncs = 0;
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  /** keep 'unsynced': counts starts, so an old one's end clears no new one. */
    +  private startGeneration = 0;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    this.syncs++;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    return this.moveOn(reason);
    +  }
    +
    +  async freeze(options?: {
    +    readonly reason?: YOfflineCapture['reason'];
    +  }): Promise<YOfflineVerdict> {
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `freeze's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed): freeze() runs on the live session, when the server says the room was replaced.',
    +      );
    +    }
    +    return this.moveOn(reason);
    +  }
    +
    +  /** The room moved on: freeze, capture into the store, end the session. */
    +  private async moveOn(
    +    reason: YOfflineCapture['reason'] | undefined,
    +  ): Promise<YOfflineVerdict> {
    +    // Freeze first, synchronously: from here nothing is written to the
    +    // document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();
    +    const capture: YOfflineCapture | null =
    +      wasUnsynced || edits.differs
    +        ? {
    +            base: this.base,
    +            capturedAt: this.now(),
    +            claimed: false,
    +            differs: edits.differs,
    +            epoch: from,
    +            id: newCaptureId(this.now()),
    +            json: edits.json,
    +            key,
    +            reason: reason ?? 'stale',
    +            state: edits.state,
    +            text: edits.text,
    +          }
    +        : null;
    +    if (store === null) {
    +      return {capture, kind: 'moved', saved: DONE};
    +    }
    +    let saved: YOfflineResult<void> = DONE;
    +    if (capture !== null) {
    +      saved = await store.putCapture(capture);
    +      if (!saved.ok) {
    +        // The slot (when there is one) keeps the edits, with what the
    +        // freeze just committed: the next page captures them from it.
    +        this.isPersisted = false;
    +        this.report(saved.error);
    +        await this.flush();
    +        return {capture, kind: 'moved', saved};
    +      }
    +    }
    +    if (this.slot !== null) {
    +      // What was queued is in the capture; this page's rows are stale.
    +      // Only its own: another tab at the old epoch may hold edits it has
    +      // not captured yet.
    +      this.pending = [];
    +      this.confirmed = null;
    +      this.adopting = null;
    +      this.clearing = false;
    +      this.startPending = false;
    +      await this.writing;
    +      const discarded = await this.slot.discard();
    +      if (!discarded.ok) {
    +        this.report(discarded.error);
    +      }
    +      this.slot.close();
    +    }
    +    return {capture, kind: 'moved', saved};
    +  }
    +
    +  dispose(): void {
    +    this.isEnded = true;
    +    this.stop();
    +    const slot = this.slot;
    +    // What a delay held back is stored, then the writer lock goes (the
    +    // rows become the next handle's to replace).
    +    void (
    +      this.timer !== null || this.writing !== null
    +        ? this.flush()
    +        : Promise.resolve()
    +    ).then(() => {
    +      if (slot !== null) {
    +        slot.close();
    +      }
    +    });
    +  }
    +}
    +
    +/**
    + * @experimental Attach the offline layer to a bound editor. Start here:
    + *
    + * 1. `const opened = await openYOfflineStore({idb: {indexedDB, IDBKeyRange}})`;
    + * 2. `const loaded = await loadYOffline({store, key})`, and create the
    + *    document from `loaded.state` (null: none stored, fetch it);
    + * 3. `const session = attachYOfflineSession({binding, store, key, epoch:
    + *    loaded.epoch, loaded, stage, onError})`;
    + * 4. `await session.serverEpoch(epoch)` whenever the server names its epoch:
    + *    before the provider syncs (every connect and reconnect), and when the
    + *    room is replaced or upgraded. `'same'` means sync, `'moved'` means the
    + *    document was frozen and captured;
    + * 5. `session.markSynced()` when the server holds the document;
    + * 6. on the document the page syncs (a fresh one after `'moved'`),
    + *    `await recoverYOfflineEdits({...})` for the Offline edits panel (and
    + *    the replay, at stage `'replay'`).
    + */
    +export function attachYOfflineSession(
    +  options: YOfflineSessionOptions,
    +): YOfflineSession {
    +  const entry = 'attachYOfflineSession';
    +  requireOption(
    +    typeof options === 'object' && options !== null,
    +    `${entry} needs options: {binding, store, key, epoch, stage, onError}.`,
    +  );
    +  requireStage(entry, options.stage);
    +  requireOption(
    +    typeof options.binding === 'object' &&
    +      options.binding !== null &&
    +      typeof options.binding.freeze === 'function',
    +    `${entry} needs binding: what createYBinding(editor, {...}) returns, or the collab output of YCollabExtension configured with yCollab({...}).`,
    +  );
    +  requireOption(
    +    typeof options.key === 'string' && options.key !== '',
    +    `${entry} needs key: a non-empty string that names the document in your app (its id).`,
    +  );
    +  requireOption(
    +    options.epoch === null ||
    +      (typeof options.epoch === 'string' && options.epoch !== ''),
    +    `${entry} needs epoch: the epoch (generation) the document was made against as a string (String(epoch) for a number; loaded.epoch for a document from loadYOffline), or null for a document that never synced.`,
    +  );
    +  requireOption(
    +    options.persistEdits === undefined ||
    +      typeof options.persistEdits === 'boolean',
    +    `${entry}'s persistEdits is true (the default: store every edit as it is made, so the document survives a reload with no connection) or false (store only captures); got ${typeof options.persistEdits}.`,
    +  );
    +  requireOption(
    +    typeof options.onError === 'function',
    +    `${entry} needs onError: a function that tells the user their edits are not saved on this device (a full quota, a closed store), so a storage failure is never silent.`,
    +  );
    +  requireOption(
    +    options.keep === undefined ||
    +      options.keep === 'document' ||
    +      options.keep === 'unsynced',
    +    `${entry}'s keep is 'document' (the default: store the whole document, to open it with no connection) or 'unsynced' (store only while the server lacks edits; markSynced() deletes them); got ${String(options.keep)}.`,
    +  );
    +  requireOption(
    +    options.writeDelay === undefined ||
    +      (typeof options.writeDelay === 'number' && options.writeDelay >= 0),
    +    `${entry}'s writeDelay is the milliseconds to wait for updates to pause before storing them (0 or more); got ${String(options.writeDelay)}.`,
    +  );
    +  requireOption(
    +    options.store !== null || options.stage === 'off',
    +    `${entry} needs store at stage '${options.stage}': pass the value of openYOfflineStore({idb}) (when it failed, run this session at stage 'off' and tell the user).`,
    +  );
    +  requireOption(
    +    options.loaded === undefined || options.loaded.epoch === options.epoch,
    +    `${entry} got a loaded document of another epoch: pass epoch: loaded.epoch (the server's epoch goes to session.serverEpoch(epoch), which captures the document when they differ).`,
    +  );
    +  return new Session(options);
    +}
    +
    +/**
    + * @experimental A capture's report: `describeUnsyncedEdits`' without the
    + * blocks the document already holds as the user had them.
    + */
    +export interface YOfflineReport extends YUnsyncedReport {
    +  readonly captureId: string;
    +  /**
    +   * The ids of the user's blocks, in their document's order (what places a
    +   * replayed added block).
    +   */
    +  readonly order: readonly string[];
    +  /** Blocks left out because the document already holds them as the user had them. */
    +  readonly inDocument: readonly string[];
    +  /**
    +   * Whether the blocks both documents hold are in another order in the
    +   * user's (they, or someone since, moved a block): no entry of `blocks`
    +   * says so, and a capture with it is kept until the user dismisses it.
    +   */
    +  readonly orderDiffers: boolean;
    +}
    +
    +const sameJSON = (a: unknown, b: unknown) =>
    +  JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
    +
    +function blockIdOf(node: SerializedLexicalNode): string | null {
    +  const state = (node as {$?: {blockId?: unknown}}).$;
    +  const id = state === undefined ? undefined : state.blockId;
    +  return typeof id === 'string' && id !== '' ? id : null;
    +}
    +
    +/** The ids of `blocks`, by position where any block lacks one (as the report names them). */
    +function idsOf(blocks: readonly SerializedLexicalNode[]): string[] {
    +  const ids = blocks.map(blockIdOf);
    +  return ids.every(id => id !== null) && new Set(ids).size === ids.length
    +    ? (ids as string[])
    +    : blocks.map((_, i) => `#${i}`);
    +}
    +
    +const isReadOnly = (error: unknown): boolean =>
    +  error instanceof YHeadlessError && error.code === 'read-only';
    +
    +/** @experimental What {@link describeYOfflineCapture} reads a capture with. */
    +export interface YOfflineDescribeOptions {
    +  /** The document as it is now (`encodeStateAsUpdate(doc)` of the fresh one). */
    +  readonly current: Uint8Array;
    +  /** The headless configuration of your editor (its nodes, `schemaVersion`). */
    +  readonly config: HeadlessYConfig;
    +  /**
    +   * Brings a state this release cannot read (a layout below `MIN_LAYOUT`)
    +   * up to one it can, with your app's migration steps (`migrateYState` on
    +   * `@lexical/y/migrate`). Without it, such a base is reported as gone
    +   * (nothing replayable) and such a capture without JSON cannot be read.
    +   */
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +}
    +
    +/**
    + * @experimental What a capture changed, block by block
    + * (`describeUnsyncedEdits`), against the document as it is now. Blocks the
    + * document already holds as the user had them are left out (an edit that
    + * did reach the server, or one already reapplied): an empty `blocks` with
    + * `orderDiffers` false means the capture can be deleted.
    + */
    +export function describeYOfflineCapture(
    +  capture: YOfflineCapture,
    +  options: YOfflineDescribeOptions,
    +): YOfflineResult<YOfflineReport> {
    +  const {config, current, migrate} = options;
    +  const describe = (
    +    edits: {json: SerializedEditorState} | {state: Uint8Array},
    +    against: Uint8Array | null,
    +  ) =>
    +    describeUnsyncedEdits({
    +      base: against,
    +      capturedAt: capture.capturedAt,
    +      config,
    +      current,
    +      edits,
    +      reason: capture.reason,
    +    });
    +  const json = capture.json as SerializedEditorState | null;
    +  // The captured state is what is compared, read as the base and the
    +  // current document are; the editor's JSON only where it holds more than
    +  // the document (a refused edit) or the state cannot be read. A node can
    +  // serialize differently in a live editor than in a headless read (a
    +  // nested editor it normalized locally), which would list it as changed.
    +  let state = capture.state;
    +  let useState = json === null || !capture.differs;
    +  let migratedState = false;
    +  let base = capture.base;
    +  let report: YUnsyncedReport | null = null;
    +  let yours: SerializedLexicalNode[] = [];
    +  // A state below the floor is refused as read only: at most once for the
    +  // base and twice for the capture's state (migrated, then left for JSON).
    +  for (let attempt = 0; attempt < 4 && report === null; attempt++) {
    +    try {
    +      report = describe(useState || json === null ? {state} : {json}, base);
    +      yours =
    +        useState || json === null
    +          ? readBlocks(state, config)
    +          : json.root.children;
    +    } catch (error) {
    +      if (!isReadOnly(error)) {
    +        return fail({
    +          cause: error,
    +          code: 'failed',
    +          message: `@lexical/y/offline: a state of this capture or the current document could not be read with options.config (${String(
    +            error,
    +          )}); the capture is kept. Check that config holds the editor's nodes and schemaVersion, and offer capture.text meanwhile.`,
    +        });
    +      }
    +      report = null;
    +      try {
    +        if (base !== null && unreadable(base, config)) {
    +          base = migrate === undefined ? null : migrate(base);
    +          if (base !== null && unreadable(base, config)) {
    +            base = null;
    +          }
    +          continue;
    +        }
    +        if (useState && unreadable(state, config)) {
    +          if (migrate !== undefined && !migratedState) {
    +            state = migrate(state);
    +            migratedState = true;
    +            continue;
    +          }
    +          if (json !== null) {
    +            useState = false;
    +            continue;
    +          }
    +        }
    +      } catch (migrationError) {
    +        return fail({
    +          cause: migrationError,
    +          code: 'failed',
    +          message:
    +            '@lexical/y/offline: options.migrate threw on a stored state; the capture is kept. Offer its text (capture.text) and fix the migration.',
    +        });
    +      }
    +      return fail({
    +        cause: error,
    +        code: 'failed',
    +        message:
    +          "@lexical/y/offline: a state of this capture or the current document is read only for this release (a layout below MIN_LAYOUT, or a newer schema), so it cannot be compared. Pass options.migrate (migrateYState from @lexical/y/migrate with your steps) to read older layouts; the capture is kept, and capture.text still holds the user's text when it was frozen.",
    +      });
    +    }
    +  }
    +  if (report === null) {
    +    return fail({
    +      code: 'failed',
    +      message:
    +        '@lexical/y/offline: options.migrate returned a state this release still cannot read; migrate to the layout the current document records.',
    +    });
    +  }
    +  // A block the user only moved is in no entry: it is told from the order
    +  // of the blocks both documents hold (by id; positions say nothing).
    +  const order = idsOf(yours);
    +  let orderDiffers = false;
    +  if (order.length > 0 && !order[0].startsWith('#')) {
    +    const now = idsOf(readBlocks(current, config));
    +    const theirs = new Set(now);
    +    const mine = new Set(order);
    +    orderDiffers =
    +      order.filter(id => theirs.has(id)).join('\u0000') !==
    +      now.filter(id => mine.has(id)).join('\u0000');
    +  }
    +  const inDocument: string[] = [];
    +  const blocks: YUnsyncedBlock[] = [];
    +  for (const block of report.blocks) {
    +    if (sameJSON(block.yours, block.now)) {
    +      inDocument.push(block.id);
    +    } else {
    +      blocks.push(block);
    +    }
    +  }
    +  return ok({
    +    ...report,
    +    blocks,
    +    captureId: capture.id,
    +    fragment: blocks.flatMap(block =>
    +      block.yours === null ? [] : [block.yours],
    +    ),
    +    inDocument,
    +    order,
    +    orderDiffers,
    +  });
    +}
    +
    +/** The top-level blocks of a readable state (as describeUnsyncedEdits reads them). */
    +function readBlocks(
    +  state: Uint8Array,
    +  config: HeadlessYConfig,
    +): SerializedLexicalNode[] {
    +  return readYState(
    +    state,
    +    config,
    +    () => $getEditor().getEditorState().toJSON().root.children,
    +  );
    +}
    +
    +/** Whether this release refuses to read `state` (a layout below the floor). */
    +function unreadable(state: Uint8Array, config: HeadlessYConfig): boolean {
    +  try {
    +    readBlocks(state, config);
    +    return false;
    +  } catch (error) {
    +    if (isReadOnly(error)) {
    +      return true;
    +    }
    +    throw error;
    +  }
    +}
    +
    +/** @experimental Why a block was not replayed. */
    +export type YReplaySkipReason =
    +  /** The report says the current document no longer matches the base there. */
    +  | 'not-replayable'
    +  /** The document changed there since the report was made. */
    +  | 'changed-since'
    +  /** The editor's blocks have no ids (BlockIdExtension), so none can be found. */
    +  | 'no-block-ids'
    +  /** The block's JSON does not parse with the editor's nodes. */
    +  | 'unreadable'
    +  /** `only` named it, but the report does not hold it. */
    +  | 'not-in-report'
    +  /** The editor update failed (the editor's onError has the error). */
    +  | 'not-written';
    +
    +/** @experimental What {@link replayUnsyncedEdits} did. */
    +export interface YReplayResult {
    +  /** The ids of the blocks applied, in the order applied. */
    +  readonly applied: readonly string[];
    +  /** The blocks left for the panel, with why. */
    +  readonly notApplied: readonly {
    +    readonly id: string;
    +    readonly reason: YReplaySkipReason;
    +  }[];
    +}
    +
    +/**
    + * @experimental Apply a report's replayable blocks to the bound editor, as
    + * one editor update the binding writes and one undo step: a changed block
    + * replaces the current one, an added block is inserted after the nearest
    + * block before it that the document holds (before the nearest after it when
    + * there is none; at the end for a plain `YUnsyncedReport`, which does not
    + * carry the user's order), a deleted block is removed. Each
    + * is checked again against the editor as it is now (the block still equals
    + * the base, an added block's id is still absent), so a block someone else
    + * changed is never overwritten: it comes back in `notApplied`.
    + *
    + * `only` limits it to those block ids (the panel's Reapply button). Call it
    + * outside an editor update (not from an update listener or a command
    + * handler): the edit must be written before it returns.
    + *
    + * @example
    + * ```ts
    + * const {applied, notApplied} = replayUnsyncedEdits({binding, report});
    + * ```
    + */
    +export function replayUnsyncedEdits(input: {
    +  readonly binding: YOfflineBinding;
    +  readonly report: YOfflineReport | YUnsyncedReport;
    +  readonly only?: readonly string[];
    +}): YReplayResult {
    +  const {binding, only, report} = input;
    +  if (binding.status.kind !== 'active') {
    +    throw new Error(
    +      `@lexical/y/offline: replayUnsyncedEdits needs an active binding (it is ${
    +        binding.status.kind
    +      }): replay into the fresh document at the current epoch, after binding.markSynced(), never into the frozen one.`,
    +    );
    +  }
    +  const editor = binding.binding.editor;
    +  const applied: string[] = [];
    +  const notApplied: {id: string; reason: YReplaySkipReason}[] = [];
    +  const wanted = only === undefined ? null : new Set(only);
    +  if (wanted !== null) {
    +    for (const id of wanted) {
    +      if (!report.blocks.some(block => block.id === id)) {
    +        notApplied.push({id, reason: 'not-in-report'});
    +      }
    +    }
    +  }
    +  const candidates = report.blocks.filter(
    +    block => wanted === null || wanted.has(block.id),
    +  );
    +  // The editor as it is now (a pending update included).
    +  const live = editor.read(
    +    () => editor.getEditorState().toJSON().root.children,
    +  );
    +  const liveIds = live.map(blockIdOf);
    +  const hasIds =
    +    liveIds.every(id => id !== null) &&
    +    new Set(liveIds).size === liveIds.length;
    +  const liveIndex = new Map<string, number>();
    +  if (hasIds) {
    +    liveIds.forEach((id, i) => liveIndex.set(id as string, i));
    +  }
    +  const order = 'order' in report ? report.order : [];
    +  const todo: YUnsyncedBlock[] = [];
    +  for (const block of candidates) {
    +    if (!block.replayable) {
    +      notApplied.push({id: block.id, reason: 'not-replayable'});
    +    } else if (!hasIds) {
    +      notApplied.push({id: block.id, reason: 'no-block-ids'});
    +    } else {
    +      const at = liveIndex.get(block.id);
    +      const now = at === undefined ? null : live[at];
    +      if (!sameJSON(now, block.base)) {
    +        notApplied.push({id: block.id, reason: 'changed-since'});
    +      } else {
    +        todo.push(block);
    +      }
    +    }
    +  }
    +  if (todo.length === 0) {
    +    return {applied, notApplied};
    +  }
    +  const um = binding.binding.undoManager;
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  // Pushed to `applied` once the update has committed.
    +  const done: string[] = [];
    +  let committed = false;
    +  editor.update(
    +    () => {
    +      const nodes = $getRoot().getChildren();
    +      const byId = new Map<string, LexicalNode>();
    +      liveIds.forEach((id, i) => {
    +        if (nodes[i] !== undefined) {
    +          byId.set(id as string, nodes[i]);
    +        }
    +      });
    +      for (const block of todo) {
    +        let made: LexicalNode | null = null;
    +        if (block.yours !== null) {
    +          try {
    +            made = $parseSerializedNode(block.yours);
    +          } catch {
    +            notApplied.push({id: block.id, reason: 'unreadable'});
    +            continue;
    +          }
    +        }
    +        const existing = byId.get(block.id);
    +        if (made === null) {
    +          if (existing !== undefined) {
    +            existing.remove();
    +            byId.delete(block.id);
    +          }
    +        } else if (existing !== undefined) {
    +          // A caret inside the block would stay on its old nodes, which
    +          // the swap removes: it moves to the end of the new block.
    +          const selection = $getSelection();
    +          const inside =
    +            selection !== null &&
    +            selection
    +              .getNodes()
    +              .some(node => node.is(existing) || existing.isParentOf(node));
    +          existing.replace(made);
    +          if (inside) {
    +            made.selectEnd();
    +          }
    +          byId.set(block.id, made);
    +        } else {
    +          // After the nearest block before it that the document holds.
    +          let anchor: LexicalNode | undefined;
    +          for (let i = order.indexOf(block.id) - 1; i >= 0; i--) {
    +            anchor = byId.get(order[i]);
    +            if (anchor !== undefined) {
    +              break;
    +            }
    +          }
    +          if (anchor !== undefined) {
    +            anchor.insertAfter(made);
    +          } else {
    +            // None before it: before the nearest block after it, else (a
    +            // report without the user's order, or none of their blocks
    +            // left) at the end.
    +            const at = order.indexOf(block.id);
    +            for (let i = at + 1; at >= 0 && i < order.length; i++) {
    +              anchor = byId.get(order[i]);
    +              if (anchor !== undefined) {
    +                break;
    +              }
    +            }
    +            if (anchor !== undefined) {
    +              anchor.insertBefore(made);
    +            } else {
    +              $getRoot().append(made);
    +            }
    +          }
    +          byId.set(block.id, made);
    +        }
    +        done.push(block.id);
    +      }
    +    },
    +    {
    +      discrete: true,
    +      onUpdate: () => {
    +        committed = true;
    +      },
    +    },
    +  );
    +  if (um !== null) {
    +    um.stopCapturing();
    +  }
    +  if (committed) {
    +    for (const id of done) {
    +      applied.push(id);
    +    }
    +  } else {
    +    for (const id of done) {
    +      notApplied.push({id, reason: 'not-written'});
    +    }
    +  }
    +  return {applied, notApplied};
    +}
    +
    +/** @experimental One capture of {@link recoverYOfflineEdits}' result. */
    +export interface YOfflineRecovered {
    +  readonly capture: YOfflineCapture;
    +  /** What is left to show, or why the capture could not be read. */
    +  readonly report: YOfflineResult<YOfflineReport>;
    +  /** What the replay stage applied; null when it did not run for this capture. */
    +  readonly replay: YReplayResult | null;
    +}
    +
    +/**
    + * @experimental On a fresh document at the current epoch, after its first
    + * sync: gather what did not sync and, at stage `'replay'`, reapply what is
    + * safe. In order:
    + *
    + * 1. every slot of `key` left at another epoch (a tab that closed before it
    + *    could freeze), or never synced (edits made on this device that never
    + *    reached a server: their base is unknown, so nothing of them is
    + *    replayable), becomes a capture;
    + * 2. each capture is described against the document as it is now;
    + * 3. at stage `'replay'`, each capture this call claims (once, across tabs)
    + *    has its replayable blocks applied as one undo step;
    + * 4. a capture with nothing left to show is deleted once the server holds
    + *    the document: only with `session`, the document's offline session,
    + *    reporting no unsynced edits (after its `markSynced()`). Without it,
    + *    or while the document holds edits the server lacks (a replay that has
    + *    not synced), such a capture is returned with no blocks, for the panel
    + *    to dismiss: until the server holds what was reapplied, the capture may
    + *    be its only stored copy.
    + *
    + * The result is the Offline edits panel's content. Stage `'off'` returns an
    + * empty list and touches nothing.
    + */
    +export async function recoverYOfflineEdits(input: {
    +  /** The fresh document's binding: active, synced, at `epoch`. */
    +  readonly binding: YOfflineBinding;
    +  readonly store: YOfflineStore | null;
    +  readonly key: string;
    +  /** The epoch the fresh document is at. */
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly config: HeadlessYConfig;
    +  readonly migrate?: (state: Uint8Array) => Uint8Array;
    +  /**
    +   * The fresh document's offline session: with it, a capture the server
    +   * already holds (its session reports no unsynced edits) is deleted.
    +   */
    +  readonly session?: YOfflineSession;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}): Promise<YOfflineResult<YOfflineRecovered[]>> {
    +  const entry = 'recoverYOfflineEdits';
    +  requireStage(entry, input.stage);
    +  const {binding, config, epoch, key, migrate, stage, store} = input;
    +  if (stage === 'off' || store === null) {
    +    return ok([]);
    +  }
    +  requireOption(
    +    typeof epoch === 'string' && epoch !== '',
    +    `${entry} needs epoch: the epoch the fresh document is at, as a non-empty string.`,
    +  );
    +  const now = input.now ?? Date.now;
    +  // 1. Slots left at another epoch.
    +  const slots = await store.slots(key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  for (const info of slots.value) {
    +    if (info.epoch === epoch) {
    +      continue;
    +    }
    +    // Through a handle, which then owns exactly the rows it read: only
    +    // rows whose writer is gone. A tab still open at that epoch keeps its
    +    // rows, and captures them itself when it learns the epoch moved.
    +    const stale = store.slot(key, info.epoch);
    +    const stored = await stale.load({writers: 'gone'});
    +    if (!stored.ok) {
    +      // Left as it is, for the app to salvage or clear.
    +      return stored;

    Done: YOfflineError carries epoch for a slot's 'corrupt' (and 'newer'), so the app can store.clear(key, {epoch: error.epoch, captures: false}) and call recovery again. Regression: case 12.

    zurfyx zurfyx commented on code on Nov 13, 2026 17:05 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineStore.ts:1
    @@ -0,0 +1,1408 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// Local persistence for Yjs 14 documents (`@lexical/y/offline`): a document's
    +// updates in IndexedDB, by an app-chosen key and the epoch (generation) the
    +// document was made against. No provider for Yjs 14 exists (`y-indexeddb`
    +// imports Yjs 13), and none keys by epoch or reports quota and corruption, so
    +// this one is written here on IndexedDB alone, with `@y/y` used only to merge
    +// updates.
    +//
    +// A slot (key, epoch) holds rows of two kinds:
    +//
    +// - `base`: a state the server is known to hold (written by `confirm`);
    +// - `since`: every update the document made or received after it.
    +//
    +// The document is their merge; what the server may lack is in `since`. Rows
    +// are keyed `[key, epoch, kind, writer, n]` with a random `writer` per slot
    +// handle, so two tabs on one key never overwrite each other. A handle only
    +// replaces rows it owns (the ones it loaded or wrote, all of which its
    +// document holds): another tab's rows stay until that tab, or a later load,
    +// replaces them.
    +
    +import {mergeUpdates} from '@y/y';
    +
    +/**
    + * @experimental The defaults of the optional fields of `@lexical/y/offline`,
    + * by name, so code can say which it relies on.
    + */
    +export const Y_OFFLINE_DEFAULTS: {
    +  readonly databaseName: string;
    +  readonly compactAfter: number;
    +  readonly openTimeout: number;
    +} = /* @__PURE__ */ Object.freeze({
    +  /** `since` rows a slot handle writes before it compacts them into one. */
    +  compactAfter: 64,
    +  databaseName: 'lexical-y-offline',
    +  /** Milliseconds openYOfflineStore waits for the database to open. */
    +  openTimeout: 10000,
    +});
    +
    +/** @experimental What failed (see {@link YOfflineError}). */
    +export type YOfflineErrorCode =
    +  /** There is no IndexedDB here (a private window, Node without a fake). */
    +  | 'unavailable'
    +  /** Another tab holds an older version of the database open. */
    +  | 'blocked'
    +  /** The browser refused the write: the origin's storage quota is full. */
    +  | 'quota'
    +  /** A stored row is not what this module wrote, or does not decode. */
    +  | 'corrupt'
    +  /** The store was closed (`store.close()`, or the database was deleted). */
    +  | 'closed'
    +  /**
    +   * The write would pass one of the store's `limits` (see `limit`): it was
    +   * refused, and nothing was evicted.
    +   */
    +  | 'limit'
    +  /** Any other IndexedDB failure; `cause` holds it. */
    +  | 'failed';
    +
    +/**
    + * @experimental A failure of the local store. Nothing here throws for a
    + * storage failure: every call returns a {@link YOfflineResult}, and
    + * `message` says what to do.
    + */
    +export interface YOfflineError {
    +  readonly code: YOfflineErrorCode;
    +  /** What happened and what the app can do about it. */
    +  readonly message: string;
    +  /** The underlying error, when there is one. */
    +  readonly cause?: unknown;
    +  /**
    +   * With `'corrupt'`: what the readable rows hold (their merge, the base
    +   * apart), so the app can offer it before clearing the slot.
    +   */
    +  readonly salvage?: YOfflineSalvage;
    +  /** With `'limit'`: which limit (see {@link YOfflineLimits}). */
    +  readonly limit?: 'keys' | 'bytes';
    +}
    +
    +/**
    + * @experimental Caps a store keeps by refusing writes (`'limit'`), never by
    + * evicting: what is stored stays until the app clears it.
    + */
    +export interface YOfflineLimits {
    +  /** Most keys stored per group (a new key past it is refused). */
    +  readonly keys?: number;
    +  /**
    +   * Most bytes stored per key: its rows' updates and its captures' states
    +   * and bases (a capture's JSON and text are not counted). Each connection
    +   * counts what it last read of the key plus what it wrote since; another
    +   * tab's writes count from its next read (a compaction, a confirmation, a
    +   * capture), so tabs writing at once can pass it by what they wrote since.
    +   */
    +  readonly bytesPerKey?: number;
    +  /**
    +   * The group a key counts in for `keys`, e.g. its viewer for keys
    +   * `viewer|doc`: `key => key.split('|')[0]`. Default: one group.
    +   */
    +  readonly group?: (key: string) => string;
    +}
    +
    +/** @experimental What a corrupt slot still holds (see {@link YOfflineError}). */
    +export interface YOfflineSalvage {
    +  /** The merge of every readable row, or null when none is. */
    +  readonly state: Uint8Array | null;
    +  readonly readableRows: number;
    +  readonly unreadableRows: number;
    +}
    +
    +/** @experimental A value, or the error that kept it from being made. */
    +export type YOfflineResult<T> =
    +  | {readonly ok: true; readonly value: T}
    +  | {readonly ok: false; readonly error: YOfflineError};
    +
    +/** @experimental What a slot holds (see {@link YOfflineSlot.load}). */
    +export interface YOfflineStored {
    +  /** The whole document: `base` and `since` merged (a Yjs update). */
    +  readonly state: Uint8Array;
    +  /** The state the server is known to hold, or null when none was confirmed. */
    +  readonly base: Uint8Array | null;
    +  /** Whether updates were stored after `base`: the server may lack them. */
    +  readonly hasUnsyncedEdits: boolean;
    +}
    +
    +/** @experimental One slot of a key (see {@link YOfflineStore.slots}). */
    +export interface YOfflineSlotInfo {
    +  readonly key: string;
    +  /** The epoch the slot's document was made against; null: never synced. */
    +  readonly epoch: string | null;
    +  /** When its newest row was written (Unix ms). */
    +  readonly updatedAt: number;
    +  readonly hasUnsyncedEdits: boolean;
    +  readonly rows: number;
    +}
    +
    +/**
    + * @experimental A frozen copy of a client's document that did not sync,
    + * with the base it was made against: what the Offline edits panel shows.
    + */
    +export interface YOfflineCapture {
    +  /** Unique per key. */
    +  readonly id: string;
    +  readonly key: string;
    +  /** The epoch the edits were made against; null: never synced. */
    +  readonly epoch: string | null;
    +  readonly reason: 'stale' | 'legacy' | 'expired';
    +  /** When it was captured (Unix ms). */
    +  readonly capturedAt: number;
    +  /** The whole document as the client held it (a Yjs update). */
    +  readonly state: Uint8Array;
    +  /**
    +   * The editor's content as Lexical JSON (`freeze()`'s), or null for a
    +   * capture made from storage alone (a tab that closed before it could
    +   * freeze).
    +   */
    +  readonly json: unknown | null;
    +  /** The plain text of the editor, for Copy; null as `json` is. */
    +  readonly text: string | null;
    +  /**
    +   * Whether the editor held edits the document did not (`freeze()`'s
    +   * `differs`): the report then reads `json`, else `state`.
    +   */
    +  readonly differs: boolean;
    +  /** The document the edits were made against, or null when unknown. */
    +  readonly base: Uint8Array | null;
    +  /** Set once a replay stage took the capture (see claimCapture). */
    +  readonly claimed: boolean;
    +}
    +
    +/** @experimental One (key, epoch) of a {@link YOfflineStore}. */
    +export interface YOfflineSlot {
    +  readonly key: string;
    +  /** Changes with {@link YOfflineSlot.adopt}. */
    +  readonly epoch: string | null;
    +  /**
    +   * Read the slot: null when it holds nothing. The rows read become this
    +   * handle's (create the document from `state`, so it holds them). With
    +   * `{writers: 'gone'}`, only rows whose writer is gone (no live tab holds
    +   * them): what recovery captures, leaving a live tab's rows to that tab.
    +   * Without Web Locks (`locks: null`) that is every row.
    +   */
    +  load(options?: {
    +    readonly writers?: 'all' | 'gone';
    +  }): Promise<YOfflineResult<YOfflineStored | null>>;
    +  /** Store one update the document made or received. */
    +  append(update: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * The server holds `state` (the whole document, which holds every row of
    +   * this handle): it becomes the base and this handle's rows are removed.
    +   */
    +  confirm(state: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * Replace this handle's `since` rows by one: `since` when given (what the
    +   * document holds beyond the base), else their merge.
    +   */
    +  compact(since?: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * Delete this handle's rows (the ones it loaded or wrote), and no other:
    +   * for a document that was captured, whose rows another tab at the same
    +   * epoch may still be adding to.
    +   */
    +  discard(): Promise<YOfflineResult<void>>;
    +  /** `since` rows this handle wrote since it last compacted or confirmed. */
    +  readonly rowsSinceCompaction: number;
    +  /**
    +   * Release the handle's writer lock (see `locks`): its rows become another
    +   * handle's to replace. Call it when the document is closed; a closed tab
    +   * releases it on its own.
    +   */
    +  close(): void;
    +  /**
    +   * Move a slot that never synced (`epoch` null) to the epoch the server
    +   * gave it: this handle's rows, and those it loaded whose writer is gone.
    +   * A live tab's rows stay for that tab to move.
    +   */
    +  adopt(epoch: string): Promise<YOfflineResult<void>>;
    +}
    +
    +/** @experimental The local store (see {@link openYOfflineStore}). */
    +export interface YOfflineStore {
    +  /** A handle on one slot; nothing is read or written until it is used. */
    +  slot(key: string, epoch: string | null): YOfflineSlot;
    +  /** The slots stored for `key`, newest first. */
    +  slots(key: string): Promise<YOfflineResult<YOfflineSlotInfo[]>>;
    +  /** The captures stored for `key`, oldest first. */
    +  captures(key: string): Promise<YOfflineResult<YOfflineCapture[]>>;
    +  putCapture(capture: YOfflineCapture): Promise<YOfflineResult<void>>;
    +  /**
    +   * Mark a capture as taken by a replay: true for the one caller that gets
    +   * it (a second tab, or a second call, gets false), so a capture is
    +   * replayed automatically at most once.
    +   */
    +  claimCapture(key: string, id: string): Promise<YOfflineResult<boolean>>;
    +  deleteCapture(key: string, id: string): Promise<YOfflineResult<void>>;
    +  /**
    +   * Delete what is stored for `key`: one slot when `what.epoch` is given
    +   * (null names the never-synced slot), else every slot; its captures too
    +   * with `what.captures`.
    +   */
    +  clear(
    +    key: string,
    +    what: {readonly epoch?: string | null; readonly captures: boolean},
    +  ): Promise<YOfflineResult<void>>;
    +  /** Every key that holds a slot or a capture (for clearing by owner). */
    +  keys(): Promise<YOfflineResult<string[]>>;
    +  /** Close the database: later calls return `'closed'`. */
    +  close(): void;
    +}
    +
    +/** @experimental Options of {@link openYOfflineStore}. */
    +export interface YOfflineStoreOptions {
    +  /**
    +   * The IndexedDB to use. Required, so every caller decides: pass
    +   * `{indexedDB, IDBKeyRange}` from `globalThis` in a browser, or a fake's
    +   * in Node (the store works without a DOM).
    +   */
    +  readonly idb: {
    +    readonly indexedDB: IDBFactory | undefined;
    +    readonly IDBKeyRange: typeof IDBKeyRange | undefined;
    +  };
    +  /**
    +   * The database's name: one per app.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.databaseName`
    +   */
    +  readonly databaseName?: string;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +  /**
    +   * Milliseconds to wait for the database to open before answering
    +   * `'unavailable'` (some browsers never answer an open in some states).
    +   * A connection that opens later is closed.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.openTimeout`
    +   */
    +  readonly openTimeout?: number;
    +  /** Caps kept by refusing writes, never by evicting. Default: none. */
    +  readonly limits?: YOfflineLimits;
    +  /**
    +   * The Web Locks the store tells live tabs by: each writing handle holds a
    +   * lock, and no handle removes rows a live handle wrote (they may be what
    +   * that tab's later rows build on). Rows of a handle that is gone (a
    +   * closed tab, an earlier page load) are replaced by the next handle that
    +   * loads them. Null: every other handle counts as live, so rows of earlier
    +   * page loads are kept until the app clears them.
    +   * @defaultValue `navigator.locks`, where there is one, else null
    +   */
    +  readonly locks?: YOfflineLocks | null;
    +}
    +
    +/** @experimental The part of the Web Locks API the store uses. */
    +export interface YOfflineLocks {
    +  request(
    +    name: string,
    +    callback: (lock: unknown) => Promise<unknown>,
    +  ): Promise<unknown>;
    +  query(): Promise<{readonly held?: readonly {readonly name?: string}[]}>;
    +}
    +
    +/** Wraps a request callback so that what it throws fails the transaction. */
    +type Guard = (fn: () => void) => () => void;
    +
    +const UPDATES = 'updates';
    +const CAPTURES = 'captures';
    +const DB_VERSION = 1;
    +const ROW_VERSION = 1;
    +
    +type RowKind = 'b' | 's';
    +/** `[key, epoch (0 for null), kind, writer, n]`. */
    +type RowKey = [string, string | 0, RowKind, string, number];
    +
    +interface Row {
    +  readonly v: number;
    +  /** The update. */
    +  readonly u: Uint8Array;
    +  /** FNV-1a of `u`: a row cut short or changed does not read as an update. */
    +  readonly h: number;
    +  /** When it was written (Unix ms). */
    +  readonly t: number;
    +}
    +
    +const ok = <T>(value: T): YOfflineResult<T> => ({ok: true, value});
    +const fail = <T>(error: YOfflineError): YOfflineResult<T> => ({
    +  error,
    +  ok: false,
    +});
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +function checksum(bytes: Uint8Array): number {
    +  let h = 0x811c9dc5;
    +  for (let i = 0; i < bytes.length; i++) {
    +    h ^= bytes[i];
    +    h = Math.imul(h, 0x01000193);
    +  }
    +  return h >>> 0;
    +}
    +
    +/**
    + * A Uint8Array of any realm: a value read back from IndexedDB in an iframe,
    + * or under a test runner's VM, is not `instanceof` this realm's.
    + */
    +function isBytes(value: unknown): value is Uint8Array {
    +  return (
    +    ArrayBuffer.isView(value) &&
    +    Object.prototype.toString.call(value) === '[object Uint8Array]'
    +  );
    +}
    +
    +/**
    + * `bytes` with a buffer of its own size: IndexedDB stores a view's whole
    + * buffer, and an update can be a short view of an encoder's long one.
    + */
    +function exact(bytes: Uint8Array): Uint8Array {
    +  return bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
    +}
    +
    +function isRow(value: unknown): value is Row {
    +  if (typeof value !== 'object' || value === null) {
    +    return false;
    +  }
    +  const row = value as Partial<Row>;
    +  return (
    +    row.v === ROW_VERSION &&
    +    isBytes(row.u) &&
    +    row.u.length > 0 &&
    +    typeof row.t === 'number' &&
    +    row.h === checksum(row.u)
    +  );
    +}
    +
    +function merge(updates: readonly Uint8Array[]): Uint8Array | null {
    +  return updates.length === 0
    +    ? null
    +    : updates.length === 1
    +      ? updates[0]
    +      : mergeUpdates(updates as Parameters<typeof mergeUpdates>[0]);
    +}
    +
    +const epochKey = (epoch: string | null): string | 0 =>
    +  epoch === null ? 0 : epoch;
    +const epochOf = (key: string | 0): string | null => (key === 0 ? null : key);
    +
    +function errorName(error: unknown): string {
    +  return typeof error === 'object' && error !== null && 'name' in error
    +    ? String((error as {name: unknown}).name)
    +    : '';
    +}
    +
    +/** A limit a write would pass, thrown inside a transaction to abort it. */
    +class LimitReached {
    +  constructor(readonly error: YOfflineError) {}
    +}
    +
    +/** The typed error of an IndexedDB failure. */
    +function storageError(cause: unknown, doing: string): YOfflineError {
    +  if (cause instanceof LimitReached) {
    +    return cause.error;
    +  }
    +  const name = errorName(cause);
    +  if (name === 'QuotaExceededError') {
    +    return {
    +      cause,
    +      code: 'quota',
    +      message: `@lexical/y/offline: the browser's storage quota is full, so ${doing} was not stored. The edits are still in the page: tell the user they are not saved on this device, free space (store.clear(key, {captures: true}) for documents no longer needed) and the next write retries.`,
    +    };
    +  }
    +  if (name === 'InvalidStateError' || name === 'TransactionInactiveError') {
    +    return {
    +      cause,
    +      code: 'closed',
    +      message: `@lexical/y/offline: the store is closed, so ${doing} did not run; open a new one with openYOfflineStore().`,
    +    };
    +  }
    +  return {
    +    cause,
    +    code: 'failed',
    +    message: `@lexical/y/offline: IndexedDB failed while ${doing} (${
    +      name || String(cause)
    +    }); the edits are still in the page. Retry, or tell the user they are not saved on this device.`,
    +  };
    +}
    +
    +class Store implements YOfflineStore {
    +  private closed = false;
    +  /**
    +   * Bytes stored per key, as this store last read them plus what it wrote
    +   * since (only with `limits.bytesPerKey`, so an append reads nothing). A
    +   * write that removes rows forgets the key: the next write reads it again.
    +   */
    +  private readonly sizes = new Map<string, number>();
    +  constructor(
    +    private readonly db: IDBDatabase,
    +    private readonly range: typeof IDBKeyRange,
    +    readonly now: () => number,
    +    private readonly limits: YOfflineLimits | null,
    +    private readonly locks: YOfflineLocks | null,
    +    private readonly name: string,
    +  ) {
    +    // Another tab upgrades or deletes the database: let it.
    +    db.onversionchange = () => this.close();
    +  }
    +
    +  close(): void {
    +    if (!this.closed) {
    +      this.closed = true;
    +      this.db.close();
    +      for (const release of this.held) {
    +        release();
    +      }
    +      this.held.clear();
    +    }
    +  }
    +
    +  /** Releases of the writer locks this store's handles hold. */
    +  private readonly held = new Set<() => void>();
    +
    +  private lockName(writer: string): string {
    +    return `lexical-y-offline:${this.name}:${writer}`;
    +  }
    +
    +  /**
    +   * Hold `writer`'s lock: resolves once it is held (a row of a writer only
    +   * exists while its lock is held, or after its handle is gone). Returns
    +   * its release.
    +   */
    +  async hold(writer: string): Promise<() => void> {
    +    const locks = this.locks;
    +    if (locks === null) {
    +      return () => {};
    +    }
    +    let release = () => {};
    +    await new Promise<void>(granted => {
    +      void locks.request(this.lockName(writer), () => {
    +        granted();
    +        return new Promise<void>(done => {
    +          release = () => {
    +            this.held.delete(release);
    +            done();
    +          };
    +          this.held.add(release);
    +        });
    +      });
    +    });
    +    return release;
    +  }
    +
    +  /** The writers whose handles are live, or null when that is unknown. */
    +  async liveWriters(): Promise<ReadonlySet<string> | null> {
    +    if (this.locks === null) {
    +      return null;
    +    }
    +    const prefix = this.lockName('');
    +    const {held = []} = await this.locks.query();
    +    const live = new Set<string>();
    +    for (const lock of held) {
    +      if (typeof lock.name === 'string' && lock.name.startsWith(prefix)) {
    +        live.add(lock.name.slice(prefix.length));
    +      }
    +    }
    +    return live;
    +  }
    +
    +  /** Every key that starts with `prefix` (arrays sort after every string and number). */
    +  prefix(prefix: readonly (string | number)[]): IDBKeyRange {
    +    return this.range.bound(prefix, [...prefix, []]);
    +  }
    +
    +  /**
    +   * One transaction: `work` issues its requests (more from their callbacks)
    +   * and the result is what it left in `out` once the transaction commits.
    +   */
    +  run<T>(
    +    stores: string[],
    +    mode: IDBTransactionMode,
    +    doing: string,
    +    work: (tx: IDBTransaction, out: {value: T}, guard: Guard) => void,
    +    initial: T,
    +  ): Promise<YOfflineResult<T>> {
    +    if (this.closed) {
    +      return Promise.resolve(
    +        fail(storageError({name: 'InvalidStateError'}, doing)),
    +      );
    +    }
    +    return new Promise(resolve => {
    +      const out = {value: initial};
    +      let tx: IDBTransaction;
    +      try {
    +        tx = this.db.transaction(stores, mode);
    +      } catch (error) {
    +        resolve(fail(storageError(error, doing)));
    +        return;
    +      }
    +      let failure: unknown = null;
    +      tx.oncomplete = () => resolve(ok(out.value));
    +      tx.onabort = () =>
    +        resolve(fail(storageError(failure ?? tx.error, doing)));
    +      tx.onerror = event => {
    +        // The request's error (a quota failure arrives here, or as the
    +        // transaction's own error on abort).
    +        const target = event.target as IDBRequest | null;
    +        failure = failure ?? (target === null ? null : target.error);
    +      };
    +      const abort = (error: unknown) => {
    +        failure = failure ?? error;
    +        try {
    +          tx.abort();
    +        } catch {
    +          resolve(fail(storageError(error, doing)));
    +        }
    +      };
    +      // A request callback that throws would abort the transaction with no
    +      // error to report (and throw at the window): it is reported instead.
    +      const guard: Guard = fn => () => {
    +        try {
    +          fn();
    +        } catch (error) {
    +          abort(error);
    +        }
    +      };
    +      try {
    +        work(tx, out, guard);
    +      } catch (error) {
    +        abort(error);
    +      }
    +    });
    +  }
    +
    +  slot(key: string, epoch: string | null): YOfflineSlot {
    +    requireKey(key);
    +    requireEpoch(epoch);
    +    return new Slot(this, key, epoch);
    +  }
    +
    +  keys(): Promise<YOfflineResult<string[]>> {
    +    return this.run<string[]>(
    +      [UPDATES, CAPTURES],
    +      'readonly',
    +      'listing the keys',
    +      (tx, out, guard) => {
    +        const keys = new Set<string>();
    +        const updates = tx.objectStore(UPDATES).getAllKeys();
    +        updates.onsuccess = guard(() => {
    +          for (const k of updates.result as RowKey[]) {
    +            keys.add(k[0]);
    +          }
    +          const captures = tx.objectStore(CAPTURES).getAllKeys();
    +          captures.onsuccess = guard(() => {
    +            for (const k of captures.result as [string, string][]) {
    +              keys.add(k[0]);
    +            }
    +            out.value = [...keys].sort();
    +          });
    +        });
    +      },
    +      [],
    +    );
    +  }
    +
    +  /**
    +   * The object stores a write needs: with limits, both (the check reads
    +   * the key's rows and captures).
    +   */
    +  stores(store: string): string[] {
    +    return this.limits === null ? [store] : [UPDATES, CAPTURES];
    +  }
    +
    +  /** The store forgets what it knew of `key`'s size (rows were removed). */
    +  forget(key: string): void {
    +    this.sizes.delete(key);
    +  }
    +
    +  /**
    +   * Inside a write transaction, before it writes `adding` bytes for `key`
    +   * (and removes the rows `removing`, whose bytes then do not count): run
    +   * `then`, or abort with `'limit'` when the write would pass a limit.
    +   * Reads nothing without limits, nor for an append whose key's size is
    +   * known.
    +   */
    +  withinLimits(
    +    tx: IDBTransaction,
    +    guard: Guard,
    +    key: string,
    +    adding: number,
    +    removing: ReadonlySet<string> | null,
    +    then: () => void,
    +    replacingCapture: string | null = null,
    +  ): void {
    +    const limits = this.limits;
    +    if (limits === null) {
    +      then();
    +      return;
    +    }
    +    const known = this.sizes.get(key);
    +    if (removing === null && known !== undefined) {
    +      this.check(key, known + adding, false, limits);
    +      this.sizes.set(key, known + adding);
    +      then();
    +      return;
    +    }
    +    // Read the key's rows and captures (a first write, or one that removes).
    +    readRows(tx, this.prefix([key]), guard, rows => {
    +      const captures = tx.objectStore(CAPTURES).getAll(this.prefix([key]));
    +      captures.onsuccess = guard(() => {
    +        let bytes = 0;
    +        for (const [rowKey, value] of rows) {
    +          if (
    +            (removing === null || !removing.has(JSON.stringify(rowKey))) &&
    +            isRow(value)
    +          ) {
    +            bytes += value.u.byteLength;
    +          }
    +        }
    +        for (const capture of captures.result as unknown[]) {
    +          // A capture put again under its id replaces itself.
    +          if (
    +            replacingCapture === null ||
    +            (capture as {id?: unknown}).id !== replacingCapture
    +          ) {
    +            bytes += captureBytes(capture);
    +          }
    +        }
    +        const isNew = rows.length === 0 && captures.result.length === 0;
    +        const finish = () => {
    +          this.check(key, bytes + adding, false, limits);
    +          this.sizes.set(key, bytes + adding);
    +          then();
    +        };
    +        if (!isNew || limits.keys === undefined) {
    +          finish();
    +          return;
    +        }
    +        // A new key: count its group's keys.
    +        const group = limits.group ?? (() => '');
    +        const mine = group(key);
    +        const updates = tx.objectStore(UPDATES).getAllKeys();
    +        updates.onsuccess = guard(() => {
    +          const all = tx.objectStore(CAPTURES).getAllKeys();
    +          all.onsuccess = guard(() => {
    +            const keys = new Set<string>();
    +            for (const k of updates.result as RowKey[]) {
    +              keys.add(k[0]);
    +            }
    +            for (const k of all.result as [string, string][]) {
    +              keys.add(k[0]);
    +            }
    +            let inGroup = 0;
    +            for (const k of keys) {
    +              if (group(k) === mine) {
    +                inGroup++;
    +              }
    +            }
    +            this.check(key, inGroup + 1, true, limits);
    +            finish();
    +          });
    +        });
    +      });
    +    });
    +  }
    +
    +  /** Throws (aborting the transaction) when `amount` passes a limit. */
    +  private check(
    +    key: string,
    +    amount: number,
    +    isKeys: boolean,
    +    limits: YOfflineLimits,
    +  ): void {
    +    const max = isKeys ? limits.keys : limits.bytesPerKey;
    +    if (max !== undefined && amount > max) {
    +      this.forget(key);
    +      throw new LimitReached({
    +        code: 'limit',
    +        limit: isKeys ? 'keys' : 'bytes',
    +        message: isKeys
    +          ? `@lexical/y/offline: storing '${key}' would make ${amount} keys in its group, past limits.keys (${max}); it was refused and nothing was evicted. The edits are still in the page: tell the user they are not saved on this device, or clear documents no longer needed (store.clear(key, {captures: true})).`
    +          : `@lexical/y/offline: storing '${key}' would hold ${amount} bytes, past limits.bytesPerKey (${max}); it was refused and nothing was evicted. The edits are still in the page: tell the user they are not saved on this device.`,
    +      });
    +    }
    +  }
    +
    +  async slots(key: string): Promise<YOfflineResult<YOfflineSlotInfo[]>> {
    +    requireKey(key);
    +    const read = await this.rows([key], 'listing the slots');
    +    if (!read.ok) {
    +      return read;
    +    }
    +    const byEpoch = new Map<string | 0, YOfflineSlotInfo>();
    +    for (const [rowKey, value] of read.value) {
    +      const before = byEpoch.get(rowKey[1]);
    +      const t = isRow(value) ? value.t : 0;
    +      byEpoch.set(rowKey[1], {
    +        epoch: epochOf(rowKey[1]),
    +        hasUnsyncedEdits:
    +          (before !== undefined && before.hasUnsyncedEdits) ||
    +          rowKey[2] === 's',
    +        key,
    +        rows: (before === undefined ? 0 : before.rows) + 1,
    +        updatedAt: Math.max(before === undefined ? 0 : before.updatedAt, t),
    +      });
    +    }
    +    return ok([...byEpoch.values()].sort((a, b) => b.updatedAt - a.updatedAt));
    +  }
    +
    +  /** The rows under a key prefix, with their keys, in key order. */
    +  rows(
    +    prefix: readonly (string | number)[],
    +    doing: string,
    +  ): Promise<YOfflineResult<[RowKey, unknown][]>> {
    +    return this.run<[RowKey, unknown][]>(
    +      [UPDATES],
    +      'readonly',
    +      doing,
    +      (tx, out, guard) =>
    +        readRows(tx, this.prefix(prefix), guard, rows => (out.value = rows)),
    +      [],
    +    );
    +  }
    +
    +  async captures(key: string): Promise<YOfflineResult<YOfflineCapture[]>> {
    +    requireKey(key);
    +    const read = await this.run<unknown[]>(
    +      [CAPTURES],
    +      'readonly',
    +      'reading the captures',
    +      (tx, out) => {
    +        const request = tx.objectStore(CAPTURES).getAll(this.prefix([key]));
    +        request.onsuccess = () => (out.value = request.result);
    +      },
    +      [],
    +    );
    +    if (!read.ok) {
    +      return read;
    +    }
    +    const captures = read.value.filter(isCapture);
    +    if (captures.length !== read.value.length) {
    +      return fail({
    +        code: 'corrupt',
    +        message: `@lexical/y/offline: ${
    +          read.value.length - captures.length
    +        } stored capture(s) of '${key}' are not readable. Call store.clear(key, {captures: true}) to drop them.`,
    +      });
    +    }
    +    return ok(captures.sort((a, b) => a.capturedAt - b.capturedAt));
    +  }
    +
    +  putCapture(capture: YOfflineCapture): Promise<YOfflineResult<void>> {
    +    return this.run<void>(
    +      this.stores(CAPTURES),
    +      'readwrite',
    +      'storing a capture',
    +      (tx, _out, guard) => {
    +        // A capture replaces any of the same id: forget the key's size so
    +        // the check reads it.
    +        this.forget(capture.key);
    +        this.withinLimits(
    +          tx,
    +          guard,
    +          capture.key,
    +          captureBytes(capture),
    +          new Set(),
    +          () => {
    +            tx.objectStore(CAPTURES).put(
    +              {
    +                ...capture,
    +                base: capture.base === null ? null : exact(capture.base),
    +                state: exact(capture.state),
    +              },
    +              [capture.key, capture.id],
    +            );
    +          },
    +          capture.id,
    +        );

    Fixed: a moved epoch's capture goes in through slot.moveIntoCapture, one transaction that deletes the slot's own rows and puts the capture, checked with those rows counted as removed. Regression: case 11 (2.5 documents of room now suffices).

    zurfyx zurfyx commented on code on Nov 13, 2026 17:05 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineStore.ts:1
    @@ -0,0 +1,1408 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// Local persistence for Yjs 14 documents (`@lexical/y/offline`): a document's
    +// updates in IndexedDB, by an app-chosen key and the epoch (generation) the
    +// document was made against. No provider for Yjs 14 exists (`y-indexeddb`
    +// imports Yjs 13), and none keys by epoch or reports quota and corruption, so
    +// this one is written here on IndexedDB alone, with `@y/y` used only to merge
    +// updates.
    +//
    +// A slot (key, epoch) holds rows of two kinds:
    +//
    +// - `base`: a state the server is known to hold (written by `confirm`);
    +// - `since`: every update the document made or received after it.
    +//
    +// The document is their merge; what the server may lack is in `since`. Rows
    +// are keyed `[key, epoch, kind, writer, n]` with a random `writer` per slot
    +// handle, so two tabs on one key never overwrite each other. A handle only
    +// replaces rows it owns (the ones it loaded or wrote, all of which its
    +// document holds): another tab's rows stay until that tab, or a later load,
    +// replaces them.
    +
    +import {mergeUpdates} from '@y/y';
    +
    +/**
    + * @experimental The defaults of the optional fields of `@lexical/y/offline`,
    + * by name, so code can say which it relies on.
    + */
    +export const Y_OFFLINE_DEFAULTS: {
    +  readonly databaseName: string;
    +  readonly compactAfter: number;
    +  readonly openTimeout: number;
    +} = /* @__PURE__ */ Object.freeze({
    +  /** `since` rows a slot handle writes before it compacts them into one. */
    +  compactAfter: 64,
    +  databaseName: 'lexical-y-offline',
    +  /** Milliseconds openYOfflineStore waits for the database to open. */
    +  openTimeout: 10000,
    +});
    +
    +/** @experimental What failed (see {@link YOfflineError}). */
    +export type YOfflineErrorCode =
    +  /** There is no IndexedDB here (a private window, Node without a fake). */
    +  | 'unavailable'
    +  /** Another tab holds an older version of the database open. */
    +  | 'blocked'
    +  /** The browser refused the write: the origin's storage quota is full. */
    +  | 'quota'
    +  /** A stored row is not what this module wrote, or does not decode. */
    +  | 'corrupt'
    +  /** The store was closed (`store.close()`, or the database was deleted). */
    +  | 'closed'
    +  /**
    +   * The write would pass one of the store's `limits` (see `limit`): it was
    +   * refused, and nothing was evicted.
    +   */
    +  | 'limit'
    +  /** Any other IndexedDB failure; `cause` holds it. */
    +  | 'failed';
    +
    +/**
    + * @experimental A failure of the local store. Nothing here throws for a
    + * storage failure: every call returns a {@link YOfflineResult}, and
    + * `message` says what to do.
    + */
    +export interface YOfflineError {
    +  readonly code: YOfflineErrorCode;
    +  /** What happened and what the app can do about it. */
    +  readonly message: string;
    +  /** The underlying error, when there is one. */
    +  readonly cause?: unknown;
    +  /**
    +   * With `'corrupt'`: what the readable rows hold (their merge, the base
    +   * apart), so the app can offer it before clearing the slot.
    +   */
    +  readonly salvage?: YOfflineSalvage;
    +  /** With `'limit'`: which limit (see {@link YOfflineLimits}). */
    +  readonly limit?: 'keys' | 'bytes';
    +}
    +
    +/**
    + * @experimental Caps a store keeps by refusing writes (`'limit'`), never by
    + * evicting: what is stored stays until the app clears it.
    + */
    +export interface YOfflineLimits {
    +  /** Most keys stored per group (a new key past it is refused). */
    +  readonly keys?: number;
    +  /**
    +   * Most bytes stored per key: its rows' updates and its captures' states
    +   * and bases (a capture's JSON and text are not counted). Each connection
    +   * counts what it last read of the key plus what it wrote since; another
    +   * tab's writes count from its next read (a compaction, a confirmation, a
    +   * capture), so tabs writing at once can pass it by what they wrote since.
    +   */
    +  readonly bytesPerKey?: number;
    +  /**
    +   * The group a key counts in for `keys`, e.g. its viewer for keys
    +   * `viewer|doc`: `key => key.split('|')[0]`. Default: one group.
    +   */
    +  readonly group?: (key: string) => string;
    +}
    +
    +/** @experimental What a corrupt slot still holds (see {@link YOfflineError}). */
    +export interface YOfflineSalvage {
    +  /** The merge of every readable row, or null when none is. */
    +  readonly state: Uint8Array | null;
    +  readonly readableRows: number;
    +  readonly unreadableRows: number;
    +}
    +
    +/** @experimental A value, or the error that kept it from being made. */
    +export type YOfflineResult<T> =
    +  | {readonly ok: true; readonly value: T}
    +  | {readonly ok: false; readonly error: YOfflineError};
    +
    +/** @experimental What a slot holds (see {@link YOfflineSlot.load}). */
    +export interface YOfflineStored {
    +  /** The whole document: `base` and `since` merged (a Yjs update). */
    +  readonly state: Uint8Array;
    +  /** The state the server is known to hold, or null when none was confirmed. */
    +  readonly base: Uint8Array | null;
    +  /** Whether updates were stored after `base`: the server may lack them. */
    +  readonly hasUnsyncedEdits: boolean;
    +}
    +
    +/** @experimental One slot of a key (see {@link YOfflineStore.slots}). */
    +export interface YOfflineSlotInfo {
    +  readonly key: string;
    +  /** The epoch the slot's document was made against; null: never synced. */
    +  readonly epoch: string | null;
    +  /** When its newest row was written (Unix ms). */
    +  readonly updatedAt: number;
    +  readonly hasUnsyncedEdits: boolean;
    +  readonly rows: number;
    +}
    +
    +/**
    + * @experimental A frozen copy of a client's document that did not sync,
    + * with the base it was made against: what the Offline edits panel shows.
    + */
    +export interface YOfflineCapture {
    +  /** Unique per key. */
    +  readonly id: string;
    +  readonly key: string;
    +  /** The epoch the edits were made against; null: never synced. */
    +  readonly epoch: string | null;
    +  readonly reason: 'stale' | 'legacy' | 'expired';
    +  /** When it was captured (Unix ms). */
    +  readonly capturedAt: number;
    +  /** The whole document as the client held it (a Yjs update). */
    +  readonly state: Uint8Array;
    +  /**
    +   * The editor's content as Lexical JSON (`freeze()`'s), or null for a
    +   * capture made from storage alone (a tab that closed before it could
    +   * freeze).
    +   */
    +  readonly json: unknown | null;
    +  /** The plain text of the editor, for Copy; null as `json` is. */
    +  readonly text: string | null;
    +  /**
    +   * Whether the editor held edits the document did not (`freeze()`'s
    +   * `differs`): the report then reads `json`, else `state`.
    +   */
    +  readonly differs: boolean;
    +  /** The document the edits were made against, or null when unknown. */
    +  readonly base: Uint8Array | null;
    +  /** Set once a replay stage took the capture (see claimCapture). */
    +  readonly claimed: boolean;
    +}
    +
    +/** @experimental One (key, epoch) of a {@link YOfflineStore}. */
    +export interface YOfflineSlot {
    +  readonly key: string;
    +  /** Changes with {@link YOfflineSlot.adopt}. */
    +  readonly epoch: string | null;
    +  /**
    +   * Read the slot: null when it holds nothing. The rows read become this
    +   * handle's (create the document from `state`, so it holds them). With
    +   * `{writers: 'gone'}`, only rows whose writer is gone (no live tab holds
    +   * them): what recovery captures, leaving a live tab's rows to that tab.
    +   * Without Web Locks (`locks: null`) that is every row.
    +   */
    +  load(options?: {
    +    readonly writers?: 'all' | 'gone';
    +  }): Promise<YOfflineResult<YOfflineStored | null>>;
    +  /** Store one update the document made or received. */
    +  append(update: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * The server holds `state` (the whole document, which holds every row of
    +   * this handle): it becomes the base and this handle's rows are removed.
    +   */
    +  confirm(state: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * Replace this handle's `since` rows by one: `since` when given (what the
    +   * document holds beyond the base), else their merge.
    +   */
    +  compact(since?: Uint8Array): Promise<YOfflineResult<void>>;
    +  /**
    +   * Delete this handle's rows (the ones it loaded or wrote), and no other:
    +   * for a document that was captured, whose rows another tab at the same
    +   * epoch may still be adding to.
    +   */
    +  discard(): Promise<YOfflineResult<void>>;
    +  /** `since` rows this handle wrote since it last compacted or confirmed. */
    +  readonly rowsSinceCompaction: number;
    +  /**
    +   * Release the handle's writer lock (see `locks`): its rows become another
    +   * handle's to replace. Call it when the document is closed; a closed tab
    +   * releases it on its own.
    +   */
    +  close(): void;
    +  /**
    +   * Move a slot that never synced (`epoch` null) to the epoch the server
    +   * gave it: this handle's rows, and those it loaded whose writer is gone.
    +   * A live tab's rows stay for that tab to move.
    +   */
    +  adopt(epoch: string): Promise<YOfflineResult<void>>;
    +}
    +
    +/** @experimental The local store (see {@link openYOfflineStore}). */
    +export interface YOfflineStore {
    +  /** A handle on one slot; nothing is read or written until it is used. */
    +  slot(key: string, epoch: string | null): YOfflineSlot;
    +  /** The slots stored for `key`, newest first. */
    +  slots(key: string): Promise<YOfflineResult<YOfflineSlotInfo[]>>;
    +  /** The captures stored for `key`, oldest first. */
    +  captures(key: string): Promise<YOfflineResult<YOfflineCapture[]>>;
    +  putCapture(capture: YOfflineCapture): Promise<YOfflineResult<void>>;
    +  /**
    +   * Mark a capture as taken by a replay: true for the one caller that gets
    +   * it (a second tab, or a second call, gets false), so a capture is
    +   * replayed automatically at most once.
    +   */
    +  claimCapture(key: string, id: string): Promise<YOfflineResult<boolean>>;
    +  deleteCapture(key: string, id: string): Promise<YOfflineResult<void>>;
    +  /**
    +   * Delete what is stored for `key`: one slot when `what.epoch` is given
    +   * (null names the never-synced slot), else every slot; its captures too
    +   * with `what.captures`.
    +   */
    +  clear(
    +    key: string,
    +    what: {readonly epoch?: string | null; readonly captures: boolean},
    +  ): Promise<YOfflineResult<void>>;
    +  /** Every key that holds a slot or a capture (for clearing by owner). */
    +  keys(): Promise<YOfflineResult<string[]>>;
    +  /** Close the database: later calls return `'closed'`. */
    +  close(): void;
    +}
    +
    +/** @experimental Options of {@link openYOfflineStore}. */
    +export interface YOfflineStoreOptions {
    +  /**
    +   * The IndexedDB to use. Required, so every caller decides: pass
    +   * `{indexedDB, IDBKeyRange}` from `globalThis` in a browser, or a fake's
    +   * in Node (the store works without a DOM).
    +   */
    +  readonly idb: {
    +    readonly indexedDB: IDBFactory | undefined;
    +    readonly IDBKeyRange: typeof IDBKeyRange | undefined;
    +  };
    +  /**
    +   * The database's name: one per app.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.databaseName`
    +   */
    +  readonly databaseName?: string;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +  /**
    +   * Milliseconds to wait for the database to open before answering
    +   * `'unavailable'` (some browsers never answer an open in some states).
    +   * A connection that opens later is closed.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.openTimeout`
    +   */
    +  readonly openTimeout?: number;
    +  /** Caps kept by refusing writes, never by evicting. Default: none. */
    +  readonly limits?: YOfflineLimits;
    +  /**
    +   * The Web Locks the store tells live tabs by: each writing handle holds a
    +   * lock, and no handle removes rows a live handle wrote (they may be what
    +   * that tab's later rows build on). Rows of a handle that is gone (a
    +   * closed tab, an earlier page load) are replaced by the next handle that
    +   * loads them. Null: every other handle counts as live, so rows of earlier
    +   * page loads are kept until the app clears them.
    +   * @defaultValue `navigator.locks`, where there is one, else null
    +   */
    +  readonly locks?: YOfflineLocks | null;
    +}
    +
    +/** @experimental The part of the Web Locks API the store uses. */
    +export interface YOfflineLocks {
    +  request(
    +    name: string,
    +    callback: (lock: unknown) => Promise<unknown>,
    +  ): Promise<unknown>;
    +  query(): Promise<{readonly held?: readonly {readonly name?: string}[]}>;
    +}
    +
    +/** Wraps a request callback so that what it throws fails the transaction. */
    +type Guard = (fn: () => void) => () => void;
    +
    +const UPDATES = 'updates';
    +const CAPTURES = 'captures';
    +const DB_VERSION = 1;
    +const ROW_VERSION = 1;
    +
    +type RowKind = 'b' | 's';
    +/** `[key, epoch (0 for null), kind, writer, n]`. */
    +type RowKey = [string, string | 0, RowKind, string, number];
    +
    +interface Row {
    +  readonly v: number;
    +  /** The update. */
    +  readonly u: Uint8Array;
    +  /** FNV-1a of `u`: a row cut short or changed does not read as an update. */
    +  readonly h: number;
    +  /** When it was written (Unix ms). */
    +  readonly t: number;
    +}
    +
    +const ok = <T>(value: T): YOfflineResult<T> => ({ok: true, value});
    +const fail = <T>(error: YOfflineError): YOfflineResult<T> => ({
    +  error,
    +  ok: false,
    +});
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +function checksum(bytes: Uint8Array): number {
    +  let h = 0x811c9dc5;
    +  for (let i = 0; i < bytes.length; i++) {
    +    h ^= bytes[i];
    +    h = Math.imul(h, 0x01000193);
    +  }
    +  return h >>> 0;
    +}
    +
    +/**
    + * A Uint8Array of any realm: a value read back from IndexedDB in an iframe,
    + * or under a test runner's VM, is not `instanceof` this realm's.
    + */
    +function isBytes(value: unknown): value is Uint8Array {
    +  return (
    +    ArrayBuffer.isView(value) &&
    +    Object.prototype.toString.call(value) === '[object Uint8Array]'
    +  );
    +}
    +
    +/**
    + * `bytes` with a buffer of its own size: IndexedDB stores a view's whole
    + * buffer, and an update can be a short view of an encoder's long one.
    + */
    +function exact(bytes: Uint8Array): Uint8Array {
    +  return bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
    +}
    +
    +function isRow(value: unknown): value is Row {
    +  if (typeof value !== 'object' || value === null) {
    +    return false;
    +  }
    +  const row = value as Partial<Row>;
    +  return (
    +    row.v === ROW_VERSION &&

    Done: a row with v > ROW_VERSION reads as a new code, 'newer' (kept, with the slot's epoch, advice to reload and not to clear), never 'corrupt'.

    zurfyx zurfyx commented on code on Nov 13, 2026 17:05 UTC
    Code Review
    packages/lexical-playground/src/collaborationYOffline.tsx:1
    @@ -0,0 +1,523 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// Collab Y offline mode (`@lexical/y/offline`), on with the "Collab Y
    +// Offline" setting (`?collabYOffline=true`):
    +//
    +// - the document is stored in IndexedDB as it is edited, so the page opens
    +//   with no connection and keeps what was typed (the toolbar's connect
    +//   button takes the page offline);
    +// - on reconnect at the same epoch it syncs as usual;
    +// - when the epoch moved, the page's copy is frozen and captured, the page
    +//   opens the room's new document, and the Offline edits panel shows what
    +//   did not sync, block by block, with Copy and Reapply (at stage `replay`,
    +//   the default, the replayable blocks are reapplied at once).
    +//
    +// The playground's relay has no epochs, so `?collabYEpoch=<n>` stands in for
    +// what a server would say: each epoch is its own room, and the panel's
    +// "Simulate replaced" button plays the server (it copies the document the
    +// server holds into the next epoch's room, then tells this page the room was
    +// replaced). `?collabYOfflineStage=persist` turns the automatic replay off.
    +
    +import {type Signal, signal} from '@lexical/extension';
    +import {useSignalValue} from '@lexical/react/useExtensionSignalValue';
    +import {createYDoc, type YCollabBinding} from '@lexical/y';
    +import {type HeadlessYConfig} from '@lexical/y/headless';
    +import {
    +  attachYOfflineSession,
    +  loadYOffline,
    +  openYOfflineStore,
    +  recoverYOfflineEdits,
    +  replayUnsyncedEdits,
    +  Y_OFFLINE_STAGES,
    +  type YOfflineCapture,
    +  type YOfflineLoaded,
    +  type YOfflineRecovered,
    +  type YOfflineSession,
    +  type YOfflineStage,
    +  type YOfflineStore,
    +} from '@lexical/y/offline';
    +import {WebsocketProvider} from '@y/websocket';
    +import {encodeStateAsUpdate} from '@y/y';
    +import {type JSX, useCallback} from 'react';
    +
    +const params = new URLSearchParams(window.location.search);
    +
    +/** The epoch the playground's "server" is at (see the note above). */
    +export const COLLAB_Y_EPOCH = params.get('collabYEpoch') || '1';
    +
    +const requestedStage = params.get('collabYOfflineStage');
    +/** The rollout stage: `replay` unless the URL says otherwise. */
    +export const COLLAB_Y_OFFLINE_STAGE: YOfflineStage = Y_OFFLINE_STAGES.includes(
    +  requestedStage as YOfflineStage,
    +)
    +  ? (requestedStage as YOfflineStage)
    +  : 'replay';
    +
    +/** The room of a document at an epoch: epoch 1 is the room without it. */
    +export function roomAtEpoch(room: string, epoch: string): string {
    +  return epoch === '1' ? room : `${room}@${epoch}`;
    +}
    +
    +/** What was read from the local store before the document is made. */
    +export interface CollabYOfflinePrepared {
    +  /** Null when there is no local store here (it says why in `problem`). */
    +  store: YOfflineStore | null;
    +  loaded: YOfflineLoaded | null;
    +  problem: string | null;
    +}
    +
    +const prepared = new Map<string, Promise<CollabYOfflinePrepared | null>>();
    +
    +/**
    + * Open the local store and read the document stored for `key`; null with
    + * offline mode off. One promise per key, so React's `use` can wait on it.
    + */
    +export function prepareCollabYOffline(
    +  key: string,
    +  enabled: boolean,
    +): Promise<CollabYOfflinePrepared | null> {
    +  const id = `${enabled}:${key}`;
    +  let promise = prepared.get(id);
    +  if (promise === undefined) {
    +    promise = enabled ? prepare(key) : Promise.resolve(null);
    +    prepared.set(id, promise);
    +  }
    +  return promise;
    +}
    +
    +async function prepare(key: string): Promise<CollabYOfflinePrepared> {
    +  const opened = await openYOfflineStore({
    +    idb: {
    +      IDBKeyRange: globalThis.IDBKeyRange,
    +      indexedDB: globalThis.indexedDB,
    +    },
    +  });
    +  if (!opened.ok) {
    +    return {loaded: null, problem: opened.error.message, store: null};
    +  }
    +  const loaded = await loadYOffline({key, store: opened.value});
    +  if (!loaded.ok) {
    +    return {loaded: null, problem: loaded.error.message, store: opened.value};
    +  }
    +  return {loaded: loaded.value, problem: null, store: opened.value};
    +}
    +
    +export interface CollabYOfflineStatus {
    +  hasUnsyncedEdits: boolean;
    +  persisted: boolean;
    +  problem: string | null;
    +}
    +
    +/** The page's offline mode: the session, and what the panel shows. */
    +export interface CollabYOffline {
    +  readonly epoch: string;
    +  readonly stage: YOfflineStage;
    +  readonly status: Signal<CollabYOfflineStatus>;
    +  /** What did not sync, per capture (null until the first sync). */
    +  readonly recovered: Signal<YOfflineRecovered[] | null>;
    +  /** The provider finished a sync: confirm it, then gather what did not sync. */
    +  onSynced(): void;
    +  reapply(captureId: string, blockId: string): Promise<void>;
    +  dismiss(captureId: string): Promise<void>;
    +  /** Play the server: move the room to the next epoch (see the note above). */
    +  simulateReplaced(): Promise<void>;
    +  /** True once the epoch moved: this document is never synced again. */
    +  frozen(): boolean;
    +  dispose(): void;
    +}
    +
    +/**
    + * The stored document to start from, when it belongs to the epoch the
    + * room is at; otherwise the page starts from the server (and a document
    + * stored at another epoch becomes a capture after the first sync).
    + */
    +export function storedStateFor(
    +  from: CollabYOfflinePrepared | null,
    +): Uint8Array | null {
    +  return from !== null &&
    +    from.loaded !== null &&
    +    from.loaded.epoch === COLLAB_Y_EPOCH
    +    ? from.loaded.state
    +    : null;
    +}
    +
    +export function createCollabYOffline(input: {
    +  binding: YCollabBinding;
    +  from: CollabYOfflinePrepared;
    +  key: string;
    +  /** The headless configuration of the same editor, for the reports. */
    +  config: HeadlessYConfig;
    +  /** The relay, and this document's room without its epoch. */
    +  endpoint: string;
    +  room: string;
    +  /** Stop syncing the page's document for good (its provider). */
    +  stopSync: () => void;
    +}): CollabYOffline {
    +  const {binding, config, from, key} = input;
    +  const {store} = from;
    +  const stage = store === null ? 'off' : COLLAB_Y_OFFLINE_STAGE;
    +  const status = signal<CollabYOfflineStatus>({
    +    hasUnsyncedEdits: false,
    +    persisted: store !== null,
    +    problem: from.problem,
    +  });
    +  const recovered = signal<YOfflineRecovered[] | null>(null);
    +  const useStored = storedStateFor(from) !== null;
    +  const session: YOfflineSession = attachYOfflineSession({
    +    binding,
    +    epoch: COLLAB_Y_EPOCH,
    +    key,
    +    loaded: useStored && from.loaded !== null ? from.loaded : undefined,
    +    onError: error => {
    +      status.value = {
    +        ...status.peek(),
    +        persisted: false,
    +        problem: error.message,
    +      };
    +    },
    +    stage,
    +    store,
    +  });
    +  const doc = binding.binding.doc;
    +  const refreshStatus = () => {
    +    const before = status.peek();
    +    const next = {
    +      hasUnsyncedEdits: session.hasUnsyncedEdits,
    +      persisted: session.persisted,
    +      problem: session.persisted ? from.problem : before.problem,
    +    };
    +    if (
    +      next.hasUnsyncedEdits !== before.hasUnsyncedEdits ||
    +      next.persisted !== before.persisted ||
    +      next.problem !== before.problem
    +    ) {
    +      status.value = next;
    +    }
    +  };
    +  const onTransaction = () => {
    +    refreshStatus();
    +    void session.flush().then(refreshStatus);
    +  };
    +  doc.on('afterTransaction', onTransaction);
    +  refreshStatus();
    +
    +  const recover = async () => {
    +    if (binding.status.kind !== 'active') {
    +      return;
    +    }
    +    try {
    +      const result = await recoverYOfflineEdits({
    +        binding,
    +        config,
    +        epoch: COLLAB_Y_EPOCH,
    +        key,
    +        session,
    +        stage,
    +        store,
    +      });
    +      if (result.ok) {
    +        recovered.value = result.value;
    +      } else {
    +        status.value = {...status.peek(), problem: result.error.message};
    +      }
    +    } catch (error) {
    +      // The reports could not be made (the headless editor): the captures
    +      // are still stored, and the panel offers their text.
    +      const captures = store === null ? null : await store.captures(key);
    +      recovered.value =
    +        captures !== null && captures.ok
    +          ? captures.value.map(capture => ({
    +              capture,
    +              replay: null,
    +              report: {
    +                error: {code: 'failed', message: String(error)},
    +                ok: false,
    +              },
    +            }))
    +          : [];
    +    }
    +  };
    +  let recovering: Promise<void> | null = null;
    +
    +  return {
    +    dismiss: async captureId => {
    +      if (store !== null) {
    +        await store.deleteCapture(key, captureId);
    +      }
    +      await recover();
    +    },
    +    dispose: () => {
    +      doc.off('afterTransaction', onTransaction);
    +      session.dispose();
    +    },
    +    epoch: COLLAB_Y_EPOCH,
    +    frozen: () => session.ended,
    +    onSynced: () => {
    +      if (session.ended) {
    +        return;
    +      }
    +      // The epoch is the room's (the provider is connected to it).
    +      void session.serverEpoch(COLLAB_Y_EPOCH).then(verdict => {
    +        if (verdict.kind === 'same' && !session.ended) {
    +          session.markSynced();
    +          refreshStatus();
    +          recovering ??= recover();
    +        }
    +      });
    +    },
    +    reapply: async (captureId, blockId) => {
    +      const entry = (recovered.peek() ?? []).find(
    +        r => r.capture.id === captureId,
    +      );
    +      if (entry !== undefined && entry.report.ok) {
    +        replayUnsyncedEdits({
    +          binding,
    +          only: [blockId],
    +          report: entry.report.value,
    +        });
    +      }
    +      await recover();
    +    },
    +    recovered,
    +    simulateReplaced: async () => {
    +      const next = String((Number(COLLAB_Y_EPOCH) || 1) + 1);
    +      // Stop syncing this document for good, then freeze and capture it:
    +      // nothing of it may reach the old room again (a reconnect included;
    +      // the toolbar's Connect does nothing once it is frozen).
    +      input.stopSync();
    +      const verdict = await session.serverEpoch(next);
    +      if (verdict.kind !== 'moved') {
    +        return;
    +      }
    +      // The server reloads the room from what it holds (the relay's room at
    +      // this epoch), as a real replace or upgrade would.
    +      const oldRoom = roomAtEpoch(input.room, COLLAB_Y_EPOCH);
    +      const serverState = await readRoom(input.endpoint, oldRoom);
    +      const seeded =
    +        serverState === null
    +          ? false
    +          : await seedRoom(
    +              input.endpoint,
    +              roomAtEpoch(input.room, next),
    +              serverState,
    +            );
    +      if (!seeded) {
    +        status.value = {
    +          ...status.peek(),
    +          problem:
    +            'The relay did not answer, so the room was not replaced. This page is frozen and its edits are stored on this device: reload when the relay is back.',
    +        };
    +        return;
    +      }
    +      const url = new URL(window.location.href);
    +      url.searchParams.set('collabYEpoch', next);
    +      window.location.href = url.toString();
    +    },
    +    stage,
    +    status,
    +  };
    +}
    +
    +/** What a room holds on the relay, or null when the relay does not answer. */
    +function readRoom(endpoint: string, room: string): Promise<Uint8Array | null> {
    +  return new Promise(resolve => {
    +    const doc = createYDoc(null);
    +    const provider = new WebsocketProvider(endpoint, room, doc, {
    +      disableBc: true,
    +    });
    +    const finish = (state: Uint8Array | null) => {
    +      clearTimeout(timer);
    +      provider.destroy();
    +      resolve(state);
    +    };
    +    const timer = setTimeout(() => finish(null), 3000);
    +    provider.on('sync', (isSynced: boolean) => {
    +      if (isSynced) {
    +        finish(encodeStateAsUpdate(doc));
    +      }
    +    });
    +  });
    +}
    +
    +/**
    + * Put `state` into a room, as a server that reloaded a document would.
    + * False when the relay does not answer.
    + */
    +function seedRoom(
    +  endpoint: string,
    +  room: string,
    +  state: Uint8Array,
    +): Promise<boolean> {
    +  return new Promise(resolve => {
    +    const provider = new WebsocketProvider(endpoint, room, createYDoc(state), {
    +      disableBc: true,
    +    });
    +    let settled = false;
    +    const finish = (seeded: boolean) => {
    +      if (!settled) {
    +        settled = true;
    +        clearTimeout(timer);
    +        // Sync step 2 (this document's content) was sent with step 1.
    +        setTimeout(() => {
    +          provider.destroy();
    +          resolve(seeded);
    +        }, 200);
    +      }
    +    };
    +    const timer = setTimeout(() => finish(false), 3000);
    +    provider.on('sync', (isSynced: boolean) => {
    +      if (isSynced) {
    +        finish(true);
    +      }
    +    });
    +  });
    +}
    +
    +/** The plain text of a serialized block. */
    +function previewOf(node: unknown): string {
    +  if (typeof node !== 'object' || node === null) {
    +    return '';
    +  }
    +  const {children, text} = node as {children?: unknown; text?: unknown};
    +  if (typeof text === 'string') {
    +    return text;
    +  }
    +  return Array.isArray(children) ? children.map(previewOf).join('') : '';
    +}
    +
    +function copy(text: string): void {
    +  void navigator.clipboard.writeText(text);
    +}
    +
    +const CHANGE_LABEL = {
    +  added: 'Added',
    +  changed: 'Changed',
    +  deleted: 'Deleted',
    +} as const;
    +
    +function CaptureView({
    +  entry,
    +  offline,
    +}: {
    +  entry: YOfflineRecovered;
    +  offline: CollabYOffline;
    +}): JSX.Element {
    +  const capture: YOfflineCapture = entry.capture;
    +  const blocks = entry.report.ok ? entry.report.value.blocks : [];
    +  const applied = entry.replay === null ? 0 : entry.replay.applied.length;
    +  return (
    +    <section
    +      className="collab-y-offline-capture"
    +      data-test-id="collab-y-offline-capture">
    +      <div className="collab-y-offline-capture-title">
    +        <strong>Offline edits</strong> from epoch {capture.epoch ?? 'none'}
    +        {applied > 0 ? ` · ${applied} reapplied (undo to revert)` : ''}
    +        {capture.text !== null ? (
    +          <button
    +            type="button"
    +            onClick={() => copy(capture.text ?? '')}
    +            title="Copy the whole document as you had it">
    +            Copy all
    +          </button>
    +        ) : null}
    +        <button
    +          type="button"
    +          data-test-id="collab-y-offline-dismiss"
    +          onClick={() => void offline.dismiss(capture.id)}>
    +          Dismiss
    +        </button>
    +      </div>
    +      {!entry.report.ok ? (
    +        <div className="collab-y-offline-problem">
    +          These edits could not be compared with the document; their text is
    +          kept (Copy all).
    +        </div>
    +      ) : blocks.length === 0 ? (
    +        <div className="collab-y-offline-empty">
    +          {entry.report.value.orderDiffers
    +            ? 'Your copy has its blocks in another order; the rest is in the document.'
    +            : 'Everything is in the document.'}
    +        </div>
    +      ) : (
    +        blocks.map(block => {
    +          const preview = previewOf(block.yours ?? block.base);
    +          return (
    +            <div
    +              key={block.id}
    +              className="collab-y-offline-block"
    +              data-test-id="collab-y-offline-block"
    +              data-change={block.change}
    +              data-replayable={block.replayable}>
    +              <span className="collab-y-offline-change">
    +                {CHANGE_LABEL[block.change]}
    +              </span>
    +              <span className="collab-y-offline-preview">{preview}</span>
    +              <button type="button" onClick={() => copy(preview)}>
    +                Copy
    +              </button>
    +              <button
    +                type="button"
    +                data-test-id="collab-y-offline-reapply"
    +                disabled={!block.replayable}
    +                title={
    +                  block.replayable
    +                    ? 'Put this block back as you had it'
    +                    : 'Someone changed this block since: copy your text instead'
    +                }
    +                onClick={() => void offline.reapply(capture.id, block.id)}>
    +                Reapply
    +              </button>
    +            </div>
    +          );
    +        })
    +      )}
    +    </section>
    +  );
    +}
    +
    +/** The status line and the Offline edits panel. */
    +export function CollabYOfflinePanel({
    +  offline,
    +}: {
    +  offline: CollabYOffline;
    +}): JSX.Element {
    +  const status = useSignalValue(offline.status);
    +  const recovered = useSignalValue(offline.recovered);
    +  const simulate = useCallback(
    +    () => void offline.simulateReplaced(),
    +    [offline],
    +  );
    +  return (
    +    <div className="collab-y-offline" data-test-id="collab-y-offline">
    +      <div
    +        className="collab-y-offline-status"
    +        role="status"

    Fixed: role=status moved to the problem line.

    rootnode-bot[bot] rootnode-bot[bot] commented on code on Nov 13, 2026 17:34 UTC
    Code Review
    packages/lexical-y/src/internal/OfflineSession.ts:1
    @@ -0,0 +1,1595 @@
    +/**
    + * Copyright (c) Meta Platforms, Inc. and affiliates.
    + *
    + * This source code is licensed under the MIT license found in the
    + * LICENSE file in the root directory of this source tree.
    + *
    + */
    +
    +// The offline session (`@lexical/y/offline`): one object an app attaches to
    +// its binding, and three signals it gives it.
    +//
    +//   const loaded = await loadYOffline({store, key});         // offline mode
    +//   const doc = createYDoc(loaded.state);
    +//   const binding = createYBinding(editor, {doc, ...});
    +//   const session = attachYOfflineSession({binding, store, key,
    +//     epoch: loaded.epoch, loaded, stage, onError});
    +//
    +//   // 1. the server said which epoch the room is at: before syncing, on
    +//   //    every connect, and on a "replaced" event (a reload or a layout
    +//   //    upgrade of the room is the same signal: a new epoch):
    +//   const verdict = await session.serverEpoch(epoch);
    +//   //    'same': sync this document. 'moved': it is frozen and captured;
    +//   //    open a fresh document at the new epoch, then
    +//   //    recoverYOfflineEdits() there.
    +//   // 2. the server holds everything the document holds:
    +//   session.markSynced();
    +//
    +// It uses the binding's public API only (`freeze()`, `status`, the editor)
    +// and `describeUnsyncedEdits`: nothing here depends on a layout.
    +
    +import {
    +  encodeStateAsUpdate,
    +  encodeStateVector,
    +  mergeUpdates,
    +  type Transaction,
    +} from '@y/y';
    +import {
    +  $getEditor,
    +  $getRoot,
    +  $getSelection,
    +  $parseSerializedNode,
    +  type LexicalNode,
    +  type SerializedEditorState,
    +  type SerializedLexicalNode,
    +} from 'lexical';
    +
    +import {type YBinding, type YLocalEdits, type YStatus} from '..';
    +import {
    +  describeUnsyncedEdits,
    +  type HeadlessYConfig,
    +  readYState,
    +  YHeadlessError,
    +  type YUnsyncedBlock,
    +  type YUnsyncedReport,
    +} from '../headless';
    +import {
    +  offlineFail as fail,
    +  offlineOk as ok,
    +  Y_OFFLINE_DEFAULTS,
    +  type YOfflineCapture,
    +  type YOfflineError,
    +  type YOfflineResult,
    +  type YOfflineSlot,
    +  type YOfflineStore,
    +} from './OfflineStore';
    +
    +/**
    + * @experimental The rollout stage of the offline layer, an explicit choice
    + * of every call that takes it:
    + * - `'off'`: nothing is persisted, captured or replayed (the calls return
    + *   at once), so an app can ship the code dark;
    + * - `'persist'`: every edit is stored on the device as it is made
    + *   (`persistEdits`), and a document whose epoch moved (a reconnect to a
    + *   replaced or upgraded room) is frozen and stored with its base, for the
    + *   Offline edits panel;
    + * - `'replay'`: as `'persist'`, and {@link recoverYOfflineEdits} applies the
    + *   blocks that are replayable.
    + */
    +export type YOfflineStage = 'off' | 'persist' | 'replay';
    +
    +/** @experimental Every {@link YOfflineStage}, in rollout order. */
    +export const Y_OFFLINE_STAGES: readonly YOfflineStage[] =
    +  /* @__PURE__ */ Object.freeze(['off', 'persist', 'replay'] as const);
    +
    +/**
    + * @experimental What the offline layer uses of a binding: a
    + * `YCollabBinding` (`createYBinding`, or YCollabExtension's `collab`) is
    + * one. An app that built a `YBinding` itself passes the binding, its
    + * status, and a `freeze()` that stops it and hands over its edits (from
    + * `binding.quiesce()`).
    + */
    +export interface YOfflineBinding {
    +  /** The YBinding: its document, editor and undo manager are read. */
    +  readonly binding: YBinding;
    +  /** `'active'` when edits can be replayed into it. */
    +  readonly status: YStatus;
    +  /** Stop reading and writing, and hand over the local edits (11.6). */
    +  freeze(): YLocalEdits;
    +}
    +
    +/** @experimental What {@link loadYOffline} read. */
    +export interface YOfflineLoaded {
    +  /** The epoch the stored document was made against; null: none, or never synced. */
    +  readonly epoch: string | null;
    +  /** The stored document (for `createYDoc(state)`), or null when none is stored. */
    +  readonly state: Uint8Array | null;
    +  /** The state the server is known to hold, or null. */
    +  readonly base: Uint8Array | null;
    +  /** Whether the stored document holds edits the server may lack. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** @internal The handle that read it (it owns the rows read). */
    +  readonly slot: YOfflineSlot | null;
    +}
    +
    +/**
    + * @experimental Read the document stored for `key`. Pass the result to
    + * {@link attachYOfflineSession} as `loaded`, with `epoch: loaded.epoch`.
    + *
    + * - Without `epoch` (bind, then sync: the page starts from the store, with
    + *   no connection): the newest slot. Create the document from `state`, and
    + *   call `session.serverEpoch(epoch)` when the server names its epoch.
    + * - With `epoch`, the server's (sync, then bind: the page has the server's
    + *   document and epoch before it binds): only the slot at that epoch.
    + *   Apply its `state` to the server's document (the same lineage, so it
    + *   merges: the edits that did not sync go out on the next sync), and bind.
    + *   A slot at another epoch is never loaded: {@link recoverYOfflineEdits}
    + *   turns it into a capture. There is nothing to ask `serverEpoch` until
    + *   the server replaces the room.
    + *
    + * A key has more than one slot only when a tab was left at an earlier
    + * epoch.
    + */
    +export async function loadYOffline(input: {
    +  readonly store: YOfflineStore;
    +  readonly key: string;
    +  /** The epoch the server's room is at, when the page knows it before binding. */
    +  readonly epoch?: string;
    +}): Promise<YOfflineResult<YOfflineLoaded>> {
    +  const wanted = input.epoch;
    +  requireOption(
    +    wanted === undefined || (typeof wanted === 'string' && wanted !== ''),
    +    `loadYOffline's epoch is the epoch your server's room is at, as a non-empty string (String(epoch) for a number), or left out to load the newest slot; got ${
    +      wanted === '' ? "''" : typeof wanted
    +    }.`,
    +  );
    +  const slots = await input.store.slots(input.key);
    +  if (!slots.ok) {
    +    return slots;
    +  }
    +  const found =
    +    wanted === undefined
    +      ? slots.value[0]
    +      : slots.value.find(info => info.epoch === wanted);
    +  if (found === undefined) {
    +    return ok({
    +      base: null,
    +      epoch: wanted === undefined ? null : wanted,
    +      hasUnsyncedEdits: false,
    +      slot: null,
    +      state: null,
    +    });
    +  }
    +  const {epoch} = found;
    +  const slot = input.store.slot(input.key, epoch);
    +  const stored = await slot.load();
    +  if (!stored.ok) {
    +    return stored;
    +  }
    +  return ok({
    +    base: stored.value === null ? null : stored.value.base,
    +    epoch,
    +    hasUnsyncedEdits: stored.value !== null && stored.value.hasUnsyncedEdits,
    +    slot,
    +    state: stored.value === null ? null : stored.value.state,
    +  });
    +}
    +
    +/**
    + * @experimental Options of {@link attachYOfflineSession}: `binding`, `store`,
    + * `key`, `epoch`, `stage` and `onError` are required.
    + */
    +export interface YOfflineSessionOptions {
    +  /**
    +   * The bound editor: what `createYBinding` returns, YCollabExtension's
    +   * `collab`, or any {@link YOfflineBinding}.
    +   */
    +  readonly binding: YOfflineBinding;
    +  /** From `openYOfflineStore`; null only with stage `'off'`. */
    +  readonly store: YOfflineStore | null;
    +  /** The document's name in your app (its id). */
    +  readonly key: string;
    +  /**
    +   * The epoch (generation) the document was made against, as a string:
    +   * `loaded.epoch` for a document created from {@link loadYOffline}, the
    +   * server's for one fetched from it, null for one that never synced.
    +   */
    +  readonly epoch: string | null;
    +  /** The rollout stage (see {@link YOfflineStage}). */
    +  readonly stage: YOfflineStage;
    +  /**
    +   * `true` (the default): every update is stored as it is made, so the
    +   * document survives a reload, a crash or a closed tab with no connection,
    +   * and a later page captures what did not sync. `false`: only captures
    +   * are stored (a moved epoch while the tab is open); unsynced edits live
    +   * in the tab until it syncs, and adds no `update` listener. Whether the
    +   * editor is editable before the server answers (offline editing) is the
    +   * app's choice, made when it binds (`synced`), not this one.
    +   * @defaultValue `true`
    +   */
    +  readonly persistEdits?: boolean;
    +  /**
    +   * What `persistEdits` keeps on the device:
    +   * - `'document'` (the default): the whole document, always (its base and
    +   *   what came since), so the page can open it with no connection
    +   *   (`loadYOffline`);
    +   * - `'unsynced'`: only while the document holds edits the server lacks.
    +   *   Nothing is stored while it is synced; the first local edit stores the
    +   *   base and what came since, and `markSynced()` deletes them.
    +   * @defaultValue `'document'`
    +   */
    +  readonly keep?: 'document' | 'unsynced';
    +  /**
    +   * Milliseconds to wait for updates to pause before storing them (0:
    +   * store each at once). While they do not pause, they are stored at least
    +   * every ten times this. `flush()` stores at once; call it on `pagehide`.
    +   * @defaultValue `0`
    +   */
    +  readonly writeDelay?: number;
    +  /**
    +   * Called with every storage failure (a full quota, a closed store): tell
    +   * the user their edits are not saved on this device. Editing goes on, and
    +   * the next write retries.
    +   */
    +  readonly onError: (error: YOfflineError) => void;
    +  /**
    +   * What {@link loadYOffline} returned, when the document was created from
    +   * it: its base and its stored rows continue here.
    +   */
    +  readonly loaded?: YOfflineLoaded;
    +  /**
    +   * Stored updates before they are compacted into one.
    +   * @defaultValue `Y_OFFLINE_DEFAULTS.compactAfter`
    +   */
    +  readonly compactAfter?: number;
    +  /** The clock, for tests. @defaultValue `Date.now` */
    +  readonly now?: () => number;
    +}
    +
    +/** @experimental What {@link YOfflineSession.serverEpoch} decided. */
    +export type YOfflineVerdict =
    +  /** Stage `'off'`: nothing was done. Handle the epoch as the app did before. */
    +  | {readonly kind: 'off'}
    +  /** The document belongs to this epoch (or just adopted it): sync it. */
    +  | {readonly kind: 'same'}
    +  /**
    +   * The room moved on. The binding is frozen and the session has ended:
    +   * never sync this document. Open a fresh one at the new epoch and call
    +   * {@link recoverYOfflineEdits} there. `capture` is what was kept (null
    +   * when the document held nothing the server lacked); `saved` says whether
    +   * it reached the store (when not, `capture` is all there is: keep the tab
    +   * open and offer Copy).
    +   */
    +  | {
    +      readonly kind: 'moved';
    +      readonly capture: YOfflineCapture | null;
    +      readonly saved: YOfflineResult<void>;
    +    };
    +
    +/** @experimental An attached session (see {@link attachYOfflineSession}). */
    +export interface YOfflineSession {
    +  readonly stage: YOfflineStage;
    +  /** The epoch the document belongs to; null until the server names one. */
    +  readonly epoch: string | null;
    +  /** Whether the document may hold edits the server lacks. */
    +  readonly hasUnsyncedEdits: boolean;
    +  /** False after a storage failure, until a write succeeds again. */
    +  readonly persisted: boolean;
    +  /** True once the epoch moved (the binding is frozen) or after `dispose()`. */
    +  readonly ended: boolean;
    +  /**
    +   * Tell the session the epoch the server's room is at: call it before the
    +   * provider syncs this document (on every connect), and when the server
    +   * says the room was replaced. The binding is frozen before this returns
    +   * its promise, so nothing typed after a `'moved'` is lost or written.
    +   */
    +  serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict>;
    +  /**
    +   * The server says the room was replaced, and the new epoch is not known
    +   * yet: the same as `serverEpoch` with a new epoch. The binding is frozen
    +   * before this returns its promise, what it holds is captured into the
    +   * store (for `recoverYOfflineEdits` on the new document), and the
    +   * session ends. Call it on the live session, before disposing it.
    +   */
    +  freeze(options?: {
    +    readonly reason?: YOfflineCapture['reason'];
    +  }): Promise<YOfflineVerdict>;
    +  /**
    +   * The authoritative copy holds everything this document holds: the
    +   * document as it is now becomes the base later edits are judged against,
    +   * and what is stored since is replaced by it (with `keep: 'unsynced'`,
    +   * deleted). "Holds" means persisted by the copy a reload or replace of
    +   * the room is seeded from: for a relay in front of a product's store
    +   * (a connector), the product's save, not the relay's acknowledgement. A
    +   * reload drops what the relay holds above that copy. Call it only when
    +   * that copy holds every update this document has (nothing newer since):
    +   * an edit made after what was persisted would fold into the base, and a
    +   * later capture would not list it. With a relay that acknowledges
    +   * nothing, call it when the provider has synced; that leaves a window (an
    +   * edit sent in that sync that never arrived is in the base).
    +   */
    +  markSynced(): void;
    +  /** Resolves once everything queued so far is stored (or failed to be). */
    +  flush(): Promise<YOfflineResult<void>>;
    +  /** Stop listening. What is stored stays (use `store.clear` to drop it). */
    +  dispose(): void;
    +}
    +
    +const REASONS: ReadonlySet<string> = new Set(['stale', 'legacy', 'expired']);
    +
    +function requireOption(condition: boolean, message: string): asserts condition {
    +  if (!condition) {
    +    throw new TypeError(`@lexical/y/offline: ${message}`);
    +  }
    +}
    +
    +function requireStage(
    +  entry: string,
    +  stage: unknown,
    +): asserts stage is YOfflineStage {
    +  requireOption(
    +    Y_OFFLINE_STAGES.includes(stage as YOfflineStage),
    +    `${entry} needs stage: 'off' (do nothing), 'persist' (store edits on this device, and keep edits that did not sync for the Offline edits panel) or 'replay' (also reapply the replayable ones); got ${String(
    +      stage,
    +    )}.`,
    +  );
    +}
    +
    +const DONE: YOfflineResult<void> = /* @__PURE__ */ ok(undefined);
    +
    +let captureCount = 0;
    +function newCaptureId(now: number): string {
    +  const random = new Uint32Array(2);
    +  globalThis.crypto.getRandomValues(random);
    +  return `${now.toString(36)}-${random[0].toString(36)}${random[1].toString(
    +    36,
    +  )}-${captureCount++}`;
    +}
    +
    +class Session implements YOfflineSession {
    +  private epochValue: string | null;
    +  private base: Uint8Array | null;
    +  /** The state vector of the base this session stored, once it has. */
    +  private storedBaseVector: Uint8Array | null = null;
    +  private unsynced: boolean;
    +  private isEnded = false;
    +  private isPersisted = true;
    +  private slot: YOfflineSlot | null = null;
    +  /** Updates not stored yet, oldest first. */
    +  private pending: Uint8Array[] = [];
    +  /** A confirmed state not stored yet: it replaces what was pending before it. */
    +  private confirmed: {state: Uint8Array; vector: Uint8Array} | null = null;
    +  /** The epoch a never-synced slot is moving to, until it has. */
    +  private adopting: string | null = null;
    +  private lastFailure: string | null = null;
    +  private writing: Promise<YOfflineResult<void>> | null = null;
    +  private stop: () => void = () => {};
    +  private readonly now: () => number;
    +  private readonly compactAfter: number;
    +  private readonly persistEdits: boolean;
    +  private readonly keepUnsyncedOnly: boolean;
    +  private readonly writeDelay: number;
    +  /** With `keep: 'unsynced'`: whether the slot holds the base and since. */
    +  private started: boolean;
    +  /** With `keep: 'unsynced'`: the slot's rows are to be deleted (synced). */
    +  private clearing = false;
    +  /** With `keep: 'unsynced'`: the state vector of the base in memory. */
    +  private baseVector: Uint8Array | null = null;
    +  private timer: ReturnType<typeof setTimeout> | null = null;
    +  private firstDelayed = 0;
    +
    +  constructor(private readonly options: YOfflineSessionOptions) {
    +    const {binding, loaded, store} = options;
    +    this.persistEdits = options.persistEdits ?? true;
    +    this.keepUnsyncedOnly = options.keep === 'unsynced';
    +    this.writeDelay = options.writeDelay ?? 0;
    +    this.started =
    +      loaded !== undefined && loaded.state !== null && loaded.hasUnsyncedEdits;
    +    this.now = options.now ?? Date.now;
    +    this.compactAfter = options.compactAfter ?? Y_OFFLINE_DEFAULTS.compactAfter;
    +    this.epochValue = options.epoch;
    +    this.base = loaded === undefined ? null : loaded.base;
    +    this.unsynced = loaded !== undefined && loaded.hasUnsyncedEdits;
    +    if (options.stage === 'off' || store === null) {
    +      return;
    +    }
    +    const doc = binding.binding.doc;
    +    if (this.persistEdits) {
    +      this.slot =
    +        loaded !== undefined && loaded.slot !== null
    +          ? loaded.slot
    +          : store.slot(options.key, options.epoch);
    +      // This handle's first row is the whole document, so its later rows
    +      // build only on rows it wrote: another tab may replace the rows it
    +      // loaded. With keep 'unsynced', only when it loaded unsynced rows
    +      // (otherwise its first local edit stores the base and since).
    +      if (
    +        doc.store.clients.size > 0 &&
    +        (!this.keepUnsyncedOnly || this.started)
    +      ) {
    +        if (
    +          loaded !== undefined &&
    +          loaded.state !== null &&
    +          !loaded.hasUnsyncedEdits &&
    +          loaded.base !== null
    +        ) {
    +          // Loaded with nothing unsynced: the document is its base, stored
    +          // as one (a later load reports nothing unsynced).
    +          this.confirmed = {
    +            state: encodeStateAsUpdate(doc),
    +            vector: encodeStateVector(doc),
    +          };
    +        } else {
    +          this.pending.push(encodeStateAsUpdate(doc));
    +        }
    +        void this.write();
    +      }
    +    }
    +    // This client's writes (as the binding's handshake counts them): a
    +    // local transaction, or the binding's own applied as an update (the
    +    // seed of an empty document).
    +    const yBinding = binding.binding;
    +    const onTransaction = (tr: Transaction) => {
    +      if (
    +        (tr.insertSet.clients.size > 0 || tr.deleteSet.clients.size > 0) &&
    +        (tr.local ||
    +          tr.origin === yBinding ||
    +          (typeof tr.origin === 'object' &&
    +            tr.origin !== null &&
    +            (tr.origin as {binding?: unknown}).binding === yBinding))
    +      ) {
    +        this.unsynced = true;
    +      }
    +    };
    +    doc.on('afterTransaction', onTransaction);
    +    let offUpdate = () => {};
    +    if (this.persistEdits) {
    +      // Every update, a peer's too: the slot is the whole document. With
    +      // keep 'unsynced', only once a local edit made it unsynced (the
    +      // transaction's afterTransaction, which marks it, runs first).
    +      const onUpdate = (update: Uint8Array) => {
    +        if (this.keepUnsyncedOnly && !this.started) {
    +          if (!this.unsynced) {
    +            return;
    +          }
    +          // The base and what came since, a peer's updates included, are
    +          // stored from the document when the queue runs.
    +          this.started = true;
    +          this.startPending = true;
    +          this.startGeneration++;
    +          this.pending = [];
    +          this.schedule();
    +          return;
    +        }
    +        this.pending.push(update);
    +        this.schedule();
    +      };
    +      doc.on('update', onUpdate);
    +      offUpdate = () => doc.off('update', onUpdate);
    +    }
    +    this.stop = () => {
    +      doc.off('afterTransaction', onTransaction);
    +      offUpdate();
    +    };
    +  }
    +
    +  get stage(): YOfflineStage {
    +    return this.options.stage;
    +  }
    +  get epoch(): string | null {
    +    return this.epochValue;
    +  }
    +  get hasUnsyncedEdits(): boolean {
    +    return this.unsynced;
    +  }
    +  get persisted(): boolean {
    +    return this.isPersisted;
    +  }
    +  get ended(): boolean {
    +    return this.isEnded;
    +  }
    +
    +  /** Store what is queued now, or once updates pause (`writeDelay`). */
    +  private schedule(): void {
    +    if (this.writeDelay <= 0) {
    +      void this.write();
    +      return;
    +    }
    +    const now = this.now();
    +    if (this.timer === null) {
    +      this.firstDelayed = now;
    +    } else {
    +      clearTimeout(this.timer);
    +    }
    +    const wait = Math.max(
    +      0,
    +      Math.min(this.writeDelay, this.firstDelayed + 10 * this.writeDelay - now),
    +    );
    +    this.timer = setTimeout(() => {
    +      this.timer = null;
    +      void this.write();
    +    }, wait);
    +  }
    +
    +  /** Store what is queued, one transaction at a time. */
    +  private write(): Promise<YOfflineResult<void>> {
    +    if (this.timer !== null) {
    +      clearTimeout(this.timer);
    +      this.timer = null;
    +    }
    +    if (this.writing === null) {
    +      this.writing = this.drain()
    +        .catch((error: unknown): YOfflineResult<void> => {
    +          // Nothing here should throw (a merge of updates Yjs itself made):
    +          // if it does, it is a failure like any other, never a queue that
    +          // stays rejected.
    +          const failure: YOfflineError = {
    +            cause: error,
    +            code: 'failed',
    +            message: `@lexical/y/offline: storing an edit failed (${String(
    +              error,
    +            )}); the edits are still in the page. Tell the user they are not saved on this device.`,
    +          };
    +          this.isPersisted = false;
    +          this.report(failure);
    +          return fail(failure);
    +        })
    +        .then(result => {
    +          this.writing = null;
    +          return result;
    +        });
    +    }
    +    return this.writing;
    +  }
    +
    +  private async drain(): Promise<YOfflineResult<void>> {
    +    const slot = this.slot;
    +    if (slot === null) {
    +      return DONE;
    +    }
    +    while (this.hasQueued()) {
    +      let result: YOfflineResult<void>;
    +      if (this.adopting !== null) {
    +        // In the queue, so no write lands under the old key meanwhile.
    +        result = await slot.adopt(this.adopting);
    +        if (result.ok) {
    +          this.adopting = null;
    +        }
    +      } else if (this.clearing) {
    +        // keep 'unsynced', synced: the stored base and since go.
    +        this.clearing = false;
    +        result = await slot.discard();
    +        if (!result.ok && !this.clearing) {
    +          this.clearing = true;
    +        }
    +      } else if (this.needsStart()) {
    +        // keep 'unsynced', first edit since a sync: the base, then what the
    +        // document holds beyond it (null base: the whole document).
    +        const doc = this.options.binding.binding.doc;
    +        const base = this.base;
    +        const vector = this.baseVector;
    +        // A sync and a new local edit while this writes start another
    +        // generation: its own start stays due.
    +        const generation = this.startGeneration;
    +        if (base !== null && vector !== null) {
    +          result = await slot.confirm(base);
    +          if (result.ok) {
    +            this.storedBaseVector = vector;
    +            result = await slot.append(encodeStateAsUpdate(doc, vector));
    +          }
    +        } else {
    +          result = await slot.append(encodeStateAsUpdate(doc));
    +        }
    +        if (result.ok && generation === this.startGeneration) {
    +          this.startPending = false;
    +        }
    +      } else if (this.confirmed !== null) {
    +        const confirming = this.confirmed;
    +        this.confirmed = null;
    +        result = await slot.confirm(confirming.state);
    +        if (result.ok) {
    +          // Only now: a compaction is a diff against the stored base.
    +          this.storedBaseVector = confirming.vector;
    +        } else if (this.confirmed === null) {
    +          this.confirmed = confirming;
    +        }
    +      } else {
    +        const batch = this.pending;
    +        const syncs = this.syncs;
    +        this.pending = [];
    +        let row: Uint8Array;
    +        try {
    +          row =
    +            batch.length === 1
    +              ? batch[0]
    +              : mergeUpdates(batch as Parameters<typeof mergeUpdates>[0]);
    +        } catch (error) {
    +          this.pending = [...batch, ...this.pending];
    +          throw error;
    +        }
    +        result = await slot.append(row);
    +        if (!result.ok) {
    +          // A sync meanwhile covers the batch: it is not queued again (it
    +          // would be stored as edits the server lacks, or, with keep
    +          // 'unsynced', as a row with no base after the clear).
    +          if (syncs === this.syncs) {
    +            this.pending = [...batch, ...this.pending];
    +          }
    +        } else if (slot.rowsSinceCompaction >= this.compactAfter) {
    +          result = await slot.compact(this.sinceBase());
    +        }
    +      }
    +      if (!result.ok) {
    +        // Kept in the queue: the next update, or flush(), retries. Reported
    +        // once per failure, not once per keystroke while it lasts.
    +        if (this.isPersisted || this.lastFailure !== result.error.code) {
    +          this.report(result.error);
    +        }
    +        this.isPersisted = false;
    +        this.lastFailure = result.error.code;
    +        return result;
    +      }
    +      this.isPersisted = true;
    +      this.lastFailure = null;
    +    }
    +    return DONE;
    +  }
    +
    +  /** Counts markSynced() calls: a batch whose append failed across one is covered. */
    +  private syncs = 0;
    +  /** keep 'unsynced': the slot's first write since a sync is due. */
    +  private startPending = false;
    +  /** keep 'unsynced': counts starts, so an old one's end clears no new one. */
    +  private startGeneration = 0;
    +  private needsStart(): boolean {
    +    return this.keepUnsyncedOnly && this.startPending;
    +  }
    +
    +  private hasQueued(): boolean {
    +    return (
    +      this.adopting !== null ||
    +      this.clearing ||
    +      this.needsStart() ||
    +      this.confirmed !== null ||
    +      this.pending.length > 0
    +    );
    +  }
    +
    +  /**
    +   * What the document holds beyond the base this session confirmed;
    +   * undefined before it confirmed one (the rows are merged instead).
    +   */
    +  private sinceBase(): Uint8Array | undefined {
    +    return this.storedBaseVector === null
    +      ? undefined
    +      : encodeStateAsUpdate(
    +          this.options.binding.binding.doc,
    +          this.storedBaseVector,
    +        );
    +  }
    +
    +  private report(error: YOfflineError): void {
    +    try {
    +      this.options.onError(error);
    +    } catch (thrown) {
    +      queueMicrotask(() => {
    +        throw thrown;
    +      });
    +    }
    +  }
    +
    +  flush(): Promise<YOfflineResult<void>> {
    +    return this.write().then(result =>
    +      // Queued while it ran.
    +      result.ok && this.hasQueued() ? this.flush() : result,
    +    );
    +  }
    +
    +  markSynced(): void {
    +    if (this.options.stage === 'off' || this.isEnded) {
    +      return;
    +    }
    +    if (this.epochValue === null) {
    +      throw new Error(
    +        "@lexical/y/offline: markSynced() before the session knows the room's epoch. Call await session.serverEpoch(epoch) when the server names its epoch (before the provider syncs), then markSynced() after the sync.",
    +      );
    +    }
    +    const doc = this.options.binding.binding.doc;
    +    const state = encodeStateAsUpdate(doc);
    +    this.base = state;
    +    this.unsynced = false;
    +    this.syncs++;
    +    if (this.slot !== null) {
    +      // The state holds everything queued before it.
    +      this.pending = [];
    +      if (this.keepUnsyncedOnly) {
    +        // Nothing is kept while synced: the base stays in memory until the
    +        // next local edit stores it.
    +        this.baseVector = encodeStateVector(doc);
    +        this.started = false;
    +        this.startPending = false;
    +        this.confirmed = null;
    +        this.clearing = true;
    +      } else {
    +        this.confirmed = {state, vector: encodeStateVector(doc)};
    +      }
    +      void this.write();
    +    }
    +  }
    +
    +  async serverEpoch(
    +    epoch: string,
    +    options?: {readonly reason?: YOfflineCapture['reason']},
    +  ): Promise<YOfflineVerdict> {
    +    requireOption(
    +      typeof epoch === 'string' && epoch !== '',
    +      `serverEpoch(epoch) takes the epoch (generation) your server named, as a non-empty string (String(epoch) for a number); got ${
    +        epoch === '' ? "''" : typeof epoch
    +      }.`,
    +    );
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `serverEpoch's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed). Attach a new session to the new document: attachYOfflineSession({binding, epoch, ...}).',
    +      );
    +    }
    +    if (this.epochValue === epoch) {
    +      return {kind: 'same'};
    +    }
    +    if (this.epochValue === null) {
    +      // A document that never synced belongs to the first epoch it meets.
    +      this.epochValue = epoch;
    +      if (this.slot !== null) {
    +        // A failure is reported through onError; the queue retries.
    +        this.adopting = epoch;
    +        await this.flush();
    +      }
    +      return {kind: 'same'};
    +    }
    +    return this.moveOn(reason);
    +  }
    +
    +  async freeze(options?: {
    +    readonly reason?: YOfflineCapture['reason'];
    +  }): Promise<YOfflineVerdict> {
    +    const reason = options === undefined ? undefined : options.reason;
    +    requireOption(
    +      reason === undefined || REASONS.has(reason),
    +      `freeze's reason is 'stale' (the default: the room moved on), 'legacy' or 'expired'; got ${String(
    +        reason,
    +      )}.`,
    +    );
    +    if (this.options.stage === 'off') {
    +      return {kind: 'off'};
    +    }
    +    if (this.isEnded) {
    +      throw new Error(
    +        '@lexical/y/offline: this session has ended (its epoch moved, or it was disposed): freeze() runs on the live session, when the server says the room was replaced.',
    +      );
    +    }
    +    return this.moveOn(reason);
    +  }
    +
    +  /** The room moved on: freeze, capture into the store, end the session. */
    +  private async moveOn(
    +    reason: YOfflineCapture['reason'] | undefined,
    +  ): Promise<YOfflineVerdict> {
    +    // Freeze first, synchronously: from here nothing is written to the
    +    // document, and what the editor holds is in the capture.
    +    const from = this.epochValue;
    +    const {binding, key, store} = this.options;
    +    const edits = binding.freeze();
    +    // Read after the freeze: it commits what the editor still held.
    +    const wasUnsynced = this.unsynced;
    +    this.isEnded = true;
    +    this.stop();

    Optional: a pending writeDelay timer is not cleared here. If it fires while moveIntoCapture runs, drain() appends the queued batch after the rows to delete were chosen. One since row is then left at the old epoch, and the next recoverYOfflineEdits turns it into a capture (base: null) whose report is 'failed' on every call. With writeDelay: 8 it happens when the epoch moves 0 or 4–7 ms after the last edit; clearing the timer here avoids it at every timing:

        this.stop();
        if (this.timer !== null) {
          clearTimeout(this.timer);
          this.timer = null;
        }
    

    The queued batch is still stored on the failure path, which calls flush().

    rootnode-bot[bot] rootnode-bot[bot] approved these changes on Nov 13, 2026 17:34 UTC
    Approved Reviewer

    This looks good to me. Thanks for the thorough tests and docs. @lexical/y/offline is additive and opt-in, its TypeScript and Flow declarations match, and the store, session and replay behave as the new y.md section describes, including the playground's Collab Y Offline mode at both the persist and replay stages. The one suggestion below is optional and non-blocking.

    Optional: clear the writeDelay timer when the epoch moves (packages/lexical-y/src/internal/OfflineSession.ts, in moveOn, line 797)

    moveOn stops the listeners and awaits this.writing, but a pending writeDelay timer keeps running. If that timer fires while moveIntoCapture is running, drain() appends the queued batch after moveIntoCapture has chosen the rows to delete. One since row is left at the old epoch, and slot.close() releases its lock.

    The next recoverYOfflineEdits captures that lone delta row (base: null). Its report comes back 'failed' on every call, so the panel keeps an entry that cannot be compared until the user dismisses it. No edit is lost: the real edit is in the first capture.

    With writeDelay: 8, an epoch that moves 0 or 4–7 ms after the last edit leaves the row behind. Clearing the timer right after this.stop() avoids it at every timing, and OfflineSession.test.ts and OfflineFaults.test.ts still pass with the change:

    this.isEnded = true;
    this.stop();
    if (this.timer !== null) {
      clearTimeout(this.timer);
      this.timer = null;
    }
    

    The queued batch is still written on the failure path, which calls flush(). If you take this, packages/lexical-y/AGENTS.md asks for a regression test in src/__tests__/unit/regressions/: for example, move the epoch with writeDelay set and assert that store.slots(key) is empty afterwards.

    Automated review (maintainer link)

    <!-- codebunny-pub:1 k=0af65ab7112febce0511ac53a0b907682b23bc0e6505db8774834d89ef4f8ebe -->

    Reviewers
    Assignees
    zurfyx zurfyx
    Labels
    risk: low confidence: 68.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 85.5% (HIGH) · Higher = larger blast radius
    85.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 68.8% · Lower = rushed or shallow review
    68.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 26.7% · Safe to merge
    26.7%
    Repository