{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "data-grid-server",
  "title": "Data Grid Server",
  "author": "gridcn",
  "description": "One server data source for the gridcn data grid: useDataGridServerRows owns sort, filter, search, page and page size, fetches one page per state with a race guard (pages mode) or fixed-size blocks as the rendered rows move, random access over a counted result or a sequential cursor chain (scroll mode), goes back to page 1 on a spec change, keeps the last good rows on screen, and validates every answer, and exposes status, error, retry and refresh. Controlled spec, page and page size pairs take a URL pagination result. Returns gridProps for DataGrid and pager controls for the pagination bar.",
  "dependencies": [],
  "registryDependencies": [
    "@gridcn/data-grid",
    "@gridcn/data-grid-pagination"
  ],
  "files": [
    {
      "path": "registry/default/blocks/data-grid-server/data-grid-server.ts",
      "content": "/** Public entry point — the only module consumers/docs should import from. */\n\nexport {\n  useDataGridServerRows,\n  type UseDataGridServerRowsOptions,\n  type UseDataGridServerRowsResult,\n  type ServerRowsPageRequest,\n  type ServerRowsRequest,\n  type ServerRowsAnswer,\n  type DataSourceState,\n  type UseDataGridServerRowsScrollOptions,\n  type UseDataGridServerRowsScrollResult,\n} from \"./use-data-grid-server-rows\";\nexport type { SaveRefreshPolicy, SaveRefreshReport } from \"./save-refresh\";\nexport { parseServerSpec, parseGroupPath, ServerSpecError, type ParseServerSpecOptions, type ServerSpecColumnRules, type ServerSpecLimits } from \"./parse-server-spec\";\nexport type { ServerChildKind, ServerGroupPath, ServerGroupRow, ServerGroupsAnswer } from \"./read-groups-answer\";\nexport type { ServerFetchAnswer } from \"./read-answer\";\n",
      "type": "registry:component",
      "target": "components/data-grid-server/data-grid-server.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/range-math.ts",
      "content": "import type { RowRange } from \"@/registry/default/components/data-grid/data-grid\";\n\n/** `end - start`, clamped to 0 for an inverted/empty range. */\nexport function rangeSize(range: RowRange): number {\n  return Math.max(0, range.end - range.start);\n}\n\n/** Whether two half-open ranges overlap or touch at an edge (touching ranges are mergeable). */\nfunction rangesAdjacentOrOverlapping(a: RowRange, b: RowRange): boolean {\n  return a.start <= b.end && b.start <= a.end;\n}\n\n/**\n * Expands `range` by `overscan` rows on each side, then rounds outward so both edges land on a\n * `blockSize` boundary — small scrolls request the same batch repeatedly instead of a slightly\n * different range every tick.\n * Clamps to `[0, total]`.\n */\nexport function expandRange(range: RowRange, opts: { overscan: number; blockSize: number; total?: number }): RowRange {\n  const { overscan, blockSize, total = Infinity } = opts;\n  const withOverscan = { start: range.start - overscan, end: range.end + overscan };\n  const batch = Math.max(1, blockSize);\n  const start = Math.floor(withOverscan.start / batch) * batch;\n  const end = Math.ceil(withOverscan.end / batch) * batch;\n  return {\n    start: Math.max(0, start),\n    end: Math.min(total, Math.max(start, end)),\n  };\n}\n\n/**\n * Subtracts every range in `covered` (already loaded or in-flight, any order/overlap) from\n * `target`, returning the remaining uncovered pieces coalesced into as few ranges as possible —\n * this is the \"never re-request a loading/loaded range; merge adjacent gaps\" rule as pure math.\n */\nexport function subtractRanges(target: RowRange, covered: readonly RowRange[]): RowRange[] {\n  if (rangeSize(target) === 0) return [];\n  const relevant = covered\n    .filter((r) => rangeSize(r) > 0 && rangesAdjacentOrOverlapping(r, target))\n    .map((r) => ({ start: Math.max(r.start, target.start), end: Math.min(r.end, target.end) }))\n    .sort((a, b) => a.start - b.start);\n\n  const merged: RowRange[] = [];\n  for (const r of relevant) {\n    const last = merged[merged.length - 1];\n    if (last && r.start <= last.end) {\n      last.end = Math.max(last.end, r.end);\n    } else {\n      merged.push({ ...r });\n    }\n  }\n\n  const gaps: RowRange[] = [];\n  let cursor = target.start;\n  for (const r of merged) {\n    if (r.start > cursor) gaps.push({ start: cursor, end: r.start });\n    cursor = Math.max(cursor, r.end);\n  }\n  if (cursor < target.end) gaps.push({ start: cursor, end: target.end });\n  return gaps;\n}\n\n/** Sum of `rangeSize` across a list of ranges — callers pass an already-merged (disjoint) list so this is a true row count, not a double-count of overlaps. */\nexport function sumRangeSizes(ranges: readonly RowRange[]): number {\n  return ranges.reduce((total, r) => total + rangeSize(r), 0);\n}\n\n/**\n * Splits `range` into consecutive chunks of at most `max` rows, covering it exactly once; a\n * single chunk when the range already fits. Each chunk obeys the `fetchRows` contract on its\n * own: exactly `chunk.end - chunk.start` rows, positionally aligned to `chunk.start`. A\n * fractional `max` is rounded down so every chunk boundary stays an integral row index.\n */\nexport function chunkRange(range: RowRange, max: number): RowRange[] {\n  const size = rangeSize(range);\n  const cap = Math.max(1, Math.floor(max));\n  if (size <= cap) return [range];\n  const chunks: RowRange[] = [];\n  for (let start = range.start; start < range.end; start += cap) {\n    chunks.push({ start, end: Math.min(range.end, start + cap) });\n  }\n  return chunks;\n}\n\n/** Splits `range` at the multiples of `size`, so each chunk lies inside one block of the grid of blocks. */\nexport function chunkAligned(range: RowRange, size: number): RowRange[] {\n  const step = Math.max(1, Math.floor(size));\n  const chunks: RowRange[] = [];\n  for (let start = range.start; start < range.end; ) {\n    const end = Math.min(range.end, (Math.floor(start / step) + 1) * step);\n    chunks.push({ start, end });\n    start = end;\n  }\n  return chunks;\n}\n\n/** Merges a list of ranges (any order/overlap) into the minimal set of disjoint, non-touching ranges. */\nexport function mergeRanges(ranges: readonly RowRange[]): RowRange[] {\n  const sorted = ranges\n    .filter((r) => rangeSize(r) > 0)\n    .slice()\n    .sort((a, b) => a.start - b.start);\n  const merged: RowRange[] = [];\n  for (const r of sorted) {\n    const last = merged[merged.length - 1];\n    if (last && r.start <= last.end) {\n      last.end = Math.max(last.end, r.end);\n    } else {\n      merged.push({ ...r });\n    }\n  }\n  return merged;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/range-math.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/fetch-hygiene.ts",
      "content": "import type { RowRange } from \"@/registry/default/components/data-grid/data-grid\";\nimport { rangeSize, sumRangeSizes } from \"./range-math\";\n\nexport const DEFAULT_LOAD_DELAY = 100;\nconst MAX_LOAD_DELAY = 2000;\nexport const DEFAULT_MAX_CONCURRENT_FETCHES = 3;\nconst MAX_CONCURRENT_FETCHES = 16;\nexport const DEFAULT_MAX_LOADED_ROWS = 10_000;\n\n/** A sequential revalidation walks from block 0 to the rendered rows; a tick that would take more blocks is skipped. */\nexport const MAX_SEQUENTIAL_REVALIDATE_BLOCKS = 10;\nexport const MIN_REVALIDATE_INTERVAL = 1000;\nexport const MAX_REVALIDATE_INTERVAL = 2_147_483_647;\n\nexport type FetchLimitOptions = { loadDelayMs?: number; maxConcurrentFetches?: number; maxLoadedRows?: number };\n\nexport type FetchLimits = {\n  loadDelayMs: number;\n  maxConcurrentFetches: number;\n  /** `Infinity` turns eviction off. */\n  maxLoadedRows: number;\n  /** The consumer passed a value that is not a number, `NaN`, or negative. */\n  maxLoadedRowsInvalid: boolean;\n};\n\nfunction clampedInteger(value: unknown, fallback: number, min: number, max: number): number {\n  return typeof value === \"number\" && Number.isFinite(value) ? Math.min(max, Math.max(min, Math.floor(value))) : fallback;\n}\n\n/** Reads the fetch limit options and never throws: a non-number or a negative `maxLoadedRows` falls back to its default, and an out-of-range number clamps. */\nexport function readFetchLimits(blockSize: number, options: FetchLimitOptions = {}): FetchLimits {\n  const rows: unknown = options.maxLoadedRows;\n  let maxLoadedRows = DEFAULT_MAX_LOADED_ROWS;\n  let maxLoadedRowsInvalid = false;\n  if (rows === Infinity) maxLoadedRows = Infinity;\n  else if (typeof rows === \"number\" && Number.isFinite(rows) && rows >= 0) maxLoadedRows = Math.max(blockSize, Math.floor(rows));\n  else if (rows !== undefined) maxLoadedRowsInvalid = true;\n  return {\n    loadDelayMs: clampedInteger(options.loadDelayMs, DEFAULT_LOAD_DELAY, 0, MAX_LOAD_DELAY),\n    maxConcurrentFetches: clampedInteger(options.maxConcurrentFetches, DEFAULT_MAX_CONCURRENT_FETCHES, 1, MAX_CONCURRENT_FETCHES),\n    maxLoadedRows,\n    maxLoadedRowsInvalid,\n  };\n}\n\n/** The interval in ms, or `null` when revalidation is off; `invalid` marks a value that was set but unusable, `raised` a value below the minimum. */\nexport function readRevalidateInterval(value: unknown): { interval: number | null; invalid: boolean; raised: boolean } {\n  if (value === undefined) return { interval: null, invalid: false, raised: false };\n  if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) return { interval: null, invalid: true, raised: false };\n  const interval = Math.min(MAX_REVALIDATE_INTERVAL, Math.floor(value));\n  return { interval: Math.max(MIN_REVALIDATE_INTERVAL, interval), invalid: false, raised: interval < MIN_REVALIDATE_INTERVAL };\n}\n\nexport const MIN_RESHAPE_DELAY = 250;\n\n/** The reshape delay of a spec with a sort or a filter when `reshapeDelayMs` is not set. */\nexport const DEFAULT_RESHAPE_DELAY = 1000;\n\n/** The delay in ms, or `null` when the reshape delay is off; `invalid` marks a value that was set but unusable, `raised` a value below the minimum. `false` turns the default off. */\nexport function readReshapeDelay(value: unknown): { delay: number | null; invalid: boolean; raised: boolean } {\n  if (value === undefined || value === false) return { delay: null, invalid: false, raised: false };\n  if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) return { delay: null, invalid: true, raised: false };\n  const delay = Math.min(MAX_REVALIDATE_INTERVAL, Math.floor(value));\n  return { delay: Math.max(MIN_RESHAPE_DELAY, delay), invalid: false, raised: delay < MIN_RESHAPE_DELAY };\n}\n\n/** The wanted range grown by one block on each side, clamped to the result. Abort and eviction act outside it only. */\nexport function keepRange(wanted: RowRange, blockSize: number, total: number): RowRange {\n  return { start: Math.max(0, wanted.start - blockSize), end: Math.min(total, wanted.end + blockSize) };\n}\n\nexport function rangesIntersect(a: RowRange, b: RowRange): boolean {\n  return a.start < b.end && b.start < a.end;\n}\n\n/** Uncovered blocks of the wanted range, by block start: the end of the block and when it first entered the range. */\nexport type Wanted = Map<number, { end: number; since: number }>;\n\n/** Drops the entries that left the wanted range and adds the new ones with `now`; an entry that stays keeps its time. */\nexport function trackWanted(wanted: Wanted, uncovered: readonly RowRange[], now: number): void {\n  const current = new Set<number>();\n  for (const block of uncovered) {\n    current.add(block.start);\n    const known = wanted.get(block.start);\n    if (known) known.end = block.end;\n    else wanted.set(block.start, { end: block.end, since: now });\n  }\n  for (const start of wanted.keys()) if (!current.has(start)) wanted.delete(start);\n}\n\n/** The blocks that stayed in the wanted range for `delay` ms, nearest to `centre` first and at most `limit`, and when the next one is due. */\nexport function dueWanted(wanted: Wanted, { now, delay, centre, limit }: { now: number; delay: number; centre: number; limit: number }): { due: RowRange[]; nextAt: number | null } {\n  const due: RowRange[] = [];\n  let nextAt: number | null = null;\n  for (const [start, { end, since }] of wanted) {\n    const at = since + delay;\n    if (at <= now) due.push({ start, end });\n    else if (nextAt === null || at < nextAt) nextAt = at;\n  }\n  due.sort((a, b) => distanceToCentre(a, centre) - distanceToCentre(b, centre) || a.start - b.start);\n  return { due: due.slice(0, Math.max(0, limit)), nextAt };\n}\n\nexport function distanceToCentre(range: RowRange, centre: number): number {\n  return Math.abs((range.start + range.end) / 2 - centre);\n}\n\nexport type EvictionPick = {\n  /** A whole block of the result. */\n  block: RowRange;\n  /** Slots of the block whose rows stay in `data` because they are protected. They move from loaded to stale. */\n  kept: readonly number[];\n};\n\ntype EvictionInput = {\n  /** Merged and ascending. */\n  loaded: readonly RowRange[];\n  /** Block index -> stamp of the latest report that had the block in its keep range; a block without a stamp is the oldest. */\n  viewed: ReadonlyMap<number, number>;\n  keep: RowRange;\n  blockSize: number;\n  cap: number;\n  /** The slots of the block whose loaded rows must stay. */\n  protectedSlots?: (block: RowRange) => readonly number[];\n};\n\n/**\n * Picks whole blocks outside the keep range, least recently viewed first, until the loaded rows fit under `cap`.\n * A block with protected slots frees only its other rows; a block that frees nothing is skipped. The cap is soft.\n */\nexport function pickEvictions({ loaded, viewed, keep, blockSize, cap, protectedSlots }: EvictionInput): EvictionPick[] {\n  let total = sumRangeSizes(loaded);\n  if (total <= cap) return [];\n  const sizes = new Map<number, number>();\n  for (const range of loaded) {\n    for (let index = Math.floor(range.start / blockSize); index * blockSize < range.end; index++) {\n      const block = { start: index * blockSize, end: (index + 1) * blockSize };\n      const overlap = Math.min(range.end, block.end) - Math.max(range.start, block.start);\n      sizes.set(index, (sizes.get(index) ?? 0) + overlap);\n    }\n  }\n  const candidates = [...sizes.keys()].filter((index) => !rangesIntersect({ start: index * blockSize, end: (index + 1) * blockSize }, keep));\n  candidates.sort((a, b) => (viewed.get(a) ?? 0) - (viewed.get(b) ?? 0) || a - b);\n  const picks: EvictionPick[] = [];\n  for (const index of candidates) {\n    if (total <= cap) break;\n    const block = { start: index * blockSize, end: (index + 1) * blockSize };\n    const kept = protectedSlots?.(block) ?? [];\n    const freed = sizes.get(index)! - kept.length;\n    if (freed <= 0) continue;\n    picks.push({ block, kept });\n    total -= freed;\n  }\n  return picks;\n}\n\n/** The block ranges of a pick, minus the kept slots, as ranges to unload. */\nexport function unloadRangesOf(pick: EvictionPick): RowRange[] {\n  const ranges: RowRange[] = [];\n  let from = pick.block.start;\n  for (const slot of [...pick.kept].sort((a, b) => a - b)) {\n    if (slot > from) ranges.push({ start: from, end: slot });\n    from = slot + 1;\n  }\n  if (from < pick.block.end) ranges.push({ start: from, end: pick.block.end });\n  return ranges.filter((range) => rangeSize(range) > 0);\n}\n\n/** Drops the stamps of blocks that hold no loaded row and sit outside the keep range. */\nexport function pruneViewed(viewed: Map<number, number>, loaded: readonly RowRange[], keep: RowRange, blockSize: number): void {\n  const held = new Set<number>();\n  for (const range of loaded) for (let index = Math.floor(range.start / blockSize); index * blockSize < range.end; index++) held.add(index);\n  for (const index of viewed.keys()) {\n    if (!held.has(index) && !rangesIntersect({ start: index * blockSize, end: (index + 1) * blockSize }, keep)) viewed.delete(index);\n  }\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/fetch-hygiene.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/scroll-blocks.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport { serverSpecKey, type DataChange, type DataGridPlugin, type FilterNode, type RowRange, type ServerSpec, type SortSpec } from \"@/registry/default/components/data-grid/data-grid\";\nimport { applyChangeWith, holeRowId, isDev } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { isGroupsAnswer } from \"./group-pages\";\nimport type { ServerGroupsAnswer } from \"./read-groups-answer\";\nimport { readAnswer, type FetchReason, type ReadAnswer, type ServerFetchAnswer, type ServerRowsAnswer, type ServerRowsRequest, type WithRowId } from \"./read-answer\";\nimport { pruneIds, stashGuardedRows, trackDeletes, unionIds, useRefreshGuard, writeBlocks, type ProtectedRows } from \"./refresh-guard\";\nimport { cursorKey, MAX_SEEN_CURSORS, needsNextBlock, skeletonCount, startsSequence, stepSequence } from \"./scroll-sequence\";\nimport { chunkAligned, chunkRange, expandRange, mergeRanges, rangeSize, subtractRanges, sumRangeSizes } from \"./range-math\";\nimport { DEFAULT_MAX_LOADED_ROWS, MAX_SEQUENTIAL_REVALIDATE_BLOCKS, distanceToCentre, dueWanted, keepRange, rangesIntersect, readFetchLimits, trackWanted, type FetchLimits } from \"./fetch-hygiene\";\nimport { readScrollSeed } from \"./scroll-seed\";\nimport { createCore, freshSequence, type Core, type Guard } from \"./scroll-core\";\nimport { evictedBlocksIn, evictSequenceRows, sequenceLoaded, shiftBlocks } from \"./sequence-eviction\";\nimport { evictRows, forgetUnloaded, stampLanded, stampViewed, unloadRows } from \"./scroll-eviction\";\nimport { useSaveRefresh, type SaveRefreshOptions, type SaveRefreshPolicy } from \"./save-refresh\";\nimport { isolate, scheduleFrame, useMountedPlugins, useRegisteredWiring, useReshape, useRevalidation, type ServerSpecState } from \"./server-state\";\nimport type { UseDataGridServerRowsRootProps } from \"./use-data-grid-server-rows\";\n\nconst DEFAULT_OVERSCAN = 30;\nconst DEFAULT_BLOCK_SIZE = 50;\n\n/** Options of `useDataGridServerRows` in scroll mode. */\nexport type UseDataGridServerRowsScrollOptions<TData, TCursor = never> = {\n  /** `\"scroll\"` fetches fixed-size blocks as the rendered rows move. Fixed for the life of the hook. */\n  mode: \"scroll\";\n  /** Identifies a row. Default: the row's `id` field (a string or number), the same default as `DataGridProvider`. */\n  getRowId?: (row: TData, index: number) => string;\n  /**\n   * How the source is fetched. `\"random\"` fetches any block by position and needs a `totalRowCount` in every answer (a development\n   * warning names an answer without one). `\"sequential\"` fetches the blocks in order, with a cursor or with offsets and `hasMore`. Default: the first answer picks it, by the rule of `fetchRows`.\n   */\n  source?: \"random\" | \"sequential\";\n  /**\n   * Resolves rows `[start, end)` of the result. The first answer picks the fetch order:\n   * - `totalRowCount` and no `nextCursor`: random access. The grid sizes its rows from the count, and a changed count starts the blocks over.\n   * - `nextCursor` (with or without a count), or neither: sequential. The grid shows the loaded rows plus one block of skeletons, and\n   *   the next block starts when the rendered rows come near the end. `nextCursor` comes back as `cursor`; `nextCursor: null`,\n   *   `hasMore: false`, or an empty block ends the source. Without a cursor, `hasMore` defaults to a full block.\n   */\n  fetchRows: (request: ServerRowsRequest<TCursor>) => Promise<ServerFetchAnswer<TData, TCursor>>;\n  /**\n   * The sort, filter, and search while `spec` is not controlled. A function runs once on the client after mount, so it can read\n   * `localStorage`; it returns the spec or `undefined`. The first request waits for it.\n   */\n  defaultSpec?: Partial<ServerSpec> | (() => Partial<ServerSpec> | undefined);\n  /** Controls the sort, filter, and search; pair it with `onSpecChange`. A content change starts the blocks over. */\n  spec?: ServerSpec;\n  onSpecChange?: (spec: ServerSpec) => void;\n  /**\n   * The answer of block 0, rows `[0, blockSize)`, for the first spec (`defaultSpec`, or the empty spec when `defaultSpec` is a function), for example from a Server Component.\n   * The hook shows it without a request, so the server HTML holds the rows; the first answer picks random access or a sequential source as `fetchRows` does, and a cursor continues the chain.\n   * Rows past `blockSize` are cut. Another first spec drops it and fetches. `refresh()` and a spec change fetch as usual.\n   * While the first spec groups, it is the groups answer of the top level (`{ groups, groupCount, totalRowCount }`).\n   * It counts as untrusted input like any answer. `onLoaded` does not fire for it.\n   */\n  initialAnswer?: ServerRowsAnswer<TData, TCursor> | ServerGroupsAnswer;\n  /** Rows per request. Requests align to multiples of it, so small scrolls reuse the same block. Default 50. */\n  blockSize?: number;\n  /** Rows fetched beyond the rendered rows on each side. Default 30. */\n  overscan?: number;\n  /**\n   * Milliseconds a block stays in the wanted range before its request starts. A fast scroll starts no request until it rests.\n   * Block 0, `refresh()`, `retry()`, and the refetch after the first answer or a count change skip it. Default 100, at most 2,000; `0` starts at once.\n   */\n  loadDelayMs?: number;\n  /** Most block requests in flight at once on a random access source. Default 3, at most 16. */\n  maxConcurrentFetches?: number;\n  /**\n   * Most rows kept loaded on a random access source. When more are loaded, the least recently viewed blocks outside the rendered rows\n   * plus overscan plus one block unload. Rows with an open edit, a pending save, or an unsaved change, and the row under the active cell, stay in `data`\n   * but stop counting as loaded, so the next window fetches their block whole.\n   * `Infinity` keeps every row. Default 10,000; a value below `blockSize` counts as `blockSize`. A sequential source cannot fetch a block again,\n   * so it keeps every loaded row by default; a finite `maxLoadedRows` ends its chain once that many rows loaded (dev-warned once).\n   */\n  maxLoadedRows?: number;\n  /**\n   * Milliseconds between `refresh()` calls the hook runs itself while the page is visible. A tick waits for a request in flight,\n   * and every refresh restarts the clock. A sequential source skips a tick while the rendered rows plus `overscan` end beyond 10 blocks.\n   * At least 1000. Off by default.\n   */\n  revalidateIntervalMs?: number;\n  /**\n   * Milliseconds to wait after a push marked a row stale before the hook runs a `refresh()` (a reshape) so the server places the\n   * rows again. The first push starts the wait and later pushes join it, so a steady feed reshapes at most once per delay. A\n   * reshape that falls due during a request, or while the page is hidden, waits and runs once; a sequential source skips it while the\n   * rendered rows plus `overscan` end beyond 10 blocks. At least 250. Default 1000 while the spec has a sort or a filter, and off otherwise;\n   * `false` turns it off, and a stale row then waits for `reshape()`, `refresh()`, or a spec change.\n   */\n  reshapeDelayMs?: number | false;\n  /** Fires after a request fails. */\n  onError?: (error: unknown) => void;\n  /** Fires after the rows of a block land, with the range they cover. The grid shows them on the next frame. */\n  onLoaded?: (range: RowRange) => void;\n  /** Fires after the hook merged an edit, insert, delete, or revert. A provider `onDataChange` after the spread runs next to the merge. */\n  onDataChange?: (next: readonly TData[], change: DataChange<TData>) => void;\n  /** Saves a change; spread to the provider through `gridProps.onSave`, where it behaves as the `DataGridProvider` prop of the same name. The hook refreshes after saves settle by `refreshAfterSave`. */\n  onSave?: SaveRefreshOptions<TData>[\"onSave\"];\n  /** When the hook calls `refresh()` after `onSave` settles: `\"settled\"` once after every save in flight (default), `\"each\"` after saves settle without waiting for the saves in flight, `false` never, or a function that gets the counts and returns whether to refresh. A sequential source skips the refresh while the rendered rows plus `overscan` end beyond 10 blocks. */\n  refreshAfterSave?: SaveRefreshPolicy;\n  /** Plugins the hook mounts after its refresh guard, through `gridProps.plugins`. */\n  plugins?: readonly DataGridPlugin<unknown>[];\n  /** Fires after the hook's own handler of `gridProps.onRenderedRowsChange`, with the rendered rows. */\n  onRenderedRowsChange?: (range: RowRange) => void;\n};\n\nimport type { UseDataGridServerRowsScrollProviderProps, UseDataGridServerRowsScrollResult } from \"./scroll-types\";\nexport type { UseDataGridServerRowsScrollProviderProps, UseDataGridServerRowsScrollResult } from \"./scroll-types\";\n\nfunction oldestMark<TData>(core: Core<TData>): number | null {\n  let oldest: number | null = null;\n  const note = (mark: number) => {\n    if (oldest === null || mark < oldest) oldest = mark;\n  };\n  for (const { guard } of core.inFlight.values()) note(guard.mark);\n  for (const { mark } of core.pending) note(mark);\n  return oldest;\n}\n\nfunction busy<TData>(core: Core<TData>): boolean {\n  return core.inFlight.size > 0 || core.pending.length > 0 || core.owed.length > 0;\n}\n\nfunction resetQueues<TData>(core: Core<TData>) {\n  if (core.delayTimer !== null) clearTimeout(core.delayTimer);\n  core.delayTimer = null;\n  core.wanted.clear();\n  core.reloads.clear();\n  core.owed = [];\n}\n\n/** Keeps the entries of rows that are still protected: a queued commit may still read or fill the map. */\nfunction forgetDisplacedWhenIdle<TData>(core: Core<TData>, stillProtected: ProtectedRows) {\n  if (oldestMark(core) !== null) return;\n  for (const id of core.displaced.keys()) if (!stillProtected?.has(id)) core.displaced.delete(id);\n  core.orphans = new Map();\n  core.carried = new Set();\n}\n\nfunction commitOnFrame<TData>(core: Core<TData>, commit: () => void, onIdle: () => void) {\n  if (core.cancelFrame !== null) return;\n  commit();\n  core.cancelFrame = scheduleFrame(() => {\n    core.cancelFrame = null;\n    if (core.pending.length > 0) commitOnFrame(core, commit, onIdle);\n    else onIdle();\n  });\n}\n\nconst rangeKey = (range: RowRange) => `${range.start}:${range.end}`;\n\nfunction positiveInteger(value: number | undefined, fallback: number, min: number): number {\n  return typeof value === \"number\" && Number.isFinite(value) ? Math.max(min, Math.floor(value)) : fallback;\n}\n\n/** Scroll mode of `useDataGridServerRows`: random access over a counted result, or a sequential chain of blocks. */\nexport function useScrollBlocks<TData, TCursor = never>(options: WithRowId<UseDataGridServerRowsScrollOptions<TData, TCursor>, TData>, specState: ServerSpecState): UseDataGridServerRowsScrollResult<TData> {\n  const { spec, ready: specReady, onSortChange, onFilterChange, onFilterJoinChange, onSearchTextChange } = specState;\n  const coreRef = useRef<Core<TData> | null>(null);\n  const getCore = useCallback((): Core<TData> => {\n    if (coreRef.current === null) coreRef.current = createCore<TData>();\n    return coreRef.current;\n  }, []);\n  const [seed] = useState(() => readScrollSeed(isGroupsAnswer(options.initialAnswer) ? undefined : (options.initialAnswer as ServerRowsAnswer<TData, TCursor> | undefined), serverSpecKey(spec), positiveInteger(options.blockSize, DEFAULT_BLOCK_SIZE, 1), options.source));\n  const seedRef = useRef(seed);\n  const [rows, setRows] = useState<(TData | undefined)[]>(() => seed?.rows ?? []);\n  const [count, setCount] = useState<number | null>(() => seed?.count ?? null);\n  const [loadedCount, setLoadedCount] = useState(() => seed?.loadedCount ?? 0);\n  const [skeletons, setSkeletons] = useState<number | null>(() => seed?.skeletons ?? null);\n  const { plugins: guardPlugins, protectedRows, savingRows, saveMark, savedSince, pruneSaves, overlayPushed, streamUpdateRow, setSettleListener, setReshapeListener, forgetStructural, evictionProtected, acknowledge, unacknowledgedRows } = useRefreshGuard({ trackUnacknowledged: true });\n  const [loading, setLoading] = useState(seed === null);\n  const [error, setError] = useState<unknown>(null);\n  const live = useRef({ options, spec });\n  useLayoutEffect(() => {\n    live.current = { options, spec };\n  });\n\n  const warn = useCallback(\n    (kind: string, message: string) => {\n      const core = getCore();\n      if (!isDev() || core.warned.has(kind)) return;\n      core.warned.add(kind);\n      console.warn(`[data-grid-server] ${message}`);\n    },\n    [getCore],\n  );\n  const blockSize = useCallback(() => positiveInteger(live.current.options.blockSize, DEFAULT_BLOCK_SIZE, 1), []);\n  const overscanOf = useCallback(() => positiveInteger(live.current.options.overscan, DEFAULT_OVERSCAN, 0), []);\n  const limits = useCallback((): FetchLimits => {\n    const read = readFetchLimits(blockSize(), live.current.options);\n    if (read.maxLoadedRowsInvalid) warn(\"maxLoadedRows\", `maxLoadedRows must be a number of rows or Infinity, so the hook uses ${DEFAULT_MAX_LOADED_ROWS}`);\n    return read;\n  }, [blockSize, warn]);\n  const seeding = useRef(false);\n  const notifyLoaded = useCallback((start: number, end: number) => {\n    if (seeding.current) return;\n    const onLoaded = live.current.options.onLoaded;\n    if (end > start && onLoaded) isolate(\"onLoaded\", () => onLoaded({ start, end }));\n  }, []);\n\n  const release = useCallback(\n    (core: Core<TData>) => {\n      forgetDisplacedWhenIdle(core, protectedRows());\n      pruneSaves(oldestMark(core));\n      if (oldestMark(core) === null) {\n        pruneIds(core.deleted, savingRows());\n        pruneIds(core.absent, savingRows());\n      }\n    },\n    [pruneSaves, protectedRows, savingRows],\n  );\n\n  const protectedFromEviction = useCallback((): ProtectedRows => {\n    const mark = oldestMark(getCore());\n    return unionIds(evictionProtected(), mark === null ? null : savedSince(mark));\n  }, [getCore, evictionProtected, savedSince]);\n\n  const commit = useCallback(() => {\n    const core = getCore();\n    const pending = core.pending.splice(0);\n    if (pending.length === 0) return;\n    const batch = pending.map(({ start, rows, guard, mark }) => ({ start, rows: overlayPushed(rows, mark, start, live.current.options.getRowId as (row: TData | undefined, index: number) => string), guard: unionIds(guard, savedSince(mark)) }));\n    const final = pending[pending.length - 1]!.final === true || core.inFlight.size === 0;\n    const displaced = core.displaced;\n    const memory = { orphans: core.orphans, carried: core.carried };\n    const length = core.kind === \"sequence\" ? core.rowsLength : null;\n    const guarded = protectedRows();\n    // A sequential refresh shrinks `loaded` at its end, before the commit, so it scans the whole dense array.\n    const ranges = core.kind === \"sequence\" ? [{ start: 0, end: Number.MAX_SAFE_INTEGER }] : core.stale.length > 0 ? mergeRanges([...core.loaded, ...core.stale]) : core.loaded;\n    const idOf = live.current.options.getRowId;\n    const unacknowledged = unacknowledgedWithoutSave(unacknowledgedRows(), savingRows());\n    if (unacknowledged !== null) {\n      for (const { start, rows, guard } of batch) {\n        const guardedHere = unionIds(guard, guarded);\n        rows.forEach((row, index) => {\n          if (row === undefined) return;\n          const id = idOf(row, start + index);\n          if (unacknowledged.has(id) && !guardedHere?.has(id)) acknowledge(id);\n        });\n      }\n    }\n    const size = blockSize();\n    const cap = limits().maxLoadedRows;\n    const loadedNow = core.stale.length > 0 ? mergeRanges([...core.loaded, ...core.stale]) : core.loaded;\n    const keep = core.keep;\n    const evicting = core.kind === \"random\" && keep !== null && Number.isFinite(cap) && sumRangeSizes(loadedNow) > cap;\n    const sequentialEvicting = core.kind === \"sequence\" && !core.seq.refresh && keep !== null && Number.isFinite(cap) && sumRangeSizes(core.loaded) > cap;\n    const wasEvicted = sequentialEvicting ? core.seq.blocks.map((block) => block.evicted) : [];\n    const loadedTotal = sumRangeSizes(core.loaded);\n    setRows((prev) => {\n      const base = length === null ? prev : Object.assign(prev.slice(), { length });\n      const written = writeBlocks(base, batch, guarded, displaced, ranges, idOf, memory, final);\n      for (const slot of written.cleared) core.cleared.add(slot);\n      for (const slot of written.restored) core.restored.add(slot);\n      if (sequentialEvicting) return evictSequenceRows(core, written.rows, { wasEvicted, loadedTotal, keep, cap, protectedIds: protectedFromEviction(), idOf });\n      return evicting ? evictRows(core, written.rows, { loaded: loadedNow, keep, size, cap, protectedIds: protectedFromEviction(), idOf }) : written.rows;\n    });\n  }, [getCore, protectedRows, savingRows, savedSince, overlayPushed, unacknowledgedRows, acknowledge, blockSize, limits, protectedFromEviction]);\n\n  const unloadSlots = useCallback(\n    (ranges: readonly RowRange[], reportAfter = false) => {\n      const core = getCore();\n      core.empty = core.empty.flatMap((empty) => subtractRanges(empty, ranges));\n      const held = mergeRanges([...core.loaded, ...core.stale]);\n      const targets = ranges.flatMap((range) => held.map((slice) => ({ start: Math.max(range.start, slice.start), end: Math.min(range.end, slice.end) })).filter((overlap) => overlap.end > overlap.start));\n      if (targets.length === 0) return;\n      const idOf = live.current.options.getRowId;\n      setRows((prev) => {\n        const unloaded = unloadRows(prev, targets, protectedFromEviction(), idOf);\n        forgetUnloaded(core, unloaded.cleared, unloaded.kept);\n        if (reportAfter) core.reportAfterUnload = true;\n        return unloaded.rows;\n      });\n    },\n    [getCore, protectedFromEviction],\n  );\n\n  // The first landing commits at once; later ones wait for the next frame, so a burst costs one copy of the rows per frame.\n  const commitSoon = useCallback(\n    () =>\n      commitOnFrame(getCore(), commit, () => {\n        const core = getCore();\n        release(core);\n        setLoading(busy(core));\n      }),\n    [getCore, commit, release],\n  );\n\n  const abortRequests = useCallback(() => {\n    const core = getCore();\n    for (const { controller } of core.inFlight.values()) controller.abort();\n    core.inFlight.clear();\n  }, [getCore]);\n\n  const dropBlocks = useCallback(\n    (size: number) => {\n      const core = getCore();\n      const hadRows = core.loaded.length > 0 || core.stale.length > 0 || core.pending.length > 0;\n      abortRequests();\n      resetQueues(core);\n      core.viewed.clear();\n      core.keep = null;\n      core.evictedBlocks.clear();\n      core.kind = \"unknown\";\n      core.seq = freshSequence();\n      setSkeletons(null);\n      core.loaded = [];\n      core.failed.clear();\n      core.pending.length = 0;\n      pruneSaves(null);\n      forgetStructural();\n      core.cancelQueuedRefresh?.();\n      core.cancelQueuedRefresh = null;\n      core.displaced = new Map();\n      core.stale = [];\n      core.empty = [];\n      core.absent = new Set(savingRows() ?? []);\n      core.cleared.clear();\n      core.cancelFrame?.();\n      core.cancelFrame = null;\n      if (core.rowsLength !== size || hadRows) setRows(new Array<TData | undefined>(size));\n      core.rowsLength = size;\n      setLoadedCount(0);\n    },\n    [getCore, abortRequests, pruneSaves, savingRows, forgetStructural],\n  );\n\n  const windowRef = useRef<(range: RowRange) => void>(noop);\n\n  const runFetchRef = useRef<(range: RowRange, cursor?: unknown) => void>(noop);\n  const pumpRef = useRef<() => void>(noop);\n\n  const landSequence = useCallback(\n    (range: RowRange, read: ReadAnswer<TData, unknown>, sentCursor: unknown, guard: Guard) => {\n      const core = getCore();\n      const seq = core.seq;\n      const size = blockSize();\n      core.ready = true;\n      core.kind = \"sequence\";\n      if (typeof read.totalRowCount === \"number\") seq.sentCount = read.totalRowCount;\n      else if (read.totalRowCount === null) seq.sentCount = null;\n      const refresh = seq.refresh;\n      const at = refresh ? refresh.local : seq.length;\n      const idOf = live.current.options.getRowId;\n      const serverLength = Math.min(read.rows.length, range.end - range.start);\n      const guarded = refresh ? null : unionIds(unionIds(guard.ids, savedSince(guard.mark)), protectedRows());\n      const incoming: TData[] = [];\n      read.rows.slice(0, serverLength).forEach((row, index) => {\n        if (row === undefined) return;\n        const id = idOf(row, range.start + index);\n        if (core.deleted.has(id)) return;\n        if (guarded !== null && guarded.has(id) && !core.absent.has(id) && !core.displaced.has(id)) return;\n        incoming.push(row);\n      });\n      if (core.absent.size > 0) read.rows.forEach((row, index) => row !== undefined && core.absent.delete(idOf(row, range.start + index)));\n      const written = incoming.length;\n      const position = at + written;\n      const serverPosition = range.start + serverLength;\n      const step = stepSequence({ read, sentCursor, loaded: serverPosition, count: seq.sentCount, seenCursors: seq.seen });\n      if (step.warning) warn(step.warning.kind, step.warning.message);\n      for (const [key, failure] of core.failed) {\n        if (failure.range.start === range.start) core.failed.delete(key);\n      }\n      if (core.failed.size === 0) setError(null);\n      seq.cursor = step.cursor;\n      const returned = cursorKey(step.cursor);\n      if (returned !== null && seq.seen.size < MAX_SEEN_CURSORS) seq.seen.add(returned);\n      core.pending.push({ start: at, rows: incoming, guard: guard.ids, mark: guard.mark });\n      if (written > 0) seq.blocks.push({ local: at, length: written, server: range.start, serverEnd: range.end, cursor: sentCursor, evicted: false });\n      if (refresh && !step.ended && position < refresh.keepUntil) {\n        core.rowsLength = Math.max(core.rowsLength, position);\n        commitSoon();\n        notifyLoaded(at, position);\n        refresh.local = position;\n        runFetchRef.current({ start: serverPosition, end: serverPosition + size }, step.cursor);\n        return;\n      }\n      seq.refresh = null;\n      seq.ended = step.ended;\n      seq.length = position;\n      seq.offset = serverPosition;\n      core.loaded = sequenceLoaded(position, seq.blocks);\n      const tail = skeletonCount({ loaded: serverPosition, blockSize: size, count: seq.sentCount, ended: step.ended });\n      if (refresh) core.pending.push({ start: position, rows: new Array<TData | undefined>(tail).fill(undefined), guard: null, mark: guard.mark });\n      core.rowsLength = position + tail;\n      setLoadedCount(sumRangeSizes(core.loaded));\n      setSkeletons(tail);\n      setCount(seq.sentCount ?? (step.ended ? position : null));\n      commitSoon();\n      notifyLoaded(at, position);\n    },\n    [getCore, warn, commitSoon, blockSize, notifyLoaded, protectedRows, savedSince],\n  );\n\n  const landReload = useCallback(\n    (range: RowRange, read: ReadAnswer<TData, unknown>, guard: Guard): boolean => {\n      const core = getCore();\n      const block = core.seq.blocks.find((candidate) => candidate.evicted && candidate.server === range.start);\n      if (!block) return false;\n      const idOf = live.current.options.getRowId;\n      const guarded = unionIds(unionIds(guard.ids, savedSince(guard.mark)), protectedRows());\n      const rows = new Array<TData | undefined>(block.length);\n      read.rows.slice(0, block.length).forEach((row, index) => {\n        const id = row === undefined ? undefined : idOf(row, range.start + index);\n        if (id !== undefined && !core.deleted.has(id) && !guarded?.has(id)) rows[index] = row;\n      });\n      block.evicted = false;\n      core.loaded = sequenceLoaded(core.seq.length, core.seq.blocks);\n      core.pending.push({ start: block.local, rows, guard: guard.ids, mark: guard.mark });\n      setLoadedCount(sumRangeSizes(core.loaded));\n      commitSoon();\n      notifyLoaded(block.local, block.local + block.length);\n      return true;\n    },\n    [getCore, commitSoon, notifyLoaded, protectedRows, savedSince],\n  );\n\n  const land = useCallback(\n    (range: RowRange, answer: unknown, sentCursor: unknown, guard: Guard) => {\n      const core = getCore();\n      const read = readAnswer<TData, unknown>(answer, range, warn, live.current.options.getRowId);\n      if (core.kind === \"unknown\") {\n        const declared = live.current.options.source;\n        core.kind = declared === \"sequential\" ? \"sequence\" : declared === \"random\" ? \"random\" : startsSequence(read) ? \"sequence\" : \"random\";\n      }\n      if (core.kind === \"sequence\") {\n        if (!landReload(range, read, guard)) landSequence(range, read, sentCursor, guard);\n        return;\n      }\n      if (live.current.options.source === \"random\" && typeof read.totalRowCount !== \"number\") {\n        warn(\"random-count\", 'source is \"random\" but fetchRows answered without a totalRowCount; the rows end at this block. Answer the count with every block');\n      }\n      const first = !core.ready;\n      const nextCount = typeof read.totalRowCount === \"number\" ? read.totalRowCount : (core.count ?? range.start + read.rows.length);\n      const refire = first || nextCount !== core.count;\n      let keep: { displaced: Map<string, TData>; orphans: Map<string, { row: TData; slot: number }>; guarded: ProtectedRows; ranges: RowRange[] } | null = null;\n      if (!first && nextCount !== core.count) {\n        abortRequestsExcept(core, range);\n        resetQueues(core);\n        core.viewed.clear();\n        core.keep = null;\n        keep = { displaced: new Map(), orphans: core.orphans, guarded: unionIds(unionIds(guard.ids, savedSince(guard.mark)), protectedRows()), ranges: mergeRanges([...core.loaded, ...core.stale]) };\n        core.loaded = [];\n        core.failed.clear();\n        core.pending.length = 0;\n        forgetStructural();\n        core.cancelQueuedRefresh?.();\n        core.cancelQueuedRefresh = null;\n        core.displaced = keep.displaced;\n        core.stale = [];\n        core.empty = [];\n        core.cleared.clear();\n        core.cancelFrame?.();\n        core.cancelFrame = null;\n      }\n      if (first) core.ready = true;\n      if (core.rowsLength !== nextCount || (!first && nextCount !== core.count)) {\n        const idOf = live.current.options.getRowId;\n        setRows((prev) => {\n          if (keep !== null && keep.guarded !== null) stashGuardedRows(prev, keep.ranges, keep.guarded, keep.displaced, idOf, keep.orphans);\n          return new Array<TData | undefined>(nextCount);\n        });\n        core.rowsLength = nextCount;\n      } else {\n        setRows((prev) => (prev.length === nextCount ? prev : Object.assign(prev.slice(0, nextCount), { length: nextCount })));\n      }\n      core.count = nextCount;\n      setCount(nextCount);\n      if (refire) setLoadedCount(0);\n\n      const expected = Math.min(range.end, nextCount) - range.start;\n      const written = Math.max(0, Math.min(read.rows.length, expected));\n      if (read.rows.length < expected) {\n        warn(\"short\", `fetchRows returned ${read.rows.length} rows for rows [${range.start}, ${Math.min(range.end, nextCount)}); only those rows count as loaded and the rest stay unloaded`);\n      }\n      for (const [key, failure] of core.failed) {\n        if (failure.range.start < range.start + written && range.start < failure.range.end) core.failed.delete(key);\n      }\n      if (core.failed.size === 0) setError(null);\n      if (written > 0) {\n        const idOf = live.current.options.getRowId;\n        const blank: RowRange[] = [];\n        const rows = read.rows.slice(0, written).map((row, index) => {\n          if (row !== undefined && !core.deleted.has(idOf(row, range.start + index))) return row;\n          blank.push({ start: range.start + index, end: range.start + index + 1 });\n          return undefined;\n        });\n        const answered = { start: range.start, end: range.start + written };\n        core.loaded = mergeRanges([...core.loaded, ...subtractRanges(answered, blank)]);\n        core.empty = mergeRanges([...core.empty.flatMap((empty) => subtractRanges(empty, [answered])), ...blank]);\n        core.stale = core.stale.flatMap((stale) => subtractRanges(stale, [answered]));\n        setLoadedCount(sumRangeSizes(core.loaded));\n        stampLanded(core, range.start, written, blockSize(), limits().maxLoadedRows);\n        core.pending.push({ start: range.start, rows, guard: guard.ids, mark: guard.mark, final: core.inFlight.size <= 1 });\n        commitSoon();\n        notifyLoaded(range.start, range.start + written);\n      }\n      if (refire && core.lastWindow) windowRef.current(core.lastWindow);\n    },\n    [getCore, warn, commitSoon, landSequence, landReload, notifyLoaded, protectedRows, savedSince, forgetStructural, blockSize, limits],\n  );\n\n  const runFetch = useCallback(\n    (range: RowRange, cursor?: unknown) => {\n      const core = getCore();\n      const key = rangeKey(range);\n      if (core.inFlight.has(key)) return;\n      const controller = new AbortController();\n      const guard: Guard = { ids: savingRows(), mark: saveMark() };\n      core.inFlight.set(key, { range, controller, guard, landed: false });\n      setLoading(true);\n      const settle = () => {\n        if (core.inFlight.get(key)?.controller !== controller) return;\n        core.inFlight.delete(key);\n        release(core);\n        // Rows still waiting for the next frame count as loading, so \"ready\" means the rows are on screen.\n        setLoading(busy(core));\n        pumpRef.current();\n        if (core.inFlight.size === 0 && core.owed.length === 0 && !core.seq.refresh) core.reason = \"load\";\n      };\n      const fail = (cause: unknown) => {\n        if (controller.signal.aborted) return;\n        const failure = cause ?? new Error(\"fetchRows rejected\");\n        core.failed.set(key, { range, cursor, error: failure });\n        setError(failure);\n        const onError = live.current.options.onError;\n        if (onError) isolate(\"onError\", () => onError(failure));\n      };\n      const request = { spec: live.current.spec, start: range.start, end: range.end, cursor, reason: core.reason, signal: controller.signal } as ServerRowsRequest<TCursor>;\n      let landed = false;\n      // A landed sequential block re-checks the rendered window once its request has settled, so the chain goes on while the window stays near the end.\n      const afterSettle = () => {\n        settle();\n        if (landed && !controller.signal.aborted && core.kind === \"sequence\" && core.lastWindow) windowRef.current(core.lastWindow);\n      };\n      try {\n        live.current.options\n          .fetchRows(request)\n          .then((answer) => {\n            if (controller.signal.aborted) return;\n            const entry = core.inFlight.get(key);\n            if (entry?.controller === controller) entry.landed = true;\n            land(range, answer, cursor, guard);\n            landed = true;\n          })\n          .catch(fail)\n          .finally(afterSettle);\n      } catch (cause) {\n        fail(cause);\n        settle();\n      }\n    },\n    [getCore, land, savingRows, saveMark, release],\n  );\n  useLayoutEffect(() => {\n    runFetchRef.current = runFetch;\n  }, [runFetch]);\n\n  const startDueBlocks = useCallback(() => {\n    const core = getCore();\n    if (core.delayTimer !== null) clearTimeout(core.delayTimer);\n    core.delayTimer = null;\n    if (!core.ready) return;\n    const size = blockSize();\n    const { loadDelayMs, maxConcurrentFetches } = limits();\n    const centre = core.lastWindow ? (core.lastWindow.start + core.lastWindow.end) / 2 : 0;\n    const armTimer = (nextAt: number | null) => {\n      if (nextAt === null) return;\n      core.delayTimer = setTimeout(() => {\n        core.delayTimer = null;\n        pumpRef.current();\n      }, Math.max(0, nextAt - Date.now()));\n    };\n    if (core.kind === \"sequence\") {\n      const { seq } = core;\n      const reloads = dueWanted(core.reloads, { now: Date.now(), delay: loadDelayMs, centre, limit: maxConcurrentFetches - core.inFlight.size });\n      for (const { start } of reloads.due) {\n        core.reloads.delete(start);\n        const block = seq.blocks.find((candidate) => candidate.evicted && candidate.server === start);\n        if (block) runFetch({ start, end: block.serverEnd }, block.cursor);\n      }\n      if (seq.ended || seq.refresh || core.inFlight.size > 0 || !core.lastWindow || !needsNextBlock(core.lastWindow, seq.length, overscanOf())) {\n        core.wanted.clear();\n        armTimer(reloads.nextAt);\n        return;\n      }\n      const { due, nextAt } = dueWanted(core.wanted, { now: Date.now(), delay: loadDelayMs, centre, limit: 1 });\n      if (due.length > 0) {\n        core.wanted.clear();\n        runFetch({ start: seq.offset, end: seq.offset + size }, seq.cursor);\n      } else armTimer(nextAt === null || (reloads.nextAt !== null && reloads.nextAt < nextAt) ? reloads.nextAt : nextAt);\n      return;\n    }\n    if (core.kind !== \"random\" || core.count === null) return;\n    while (core.inFlight.size < maxConcurrentFetches && core.owed.length > 0) {\n      let nearest = 0;\n      core.owed.forEach((block, index) => {\n        if (distanceToCentre(block, centre) < distanceToCentre(core.owed[nearest]!, centre)) nearest = index;\n      });\n      runFetch(core.owed.splice(nearest, 1)[0]!);\n    }\n    if (core.owed.length > 0) return;\n    const free = maxConcurrentFetches - core.inFlight.size;\n    const { due } = dueWanted(core.wanted, { now: Date.now(), delay: loadDelayMs, centre, limit: free });\n    for (const block of due) {\n      core.wanted.delete(block.start);\n      runFetch(block);\n    }\n    armTimer(dueWanted(core.wanted, { now: Date.now(), delay: loadDelayMs, centre, limit: 0 }).nextAt);\n  }, [getCore, blockSize, limits, overscanOf, runFetch]);\n\n  const pump = useCallback(() => runPumps(getCore(), startDueBlocks), [getCore, startDueBlocks]);\n  useLayoutEffect(() => {\n    pumpRef.current = pump;\n  }, [pump]);\n\n  const leaveKeepRange = useCallback(\n    (keep: RowRange) => {\n      const core = getCore();\n      const left: RowRange[] = [];\n      for (const [key, entry] of core.inFlight) {\n        if (entry.landed || rangesIntersect(entry.range, keep)) continue;\n        entry.controller.abort();\n        core.inFlight.delete(key);\n        left.push(entry.range);\n      }\n      const owedInside = core.owed.filter((block) => rangesIntersect(block, keep));\n      left.push(...core.owed.filter((block) => !owedInside.includes(block)));\n      core.owed = owedInside;\n      let forgotten = false;\n      for (const [key, failure] of core.failed) {\n        if (rangesIntersect(failure.range, keep)) continue;\n        core.failed.delete(key);\n        forgotten = true;\n      }\n      if (forgotten && core.failed.size === 0) setError(null);\n      if (left.length === 0) return;\n      setLoading(busy(core));\n      unloadSlots(left, true);\n    },\n    [getCore, unloadSlots],\n  );\n\n  // `immediate` skips the load delay: the user did not move for it.\n  const reportRange = useCallback(\n    (range: RowRange, immediate: boolean) => {\n      const core = getCore();\n      core.lastWindow = range;\n      if (core.ready && core.kind === \"sequence\") {\n        const { seq } = core;\n        if (!seq.ended && !seq.refresh && core.inFlight.size === 0 && needsNextBlock(range, seq.length, overscanOf())) {\n          const { loadDelayMs } = limits();\n          trackWanted(core.wanted, [{ start: seq.offset, end: seq.offset + blockSize() }], immediate ? Date.now() - loadDelayMs : Date.now());\n        } else core.wanted.clear();\n        const size = blockSize();\n        const wantedRange = expandRange(range, { overscan: overscanOf(), blockSize: size, total: seq.length });\n        core.keep = keepRange(wantedRange, size, seq.length);\n        const reloads = seq.refresh ? [] : evictedBlocksIn(seq.blocks, wantedRange).map((block) => ({ start: block.server, end: block.serverEnd }));\n        trackWanted(core.reloads, reloads, immediate ? Date.now() - limits().loadDelayMs : Date.now());\n        pump();\n        return;\n      }\n      if (!core.ready || core.count === null) return;\n      const size = blockSize();\n      const wantedRange = expandRange(range, { overscan: overscanOf(), blockSize: size, total: core.count });\n      if (rangeSize(wantedRange) === 0) return;\n      const { loadDelayMs, maxLoadedRows } = limits();\n      const keep = keepRange(wantedRange, size, core.count);\n      core.keep = keep;\n      if (Number.isFinite(maxLoadedRows)) stampViewed(core, keep, size, maxLoadedRows);\n      leaveKeepRange(keep);\n      const covered = [...core.loaded, ...core.empty, ...Array.from(core.inFlight.values(), (entry) => entry.range), ...core.owed];\n      const uncovered = subtractRanges(wantedRange, covered).flatMap((gap) => chunkAligned(gap, size));\n      trackWanted(core.wanted, uncovered, immediate ? Date.now() - loadDelayMs : Date.now());\n      pump();\n    },\n    [getCore, overscanOf, blockSize, limits, leaveKeepRange, pump],\n  );\n  const onRenderedRowsChange = useCallback(\n    (range: RowRange) => {\n      reportRange(range, false);\n      isolate(\"onRenderedRowsChange\", () => live.current.options.onRenderedRowsChange?.(range));\n    },\n    [reportRange],\n  );\n  useLayoutEffect(() => {\n    windowRef.current = (range) => reportRange(range, true);\n  }, [reportRange]);\n\n  const specKey = serverSpecKey(spec);\n  useLayoutEffect(() => {\n    if (!specReady) return;\n    const core = getCore();\n    const wasSequence = core.kind === \"sequence\";\n    dropBlocks(wasSequence ? 0 : (core.count ?? 0));\n    if (wasSequence) {\n      core.count = null;\n      setCount(null);\n    }\n    core.ready = false;\n    setError(null);\n    const seeded = seedRef.current;\n    if (seeded !== null && seeded.specKey !== specKey) seedRef.current = null;\n    if (seedRef.current !== null) {\n      const { answer, cut } = seedRef.current;\n      if (cut) warn(\"seed-long\", `initialAnswer holds more than blockSize (${blockSize()}) rows; only the first block is used`);\n      seeding.current = true;\n      land({ start: 0, end: blockSize() }, answer, undefined, { ids: savingRows(), mark: saveMark() });\n      seeding.current = false;\n      return () => {\n        resetQueues(core);\n        abortRequests();\n        core.cancelFrame?.();\n        core.cancelFrame = null;\n      };\n    }\n    setLoading(true);\n    // The first request waits a tick, so a StrictMode remount and a spec restored in a mount effect replace it before it leaves.\n    const timer = setTimeout(() => runFetch({ start: 0, end: blockSize() }), 0);\n    return () => {\n      clearTimeout(timer);\n      resetQueues(core);\n      abortRequests();\n      core.cancelFrame?.();\n      core.cancelFrame = null;\n    };\n    // `specKey` stands for the spec content.\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [specKey, specReady]);\n\n  const evictRange = useCallback(\n    (range: RowRange) => {\n      const core = getCore();\n      if (core.kind === \"sequence\") return;\n      const target = { start: Math.max(0, range.start), end: Math.min(core.count ?? 0, range.end) };\n      if (target.end <= target.start) return;\n      commit();\n      let aborted = false;\n      for (const [key, entry] of core.inFlight) {\n        if (!rangesIntersect(entry.range, target)) continue;\n        entry.controller.abort();\n        core.inFlight.delete(key);\n        aborted = true;\n      }\n      core.owed = core.owed.filter((block) => !rangesIntersect(block, target));\n      if (aborted) {\n        setLoading(busy(core));\n        pumpRef.current();\n      }\n      unloadSlots([target]);\n    },\n    [getCore, commit, unloadSlots],\n  );\n  const evict = evictRange;\n\n  const retry = useCallback(() => {\n    const core = getCore();\n    if (core.failed.size === 0) return;\n    const failures = Array.from(core.failed.values());\n    core.failed.clear();\n    core.reason = \"retry\";\n    setError(null);\n    if (core.kind === \"random\" && core.ready) {\n      for (const { range } of failures) if (!core.owed.some((block) => rangeKey(block) === rangeKey(range))) core.owed.push(range);\n      setLoading(true);\n      pumpRef.current();\n      return;\n    }\n    for (const { range, cursor } of failures) runFetch(range, cursor);\n  }, [getCore, runFetch]);\n\n  // A protected row that left its old slot must not leave the slot marked loaded; the next window fetches it again.\n  useLayoutEffect(() => {\n    const core = getCore();\n    if (core.unloaded) {\n      core.unloaded = false;\n      for (const index of core.evictedBlocks) core.viewed.delete(index);\n      core.evictedBlocks.clear();\n      setLoadedCount(sumRangeSizes(core.loaded));\n      if (core.reportAfterUnload) {\n        core.reportAfterUnload = false;\n        if (core.lastWindow) windowRef.current(core.lastWindow);\n      }\n    }\n    if (core.restored.size > 0) {\n      core.stale = mergeRanges([...core.stale, ...Array.from(core.restored, (slot) => ({ start: slot, end: slot + 1 }))]);\n      core.restored.clear();\n    }\n    if (core.cleared.size === 0) return;\n    const slots = Array.from(core.cleared);\n    core.cleared.clear();\n    if (core.kind === \"sequence\") return;\n    core.loaded = mergeRanges(slots.reduce<RowRange[]>((kept, slot) => kept.flatMap((range) => subtractRanges(range, [{ start: slot, end: slot + 1 }])), core.loaded));\n    setLoadedCount(sumRangeSizes(core.loaded));\n    if (core.lastWindow) windowRef.current(core.lastWindow);\n  }, [rows, getCore]);\n\n  const restartClockRef = useRef<() => void>(noop);\n  const refreshRef = useRef<(reason: FetchReason) => void>(noop);\n  const canRevalidate = useCallback(() => {\n    const core = getCore();\n    if (core.kind !== \"sequence\") return true;\n    const size = blockSize();\n    return Math.ceil(Math.max(size, (core.lastWindow?.end ?? 0) + overscanOf()) / size) <= MAX_SEQUENTIAL_REVALIDATE_BLOCKS;\n  }, [getCore, blockSize, overscanOf]);\n  const canRunTimed = useCallback(() => {\n    const ok = canRevalidate();\n    if (!ok) warn(\"revalidate-skipped\", \"a timed refresh was skipped because the rendered rows of a sequential source end beyond 10 blocks; call refresh() yourself, and read canRevalidate() to know when it applies\");\n    return ok;\n  }, [canRevalidate, warn]);\n  const { request: requestReshape, cancel: cancelReshape } = useReshape({ delay: options.reshapeDelayMs, ordered: spec.sorts.length + spec.filters.length > 0, run: () => refreshRef.current(\"refresh\"), busy: loading, canRun: canRunTimed, resetKey: specKey, warn });\n  const reshape = useCallback(() => requestReshape(\"soon\"), [requestReshape]);\n  useEffect(() => {\n    setReshapeListener(requestReshape);\n    return () => setReshapeListener(null);\n  }, [setReshapeListener, requestReshape]);\n  const refreshFor = useCallback((reason: FetchReason) => {\n    cancelReshape();\n    restartClockRef.current();\n    const core = getCore();\n    core.reason = reason;\n    if (!core.ready || (core.kind !== \"sequence\" && core.count === null)) {\n      core.failed.clear();\n      setError(null);\n      runFetch({ start: 0, end: blockSize() });\n      return;\n    }\n    commit();\n    const size = blockSize();\n    if (core.kind === \"sequence\") {\n      abortRequests();\n      resetQueues(core);\n      core.failed.clear();\n      setError(null);\n      core.seq.seen = new Set();\n      core.seq.blocks = [];\n      core.seq.refresh = { keepUntil: Math.max(size, (core.lastWindow?.end ?? 0) + overscanOf()), local: 0 };\n      runFetch({ start: 0, end: size });\n      return;\n    }\n    const keep = core.lastWindow ? expandRange(core.lastWindow, { overscan: overscanOf(), blockSize: size, total: core.count! }) : { start: 0, end: Math.min(size, core.count!) };\n    abortRequests();\n    resetQueues(core);\n    core.failed.clear();\n    core.empty = [];\n    setError(null);\n    for (const outside of subtractRanges({ start: 0, end: core.count! }, [keep])) evictRange(outside);\n    core.owed = chunkRange(keep, size);\n    setLoading(core.owed.length > 0);\n    pumpRef.current();\n  }, [getCore, runFetch, evictRange, abortRequests, blockSize, overscanOf, commit, cancelReshape]);\n  const refresh = useCallback(() => refreshFor(\"refresh\"), [refreshFor]);\n\n  useLayoutEffect(() => {\n    refreshRef.current = refreshFor;\n  }, [refreshFor]);\n\n  const restartClock = useRevalidation({ interval: options.revalidateIntervalMs, onTick: () => refreshRef.current(\"refresh\"), busy: loading, canTick: canRunTimed, resetKey: specKey });\n  useLayoutEffect(() => {\n    restartClockRef.current = restartClock;\n  }, [restartClock]);\n\n  useEffect(() => {\n    const core = getCore();\n    setSettleListener(() => {\n      if (core.kind !== \"sequence\" && live.current.options.refreshAfterSave !== false) refreshRef.current(\"save\");\n    });\n    return () => {\n      setSettleListener(null);\n      core.cancelQueuedRefresh?.();\n      core.cancelQueuedRefresh = null;\n    };\n  }, [getCore, setSettleListener]);\n\n  const getLoadedRanges = useCallback(() => getCore().loaded.slice(), [getCore]);\n\n  const getRowId = useCallback((row: TData, index: number) => (row === undefined ? holeRowId(index) : live.current.options.getRowId(row, index)), []);\n\n  // An insert or delete moves the end of the loaded rows; the next block starts after it.\n  const followRowOperations = useCallback(\n    (change: DataChange<TData>) => {\n      const core = getCore();\n      const { seq } = core;\n      let delta = 0;\n      for (const op of change.ops) {\n        if (op.type === \"insert\" || op.type === \"delete\") seq.blocks = shiftBlocks(seq.blocks, op.index, op.type === \"insert\" ? 1 : -1);\n        delta += op.type === \"insert\" ? 1 : op.type === \"delete\" ? -1 : 0;\n      }\n      if (delta === 0) return;\n      seq.length = Math.max(0, seq.length + delta);\n      seq.offset = Math.max(0, seq.offset + delta);\n      core.rowsLength = Math.max(0, core.rowsLength + delta);\n      core.loaded = sequenceLoaded(seq.length, seq.blocks);\n      setLoadedCount(sumRangeSizes(core.loaded));\n      if (seq.ended && seq.sentCount === null) setCount(seq.length);\n    },\n    [getCore],\n  );\n\n  const handledChanges = useRef(new WeakSet<object>());\n  const onDataChange = useCallback(\n    (next: readonly TData[], change: DataChange<TData>) => {\n      if (handledChanges.current.has(change)) return;\n      handledChanges.current.add(change);\n      const core = getCore();\n      commit();\n      // `next` is the grid's snapshot and can predate rows a landed block wrote; replaying the operations on the latest rows keeps them.\n      setRows((prev) => {\n        if (isDev() && !core.warned.has(\"dropped\")) warnDroppedEdit(prev, change, live.current.options.getRowId, warn);\n        return change.ops.length > 0 ? (applyChangeWith(prev as TData[], change, getRowId, { rowOfUpdate: streamUpdateRow(change) }) as (TData | undefined)[]) : (next.slice() as (TData | undefined)[]);\n      });\n      if (core.kind === \"sequence\") followRowOperations(change);\n      trackDeletes(core.deleted, change);\n      if (core.kind !== \"sequence\" && core.ready && change.ops.some((op) => op.type !== \"update\")) {\n        // A local insert, delete, or move shifts rows away from the positions the loaded ranges name; the refresh loads the rendered ones again.\n        const inserted = change.ops.filter((op) => op.type === \"insert\").length;\n        core.stale = mergeRanges([...core.stale, ...core.loaded].map((range) => ({ start: range.start, end: range.end + inserted })));\n        core.loaded = [];\n        setLoadedCount(0);\n        // A burst of row operations refreshes once, on the next frame. A push goes through the reshape rule instead.\n        if (change.source === \"stream\") requestReshape(\"soon\");\n        else if (core.cancelQueuedRefresh === null) {\n          core.cancelQueuedRefresh = scheduleFrame(() => {\n            core.cancelQueuedRefresh = null;\n            refreshRef.current(\"refresh\");\n          });\n        }\n      } else if (core.kind === \"sequence\" && change.source === \"stream\" && change.ops.some((op) => op.type !== \"update\")) {\n        requestReshape(\"soon\");\n      }\n      const onDataChange = live.current.options.onDataChange;\n      if (onDataChange) isolate(\"onDataChange\", () => onDataChange(next, change));\n    },\n    [getCore, commit, getRowId, warn, followRowOperations, requestReshape, streamUpdateRow],\n  );\n\n  const refreshAfterSave = useCallback(() => {\n    if (canRunTimed()) refreshFor(\"save\");\n  }, [canRunTimed, refreshFor]);\n  const { onSave, wrapSave } = useSaveRefresh(options, refreshAfterSave);\n\n  const plugins = useMountedPlugins(guardPlugins, options.plugins);\n  const providerProps = useMemo<UseDataGridServerRowsScrollProviderProps<TData>>(\n    () => ({\n      data: rows as TData[],\n      getRowId,\n      onDataChange,\n      ...(onSave ? { onSave } : {}),\n      onRenderedRowsChange,\n      sortMode: \"server\",\n      filterMode: \"server\",\n      sortState: spec.sorts as SortSpec[],\n      onSortChange,\n      filterState: spec.filters as FilterNode[],\n      onFilterChange, onFilterJoinChange, filterJoin: spec.filterJoin ?? \"and\",\n      searchText: spec.searchText,\n      onSearchTextChange,\n      totalRowCount: count,\n      checkedRowsLifetime: \"across-filters\",\n      headerClickBehavior: \"sort\",\n      plugins,\n    }),\n    [rows, count, spec, getRowId, onDataChange, onSave, onRenderedRowsChange, onSortChange, onFilterChange, onFilterJoinChange, onSearchTextChange, plugins],\n  );\n  useRegisteredWiring(providerProps, wrapSave);\n  const rootProps = useMemo<UseDataGridServerRowsRootProps>(() => ({ loading, error, onRetry: retry }), [loading, error, retry]);\n  const gridProps = useMemo(() => ({ ...providerProps, ...rootProps }), [providerProps, rootProps]);\n\n  const status = error !== null ? \"error\" : loading ? \"loading\" : \"ready\";\n  const unloadedCount = skeletons ?? (count ?? 0) - loadedCount;\n  return { gridProps, providerProps, rootProps, spec, totalRowCount: count, status, loading, error, retry, refresh, reshape, canRevalidate, unloadedCount, getLoadedRanges, evict };\n}\n\nfunction noop() {}\n\n/** Unacknowledged rows that no save is pending for: a landed block replaces them, while a saving row keeps its local value. */\nfunction unacknowledgedWithoutSave(unacknowledged: ReadonlySet<string> | null, saving: ProtectedRows): ReadonlySet<string> | null {\n  if (unacknowledged === null || saving === null) return unacknowledged;\n  const rest = new Set<string>();\n  for (const id of unacknowledged) if (!saving.has(id)) rest.add(id);\n  return rest.size > 0 ? rest : null;\n}\n\n/** Runs `step` until no call asked for another pass; a call from inside `step` only asks. */\nfunction runPumps<TData>(core: Core<TData>, step: () => void) {\n  if (core.pumping) {\n    core.pumpAgain = true;\n    return;\n  }\n  core.pumping = true;\n  try {\n    do {\n      core.pumpAgain = false;\n      step();\n    } while (core.pumpAgain);\n  } finally {\n    core.pumping = false;\n  }\n}\n\nfunction abortRequestsExcept<TData>(core: Core<TData>, keep: RowRange) {\n  const keepKey = rangeKey(keep);\n  for (const [key, { controller }] of core.inFlight) {\n    if (key === keepKey) continue;\n    controller.abort();\n    core.inFlight.delete(key);\n  }\n}\n\nfunction warnDroppedEdit<TData>(prev: readonly (TData | undefined)[], change: DataChange<TData>, getRowId: (row: TData, index: number) => string, warn: (kind: string, message: string) => void) {\n  const missing = new Map<string, string>();\n  for (const op of change.ops) if (op.type !== \"insert\") missing.set(op.rowId, op.rowId);\n  if (missing.size === 0) return;\n  // `some` skips holes and stops once every edited row is found, so a normal edit scans only up to its rows.\n  prev.some((row, index) => {\n    if (row !== undefined) missing.delete(getRowId(row, index));\n    return missing.size === 0;\n  });\n  const dropped = missing.values().next();\n  if (!dropped.done) warn(\"dropped\", `an edit to row \"${dropped.value}\" was dropped because the row was evicted before the change merged; this hook does not own persistence, so keep the edit in your own cache`);\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/scroll-blocks.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/scroll-sequence.ts",
      "content": "import type { RowRange } from \"@/registry/default/components/data-grid/data-grid\";\nimport { MAX_ROW_COUNT, type ReadAnswer } from \"./read-answer\";\n\n/** Whether the first answer makes the source sequential: it carries a cursor, or it carries no count to size random access. */\nexport function startsSequence(read: Pick<ReadAnswer<unknown, unknown>, \"nextCursor\" | \"totalRowCount\">): boolean {\n  return read.nextCursor !== undefined || typeof read.totalRowCount !== \"number\";\n}\n\nconst MAX_CURSOR_KEY_LENGTH = 1024;\n/** Cursors a chain remembers; a longer chain stops recording and relies on the `Object.is` check. */\nexport const MAX_SEEN_CURSORS = 10_000;\n\n/** A stable key for comparing cursors by content; `null` for a cursor too large or not serializable to key. */\nexport function cursorKey(cursor: unknown): string | null {\n  if (cursor === null || cursor === undefined) return null;\n  if (typeof cursor !== \"object\") {\n    const key = `${typeof cursor}:${String(cursor)}`;\n    return key.length <= MAX_CURSOR_KEY_LENGTH ? key : null;\n  }\n  try {\n    const json = JSON.stringify(cursor);\n    return json !== undefined && json.length <= MAX_CURSOR_KEY_LENGTH ? `json:${json}` : null;\n  } catch {\n    return null;\n  }\n}\n\nexport type SequenceStep<TCursor> = {\n  ended: boolean;\n  /** The cursor the next block sends. */\n  cursor: TCursor | undefined;\n  warning: { kind: string; message: string } | null;\n};\n\ntype StepInput<TCursor> = {\n  read: ReadAnswer<unknown, TCursor>;\n  /** The cursor this block was requested with. */\n  sentCursor: TCursor | undefined;\n  /** Rows loaded once this block is written. */\n  loaded: number;\n  /** The count the server sent, if any. */\n  count: number | null;\n  /** Keys of the cursors this chain already returned. */\n  seenCursors?: ReadonlySet<string>;\n};\n\n/** Decides what a landed block means for the chain: does it go on, and with which cursor. */\nexport function stepSequence<TCursor>({ read, sentCursor, loaded, count, seenCursors }: StepInput<TCursor>): SequenceStep<TCursor> {\n  const cursor = read.nextCursor ?? undefined;\n  const end = (warning: SequenceStep<TCursor>[\"warning\"] = null): SequenceStep<TCursor> => ({ ended: true, cursor, warning });\n  if (read.rows.length === 0) {\n    const emptyWithCursor = read.nextCursor !== undefined && read.nextCursor !== null;\n    return end(emptyWithCursor ? { kind: \"empty\", message: \"fetchRows returned an empty block with a next cursor; an empty block ends the source, so return rows or a null cursor\" } : null);\n  }\n  if (read.nextCursor === null || read.hasMoreSent === false) return end();\n  if (read.nextCursor === undefined && !read.hasMore) return end();\n  if (read.nextCursor !== undefined && Object.is(read.nextCursor, sentCursor)) {\n    return end({ kind: \"cursor\", message: \"fetchRows answered the cursor it was sent; the source ends here, so return a new cursor or null\" });\n  }\n  const key = cursorKey(read.nextCursor);\n  if (key !== null && seenCursors?.has(key)) {\n    return end({ kind: \"cursor\", message: \"fetchRows returned a cursor it returned before; the source ends here, so return a new cursor or null\" });\n  }\n  if (count !== null && loaded >= count) return end();\n  if (loaded >= MAX_ROW_COUNT) return end({ kind: \"max\", message: `the source loaded ${MAX_ROW_COUNT} rows; it ends here` });\n  return { ended: false, cursor, warning: null };\n}\n\n/** Skeleton rows below the loaded rows: one block, cut to the rows the server still owes. */\nexport function skeletonCount({ loaded, blockSize, count, ended }: { loaded: number; blockSize: number; count: number | null; ended: boolean }): number {\n  if (ended) return 0;\n  const owed = count === null ? blockSize : Math.max(0, count - loaded);\n  return Math.min(blockSize, owed, Math.max(0, MAX_ROW_COUNT - loaded));\n}\n\n/** The next block starts when the rendered rows come within `overscan` of the loaded end. */\nexport function needsNextBlock(window: RowRange, loaded: number, overscan: number): boolean {\n  return window.end + overscan >= loaded;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/scroll-sequence.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/scroll-eviction.ts",
      "content": "import type { RowRange } from \"@/registry/default/components/data-grid/data-grid\";\nimport { pickEvictions, pruneViewed, unloadRangesOf } from \"./fetch-hygiene\";\nimport { mergeRanges, subtractRanges } from \"./range-math\";\nimport type { ProtectedRows } from \"./refresh-guard\";\nimport type { Core } from \"./scroll-core\";\n\nexport function stampViewed<TData>(core: Core<TData>, keep: RowRange, size: number, cap: number) {\n  const stamp = ++core.tick;\n  for (let index = Math.floor(keep.start / size); index * size < keep.end; index++) core.viewed.set(index, stamp);\n  if (core.viewed.size > Math.ceil(cap / size) * 2 + 256) pruneViewed(core.viewed, core.loaded, keep, size);\n}\n\nexport function stampLanded<TData>(core: Core<TData>, start: number, length: number, size: number, cap: number) {\n  if (!Number.isFinite(cap)) return;\n  for (let index = Math.floor(start / size); index * size < start + length; index++) if (!core.viewed.has(index)) core.viewed.set(index, core.tick);\n}\n\n/** Unloads the target slots of `prev` except protected rows; `cleared` lists the slots that were unloaded. Pure. */\nexport function unloadRows<TData>(prev: readonly (TData | undefined)[], targets: readonly RowRange[], protectedIds: ProtectedRows, idOf: (row: TData, index: number) => string): { rows: (TData | undefined)[]; cleared: RowRange[]; kept: RowRange[] } {\n  let next: (TData | undefined)[] | null = null;\n  const kept: RowRange[] = [];\n  for (const { start, end } of targets) {\n    for (let index = start; index < Math.min(end, prev.length); index++) {\n      const row = prev[index];\n      if (row === undefined) continue;\n      if (protectedIds?.has(idOf(row, index))) kept.push({ start: index, end: index + 1 });\n      else (next ??= prev.slice())[index] = undefined;\n    }\n  }\n  return { rows: next ?? (prev as (TData | undefined)[]), cleared: kept.length === 0 ? targets.slice() : targets.flatMap((target) => subtractRanges(target, kept)), kept };\n}\n\n/**\n * Removes unloaded slots from the ranges the hook claims. A kept slot (a protected row that stays) moves from `loaded` to `stale`,\n * so the next window fetches its block whole and the answer replaces or moves the row. Idempotent: a StrictMode updater may run twice.\n */\nexport function forgetUnloaded<TData>(core: Core<TData>, cleared: readonly RowRange[], kept: readonly RowRange[] = []) {\n  if (cleared.length === 0 && kept.length === 0) return;\n  core.loaded = mergeRanges(core.loaded.flatMap((range) => subtractRanges(range, [...cleared, ...kept])));\n  core.stale = mergeRanges([...core.stale.flatMap((range) => subtractRanges(range, cleared)), ...kept]);\n  core.empty = core.empty.flatMap((range) => subtractRanges(range, cleared));\n  core.unloaded = true;\n}\n\ntype EvictInput<TData> = { loaded: readonly RowRange[]; keep: RowRange; size: number; cap: number; protectedIds: ProtectedRows; idOf: (row: TData, index: number) => string };\n\n/** Unloads the least recently viewed blocks outside the keep range until the loaded rows fit the cap. Pure in `rows`; the core updates are idempotent. */\nexport function evictRows<TData>(core: Core<TData>, rows: (TData | undefined)[], { loaded, keep, size, cap, protectedIds, idOf }: EvictInput<TData>): (TData | undefined)[] {\n  const protectedSlots = protectedIds === null ? undefined : (block: RowRange) => protectedSlotsIn(rows, block, protectedIds, idOf);\n  const picks = pickEvictions({ loaded, viewed: core.viewed, keep, blockSize: size, cap, protectedSlots });\n  if (picks.length === 0) return rows;\n  const ranges = picks.flatMap(unloadRangesOf);\n  // `rows` is the fresh copy that `writeBlocks` returned, so the slots are written in place.\n  for (const { start, end } of ranges) rows.fill(undefined, start, Math.min(end, rows.length));\n  forgetUnloaded(core, ranges, picks.flatMap((pick) => pick.kept.map((slot) => ({ start: slot, end: slot + 1 }))));\n  core.reportAfterUnload = true;\n  for (const pick of picks) if (pick.kept.length === 0) core.evictedBlocks.add(pick.block.start / size);\n  return rows;\n}\n\nexport function protectedSlotsIn<TData>(rows: readonly (TData | undefined)[], block: RowRange, protectedIds: ReadonlySet<string>, idOf: (row: TData, index: number) => string): number[] {\n  const slots: number[] = [];\n  for (let index = block.start; index < Math.min(block.end, rows.length); index++) {\n    const row = rows[index];\n    if (row !== undefined && protectedIds.has(idOf(row, index))) slots.push(index);\n  }\n  return slots;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/scroll-eviction.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/scroll-core.ts",
      "content": "import type { RowRange } from \"@/registry/default/components/data-grid/data-grid\";\nimport type { Wanted } from \"./fetch-hygiene\";\nimport type { SeqBlock } from \"./sequence-eviction\";\nimport type { FetchReason } from \"./read-answer\";\nimport type { GuardedBlock, ProtectedRows } from \"./refresh-guard\";\n\nexport type Pending<TData> = GuardedBlock<TData> & { rows: (TData | undefined)[]; mark: number; final?: boolean };\n/** `guard` is the set of rows protected when the request started; a retry reuses it. */\nexport type Guard = { ids: ProtectedRows; /** The save count when the request started; later saves are protected too. */ mark: number };\nexport type InFlight = { range: RowRange; controller: AbortController; guard: Guard; /** The answer is being written; the request only waits to settle. */ landed: boolean };\nexport type Failed = { range: RowRange; cursor: unknown; error: unknown };\n\nexport type Sequence = {\n  /** The cursor the next block sends. */\n  cursor: unknown;\n  ended: boolean;\n  /** Rows loaded, without the skeleton rows below them. */\n  length: number;\n  /** Where the next request starts: the rows the server answered, which exceed `length` by the protected rows dropped from appended blocks. */\n  offset: number;\n  /** The count the server sent, if any. */\n  sentCount: number | null;\n  /** A refresh rewrites the rows in place from the first block until the chain passes `keepUntil`. */\n  refresh: { keepUntil: number; local: number } | null;\n  /** Keys of the cursors the chain returned so far. */\n  seen: Set<string>;\n  /** The landed blocks, ascending by `local`; an evicted block reloads from its stored cursor. */\n  blocks: SeqBlock[];\n};\n\nexport const freshSequence = (): Sequence => ({ cursor: undefined, ended: false, length: 0, offset: 0, sentCount: null, refresh: null, seen: new Set(), blocks: [] });\n\nexport type Core<TData> = {\n  count: number | null;\n  /** The first block of the current spec landed. */\n  ready: boolean;\n  loaded: RowRange[];\n  /** Decided by the first answer of the current spec. */\n  kind: \"unknown\" | \"random\" | \"sequence\";\n  seq: Sequence;\n  inFlight: Map<string, InFlight>;\n  failed: Map<string, Failed>;\n  pending: Pending<TData>[];\n  cancelFrame: (() => void) | null;\n  lastWindow: RowRange | null;\n  rowsLength: number;\n  warned: Set<string>;\n  /** Guarded rows an earlier block overwrote, for the block that brings their id back; empty when no request is pending. */\n  displaced: Map<string, TData>;\n  /** Protected rows that are not loaded (dropped by a spec change or deleted locally); a block that carries one keeps its incoming copy. */\n  absent: Set<string>;\n  /** Ranges whose rows a local row operation moved: not loaded, but a protected row may still sit there. A landing block or an eviction removes them. */\n  stale: RowRange[];\n  /** Protected rows that a block overwrote, and the ids the landed blocks carried; both are emptied when no request is pending. */\n  orphans: Map<string, { row: TData; slot: number }>;\n  carried: Set<string>;\n  /** Cancels the refresh that a burst of local row operations queued for the next frame. */\n  cancelQueuedRefresh: (() => void) | null;\n  /** Rows with a delete still saving: an answer that carries one drops it. */\n  deleted: Set<string>;\n  /** Slots an answer left empty on purpose (a repeated or deleted row): answered, never refetched, never claimed as loaded. */\n  empty: RowRange[];\n  /** Slots a protected row moved away from; `core.loaded` stops claiming them. */\n  cleared: Set<number>;\n  /** Slots where a protected row returned outside any claimed range; they join `stale`, so a count change still finds the row. */\n  restored: Set<number>;\n  /** Uncovered blocks of the wanted range with the time each entered it; one entry for a sequential source. */\n  wanted: Wanted;\n  /** Evicted sequential blocks inside the wanted range, by server start. */\n  reloads: Wanted;\n  delayTimer: ReturnType<typeof setTimeout> | null;\n  /** Why the requests that start now run; back to `\"load\"` when none is owed or in flight. */\n  reason: FetchReason;\n  /** Blocks of a refresh or retry that wait for a free request slot. */\n  owed: RowRange[];\n  /** Block index -> stamp of the latest report that had the block in its keep range. */\n  viewed: Map<number, number>;\n  tick: number;\n  /** The keep range of the latest report. */\n  keep: RowRange | null;\n  /** Blocks an eviction unloaded; the layout effect drops their stamps. */\n  evictedBlocks: Set<number>;\n  /** Set when rows were unloaded; the layout effect syncs the loaded count. */\n  unloaded: boolean;\n  /** Set by an eviction; the layout effect reports the rendered rows again, in case a report ran before the rows unloaded. */\n  reportAfterUnload: boolean;\n  pumping: boolean;\n  pumpAgain: boolean;\n};\n\nexport function createCore<TData>(): Core<TData> {\n  return { count: null, ready: false, loaded: [], kind: \"unknown\", seq: freshSequence(), inFlight: new Map(), failed: new Map(), pending: [], cancelFrame: null, lastWindow: null, rowsLength: 0, warned: new Set(), displaced: new Map(), absent: new Set(), deleted: new Set(), cancelQueuedRefresh: null, orphans: new Map(), carried: new Set(), empty: [], stale: [], cleared: new Set(), restored: new Set(), wanted: new Map(), reloads: new Map(), delayTimer: null, reason: \"load\", owed: [], viewed: new Map(), tick: 0, keep: null, evictedBlocks: new Set(), unloaded: false, reportAfterUnload: false, pumping: false, pumpAgain: false };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/scroll-core.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/scroll-seed.ts",
      "content": "import { readAnswer, type ServerRowsAnswer } from \"./read-answer\";\nimport { skeletonCount, startsSequence, stepSequence } from \"./scroll-sequence\";\n\n/** The `initialAnswer` of scroll mode, read into the first render state; it stands for block 0 of the spec whose key it carries. */\nexport type ScrollSeed<TData, TCursor> = {\n  specKey: string;\n  /** The answer cut to one block, handed to the landing path. */\n  answer: ServerRowsAnswer<TData, TCursor>;\n  cut: boolean;\n  rows: (TData | undefined)[];\n  count: number | null;\n  skeletons: number | null;\n  loadedCount: number;\n};\n\nexport function readScrollSeed<TData, TCursor>(initial: ServerRowsAnswer<TData, TCursor> | undefined, specKey: string, blockSize: number, source: \"random\" | \"sequential\" | undefined): ScrollSeed<TData, TCursor> | null {\n  if (initial === undefined) return null;\n  const range = { start: 0, end: blockSize };\n  let read: ReturnType<typeof readAnswer<TData, TCursor>>;\n  try {\n    read = readAnswer<TData, TCursor>(initial, range, () => {});\n  } catch {\n    return null;\n  }\n  const cut = Array.isArray(initial.rows) && initial.rows.length > blockSize;\n  const answer = { ...initial, rows: read.rows } as ServerRowsAnswer<TData, TCursor>;\n  const sequence = source === \"sequential\" || (source !== \"random\" && startsSequence(read));\n  if (!sequence) {\n    const count = typeof read.totalRowCount === \"number\" ? read.totalRowCount : read.rows.length;\n    const rows = new Array<TData | undefined>(count);\n    const written = Math.min(read.rows.length, count);\n    for (let index = 0; index < written; index++) rows[index] = read.rows[index];\n    return { specKey, answer, cut, rows, count, skeletons: null, loadedCount: read.rows.slice(0, written).filter((row) => row !== undefined).length };\n  }\n  const sentCount = typeof read.totalRowCount === \"number\" ? read.totalRowCount : null;\n  const loaded = read.rows.filter((row) => row !== undefined);\n  const { ended } = stepSequence({ read, sentCursor: undefined, loaded: read.rows.length, count: sentCount, seenCursors: new Set() });\n  const tail = skeletonCount({ loaded: read.rows.length, blockSize, count: sentCount, ended });\n  const rows = [...loaded, ...new Array<undefined>(tail).fill(undefined)];\n  return { specKey, answer, cut, rows, count: sentCount ?? (ended ? loaded.length : null), skeletons: tail, loadedCount: loaded.length };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/scroll-seed.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/scroll-types.ts",
      "content": "import type { DataChange, DataGridPlugin, FilterNode, RowRange, ServerSpec, SortSpec } from \"@/registry/default/components/data-grid/data-grid\";\nimport type { ExpandedState, ServerGroupLayout } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport type { SaveRefreshOptions } from \"./save-refresh\";\nimport type { UseDataGridServerRowsRootProps } from \"./use-data-grid-server-rows\";\n\n/** Props of {@link UseDataGridServerRowsScrollResult.gridProps} that belong to `DataGridProvider`. */\nexport type UseDataGridServerRowsScrollProviderProps<TData> = {\n  /** Sparse at runtime: an unloaded row is a hole, typed as `TData` to match `DataGridProps`. */\n  data: readonly TData[];\n  /** Gives an unloaded row a placeholder id and a loaded row its own. */\n  getRowId: (row: TData, index: number) => string;\n  /** Keeps the rows in step with edits, inserts, deletes, and reverts of a refused save. Send changes to your API from `onSave`. */\n  onDataChange: (next: readonly TData[], change: DataChange<TData>) => void;\n  /** Present when the hook got an `onSave`. */\n  onSave?: SaveRefreshOptions<TData>[\"onSave\"];\n  /** Reports the rendered rows so the hook can fetch the blocks they need. */\n  onRenderedRowsChange: (range: RowRange) => void;\n  sortMode: \"server\";\n  filterMode: \"server\";\n  sortState: SortSpec[];\n  onSortChange: (next: SortSpec[]) => void;\n  filterState: FilterNode[];\n  onFilterChange: (next: FilterNode[]) => void;\n  filterJoin: \"and\" | \"or\";\n  onFilterJoinChange: (next: \"and\" | \"or\") => void;\n  searchText: string;\n  onSearchTextChange: (next: string) => void;\n  /** The row count of the result; `null` until the first block lands, and for a sequential source until it ends or the server sends one. */\n  totalRowCount: number | null;\n  /** Keeps checks by row id across window moves, evictions, and server sorts and filters. */\n  checkedRowsLifetime: \"across-filters\";\n  /** The refresh guard that keeps a refresh from overwriting a row with a pending save or an open edit, then the `plugins` option. */\n  plugins: readonly DataGridPlugin<unknown>[];\n  /** Sorts on a header click. Override it after the spread. */\n  headerClickBehavior: \"sort\";\n  /** Present while the source groups: the group columns, outermost first. */\n  groupBy?: readonly string[];\n  /** Present while the source groups. */\n  onGroupByChange?: (next: readonly string[]) => void;\n  /** Present while the source groups: the open groups. */\n  expanded?: ExpandedState;\n  /** Present while the source groups. */\n  onExpandedChange?: (next: ExpandedState) => void;\n  /** Present while `groupBy` is not empty. */\n  groupMode?: \"server\";\n  /** Present while `groupBy` is not empty. */\n  groupLayout?: ServerGroupLayout;\n};\n\n/** Return value of `useDataGridServerRows` in scroll mode. */\nexport type UseDataGridServerRowsScrollResult<TData> = {\n  /** Spread onto `<DataGrid {...server.gridProps} columns={columns} />`. */\n  gridProps: UseDataGridServerRowsScrollProviderProps<TData> & UseDataGridServerRowsRootProps;\n  /** The part of `gridProps` for `<DataGridProvider>` in a composed layout. */\n  providerProps: UseDataGridServerRowsScrollProviderProps<TData>;\n  /** The part of `gridProps` for `<DataGridRoot>` in a composed layout: the loading flag and the error state. */\n  rootProps: UseDataGridServerRowsRootProps;\n  /** The sort, filter, and search text of the current requests. */\n  spec: ServerSpec;\n  /** The row count of the result; `null` until the first block lands, and for a sequential source until it ends or the server sends one. */\n  totalRowCount: number | null;\n  /** `\"error\"` wins over `\"loading\"`. */\n  status: \"loading\" | \"error\" | \"ready\";\n  /** A request of the current spec is in flight. */\n  loading: boolean;\n  /** The latest failure of the current spec that no landed block has replaced, or `null`. */\n  error: unknown;\n  /** Repeats the blocks that failed. Does nothing without an error. */\n  retry: () => void;\n  /**\n   * Fetches the rendered rows again and keeps them on screen until the answers land. Drops every other loaded row. A sequential\n   * source refetches from the first block up to the rendered rows. A row with a pending edit, delete, or in-flight save keeps its local state.\n   * The hook calls it after saves settle by `refreshAfterSave`; call it yourself with `refreshAfterSave: false` or a void `onSave`.\n   */\n  refresh: () => void;\n  /** Asks the server to place the pushed rows again: one `refresh()` on the next frame, or after `reshapeDelayMs` when it is set. Calls in one frame join. A sequential source skips it while the rendered rows plus `overscan` end beyond 10 blocks. */\n  reshape: () => void;\n  /**\n   * Whether a timed refresh would run now. A sequential source skips `revalidateIntervalMs`, `reshapeDelayMs`, and `refreshAfterSave`\n   * refreshes while the rendered rows plus `overscan` end beyond 10 blocks, and then returns `false`; call `refresh()` yourself there.\n   * Not reactive: read it in an effect or a handler.\n   */\n  canRevalidate: () => boolean;\n  /** Rows with no data yet; they render as skeletons. A sequential source reports its one block of skeletons. */\n  unloadedCount: number;\n  /** The loaded ranges, merged and ascending. Not reactive: read it in an effect or a handler. */\n  getLoadedRanges: () => readonly RowRange[];\n  /**\n   * Unloads the rows in `range` and aborts the requests it covers; the next rendered window that covers them fetches them again.\n   * Rows with an open edit, a pending save, or an unsaved change, and the row under the active cell, stay in `data` but stop counting as loaded. Does nothing on a sequential source.\n   */\n  evict: (range: RowRange) => void;\n};\n",
      "type": "registry:component",
      "target": "components/data-grid-server/scroll-types.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/sequence-eviction.ts",
      "content": "import type { RowRange } from \"@/registry/default/components/data-grid/data-grid\";\nimport { distanceToCentre, rangesIntersect } from \"./fetch-hygiene\";\nimport { subtractRanges } from \"./range-math\";\nimport type { ProtectedRows } from \"./refresh-guard\";\nimport type { Core } from \"./scroll-core\";\nimport { protectedSlotsIn } from \"./scroll-eviction\";\n\n/** One landed block of a sequential chain: where its rows sit in `data` and the request that fetches it again. */\nexport type SeqBlock = { local: number; length: number; server: number; serverEnd: number; cursor: unknown; evicted: boolean };\n\n/** The loaded rows of a sequential chain: `[0, position)` minus the evicted blocks. */\nexport function sequenceLoaded(position: number, blocks: readonly SeqBlock[]): RowRange[] {\n  const gone = blocks.filter((block) => block.evicted).map((block) => ({ start: block.local, end: block.local + block.length }));\n  return position > 0 ? subtractRanges({ start: 0, end: position }, gone) : [];\n}\n\n/** The evicted blocks that overlap `range`. */\nexport function evictedBlocksIn(blocks: readonly SeqBlock[], range: RowRange): SeqBlock[] {\n  let low = 0;\n  let high = blocks.length;\n  while (low < high) {\n    const mid = (low + high) >> 1;\n    if (blocks[mid]!.local + blocks[mid]!.length <= range.start) low = mid + 1;\n    else high = mid;\n  }\n  const found: SeqBlock[] = [];\n  for (let index = low; index < blocks.length && blocks[index]!.local < range.end; index++) if (blocks[index]!.evicted) found.push(blocks[index]!);\n  return found;\n}\n\n/** Moves the blocks after a local insert (`delta` 1) or delete (`delta` -1) at `index`. */\nexport function shiftBlocks(blocks: SeqBlock[], index: number, delta: 1 | -1): SeqBlock[] {\n  const shifted: SeqBlock[] = [];\n  for (const block of blocks) {\n    if (block.local >= index + (delta === 1 ? 0 : 1)) shifted.push({ ...block, local: block.local + delta });\n    else if (index < block.local + block.length) shifted.push({ ...block, length: block.length + delta });\n    else shifted.push(block);\n  }\n  return shifted.filter((block) => block.length > 0);\n}\n\ntype EvictInput<TData> = {\n  /** `evicted` flags before this commit; a repeated run of the updater picks the same blocks. */\n  wasEvicted: readonly boolean[];\n  loadedTotal: number;\n  keep: RowRange;\n  cap: number;\n  protectedIds: ProtectedRows;\n  idOf: (row: TData, index: number) => string;\n};\n\n/**\n * Unloads the blocks furthest from the keep range until the loaded rows fit `cap`; that is the front of the chain while the user scrolls down.\n * A block with a protected row stays whole. Writes the slots of `rows` in place.\n */\nexport function evictSequenceRows<TData>(core: Core<TData>, rows: (TData | undefined)[], { wasEvicted, loadedTotal, keep, cap, protectedIds, idOf }: EvictInput<TData>): (TData | undefined)[] {\n  const { blocks } = core.seq;\n  const centre = (keep.start + keep.end) / 2;\n  const candidates = blocks.filter((block, index) => !wasEvicted[index] && !rangesIntersect({ start: block.local, end: block.local + block.length }, keep));\n  candidates.sort((a, b) => distanceToCentre({ start: b.local, end: b.local + b.length }, centre) - distanceToCentre({ start: a.local, end: a.local + a.length }, centre) || a.local - b.local);\n  let total = loadedTotal;\n  let evicted = false;\n  for (const block of candidates) {\n    if (total <= cap) break;\n    const range = { start: block.local, end: block.local + block.length };\n    if (protectedIds !== null && protectedSlotsIn(rows, range, protectedIds, idOf).length > 0) continue;\n    rows.fill(undefined, range.start, Math.min(range.end, rows.length));\n    block.evicted = true;\n    total -= block.length;\n    evicted = true;\n  }\n  if (!evicted) return rows;\n  core.loaded = sequenceLoaded(core.seq.length, blocks);\n  core.unloaded = true;\n  return rows;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/sequence-eviction.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/group-lists.ts",
      "content": "import { groupIdOf, groupKeyText, type GroupPathSegment, type ServerGroupSlot } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { MAX_ROW_COUNT } from \"./read-answer\";\nimport type { ServerGroupRow } from \"./read-groups-answer\";\n\n/** The children of one group: its groups of the next level, or its rows. The top level has the id `\"\"`. */\nexport type GroupList<TData> = {\n  id: string;\n  path: readonly GroupPathSegment[];\n  kind: \"groups\" | \"rows\";\n  /** `null` until the server answered the top level. */\n  count: number | null;\n  entries: (ServerGroupRow | TData | undefined)[];\n  /** Loaded block index to the stamp of the latest report that kept it in view. */\n  blocks: Map<number, number>;\n  /** Key shifts seen since the lists were last reloaded; the second one fails the block. */\n  conflicts: number;\n};\n\n/** Every list of an open or loaded group, by group id. */\nexport type GroupStore<TData> = { groupBy: readonly string[]; blockSize: number; lists: Map<string, GroupList<TData>>; leafCount: number | null };\n\n/** The view rows of the open lists, in order, and where each one lives. */\nexport type GroupView<TData> = {\n  /** One entry per view row; a group row and an unloaded row are `undefined`. */\n  data: (TData | undefined)[];\n  slots: ServerGroupSlot[];\n  /** The list and the offset inside it of every view row. */\n  owners: GroupList<TData>[];\n  offsets: number[];\n  leafCount: number;\n  holes: number;\n};\n\nexport const createGroupStore = <TData>(groupBy: readonly string[], blockSize: number): GroupStore<TData> => ({ groupBy, blockSize, lists: new Map(), leafCount: null });\n\nexport const blockOf = (offset: number, blockSize: number) => Math.floor(offset / blockSize);\n\nexport function listFor<TData>(store: GroupStore<TData>, path: readonly GroupPathSegment[], count: number | null): GroupList<TData> {\n  const id = path.length === 0 ? \"\" : groupIdOf(path);\n  let list = store.lists.get(id);\n  if (!list) {\n    list = { id, path, kind: path.length < store.groupBy.length ? \"groups\" : \"rows\", count, entries: [], blocks: new Map(), conflicts: 0 };\n    store.lists.set(id, list);\n  }\n  return list;\n}\n\nfunction setCount<TData>(list: GroupList<TData>, count: number, blockSize: number) {\n  list.count = count;\n  if (list.entries.length > count) list.entries.length = count;\n  for (const block of list.blocks.keys()) if (block * blockSize >= count) list.blocks.delete(block);\n}\n\n/** Writes a block of groups. Returns `\"shifted\"` when a key now sits at another offset than in a loaded block (the others drop), `\"failed\"` on a second shift. */\nexport function landGroups<TData>(store: GroupStore<TData>, list: GroupList<TData>, block: number, groups: readonly ServerGroupRow[], groupCount: number, stamp: number): \"ok\" | \"shifted\" | \"failed\" {\n  const size = store.blockSize;\n  const start = block * size;\n  const elsewhere = new Map<string, number>();\n  for (const other of list.blocks.keys()) {\n    if (other === block) continue;\n    for (let offset = other * size; offset < Math.min((other + 1) * size, list.entries.length); offset++) {\n      const entry = list.entries[offset] as ServerGroupRow | undefined;\n      if (entry) elsewhere.set(groupKeyText(entry.key), offset);\n    }\n  }\n  const shifted = groups.some((group, index) => {\n    const at = elsewhere.get(groupKeyText(group.key));\n    return at !== undefined && at !== start + index;\n  });\n  if (shifted) {\n    if (list.conflicts >= 1) return \"failed\";\n    list.conflicts++;\n    list.entries = [];\n    list.blocks = new Map();\n  }\n  setCount(list, groupCount, size);\n  groups.forEach((group, index) => {\n    if (start + index < groupCount) list.entries[start + index] = group;\n    const child = store.lists.get(groupIdOf([...list.path, { columnId: store.groupBy[list.path.length]!, key: group.key }]));\n    if (child && child.count !== group.childCount) setCount(child, group.childCount, size);\n  });\n  list.blocks.set(block, stamp);\n  return shifted ? \"shifted\" : \"ok\";\n}\n\n/** Writes a block of rows. `keep` names an existing row that a pending edit or save protects from the answer. */\nexport function landRows<TData>(store: GroupStore<TData>, list: GroupList<TData>, block: number, rows: readonly (TData | undefined)[], count: number | undefined, stamp: number, keep: (existing: TData, offset: number) => boolean) {\n  const size = store.blockSize;\n  if (count !== undefined) setCount(list, count, size);\n  const start = block * size;\n  rows.forEach((row, index) => {\n    const offset = start + index;\n    if (list.count !== null && offset >= list.count) return;\n    const existing = list.entries[offset] as TData | undefined;\n    if (existing !== undefined && keep(existing, offset)) return;\n    list.entries[offset] = row;\n  });\n  list.blocks.set(block, stamp);\n}\n\nexport function evictBlock<TData>(store: GroupStore<TData>, list: GroupList<TData>, block: number) {\n  if (!list.blocks.delete(block)) return;\n  const start = block * store.blockSize;\n  const end = Math.min(start + store.blockSize, list.entries.length);\n  for (let offset = start; offset < end; offset++) list.entries[offset] = undefined;\n}\n\n/** Lays the open lists out as view rows. A child list that is not loaded yet shows as unloaded rows, sized by the `childCount` of its group. `topWindow` cuts the top level to one page of groups. The walk stops at `cap` view rows (default `MAX_ROW_COUNT`) and calls `onCapped` once. */\nexport function layoutView<TData>(store: GroupStore<TData>, isOpen: (groupId: string) => boolean, statusOf: (groupId: string) => \"loading\" | \"failed\" | undefined, topWindow?: { start: number; end: number }, { cap = MAX_ROW_COUNT, onCapped }: { cap?: number; onCapped?: () => void } = {}): GroupView<TData> {\n  const view: GroupView<TData> = { data: [], slots: [], owners: [], offsets: [], leafCount: store.leafCount ?? 0, holes: 0 };\n  const top = store.lists.get(\"\");\n  let capped = false;\n  if (top?.count) walk(top);\n  if (capped) onCapped?.();\n  return view;\n\n  function walk(list: GroupList<TData>) {\n    const count = list.count ?? 0;\n    const window = list.id === \"\" ? topWindow : undefined;\n    for (let offset = window?.start ?? 0; offset < (window ? Math.min(count, window.end) : count); offset++) {\n      if (view.data.length >= cap) {\n        capped = true;\n        return;\n      }\n      const entry = list.entries[offset];\n      view.owners.push(list);\n      view.offsets.push(offset);\n      if (list.kind === \"rows\" || entry === undefined) {\n        view.data.push(entry as TData | undefined);\n        if (entry === undefined) view.holes++;\n        continue;\n      }\n      const group = entry as ServerGroupRow;\n      const path = [...list.path, { columnId: store.groupBy[list.path.length]!, key: group.key }];\n      const id = groupIdOf(path);\n      const open = isOpen(id);\n      const status = open ? statusOf(id) : undefined;\n      view.slots.push({\n        viewRow: view.data.length,\n        path,\n        count: group.totalRowCount,\n        childCount: group.childCount,\n        ...(group.label === undefined ? null : { label: group.label }),\n        ...(group.aggregates ? { aggregates: group.aggregates } : null),\n        ...(status ? { status } : null),\n      });\n      view.data.push(undefined);\n      if (open) walk(listFor(store, path, group.childCount));\n      if (capped) return;\n    }\n  }\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/group-lists.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/group-pages.ts",
      "content": "\"use client\";\n\nimport { useDataGridServerPager, type DataGridPaginationControls } from \"@/registry/default/components/data-grid-pagination/data-grid-pagination\";\nimport { DEFAULT_PAGE_SIZES } from \"@/registry/default/components/data-grid-pagination/pagination-math\";\nimport { createGroupStore, landGroups, listFor, type GroupStore } from \"./group-lists\";\nimport { readGroupsAnswer, type ServerGroupsAnswer } from \"./read-groups-answer\";\n\n/** Pages mode of the group engine: the top level is one page of groups, and a block of any list holds `pageSize` entries. */\nexport type GroupPagesConfig = {\n  page: number;\n  pageSize: number;\n  pageSizeOptions?: readonly number[];\n  onPageChange: (page: number) => void;\n  onPageSizeChange: (pageSize: number) => void;\n};\n\nexport const pageWindowOf = (pages: GroupPagesConfig | undefined) => (pages ? { start: (pages.page - 1) * pages.pageSize, end: pages.page * pages.pageSize } : undefined);\n\nexport function isGroupsAnswer(answer: unknown): answer is ServerGroupsAnswer {\n  return typeof answer === \"object\" && answer !== null && Array.isArray((answer as { groups?: unknown }).groups);\n}\n\n/** A store whose top level holds the `initialAnswer` as block `block`; `null` when the answer is not a usable groups answer. */\nexport function seedGroupStore<TData>(answer: unknown, groupBy: readonly string[], blockSize: number, block: number, aggregateIds: readonly string[]): GroupStore<TData> | null {\n  if (!isGroupsAnswer(answer)) return null;\n  try {\n    const start = block * blockSize;\n    const read = readGroupsAnswer(answer, { start, end: start + blockSize }, { topLevel: true, aggregateIds }, () => {});\n    const store = createGroupStore<TData>(groupBy, blockSize);\n    landGroups(store, listFor(store, [], null), block, read.groups, read.groupCount, 0);\n    if (read.totalRowCount !== undefined) store.leafCount = read.totalRowCount;\n    return store;\n  } catch {\n    return null;\n  }\n}\n\n/** The pager of a grouped pages source: a page counts top-level groups. Inert (no count) without `pages`. */\nexport function useGroupPager(pages: GroupPagesConfig | undefined, groupCount: number | null): { pager: DataGridPaginationControls; plugins: ReturnType<typeof useDataGridServerPager>[\"gridProps\"][\"plugins\"] } {\n  const { pager, gridProps } = useDataGridServerPager({\n    page: pages?.page ?? 1,\n    pageSize: pages?.pageSize ?? 1,\n    pageSizeOptions: pages?.pageSizeOptions ?? DEFAULT_PAGE_SIZES,\n    totalRowCount: pages ? groupCount : null,\n    unit: \"groups\",\n    onPageChange: pages?.onPageChange ?? noop,\n    onPageSizeChange: pages?.onPageSizeChange,\n  });\n  return { pager, plugins: gridProps.plugins };\n}\n\nfunction noop() {}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/group-pages.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/group-save-scope.ts",
      "content": "import type { DataChange, ServerSpec } from \"@/registry/default/components/data-grid/data-grid\";\n\n/** What a settled save reloads: every list, nothing, or the group rows above these rows. */\nexport type GroupSaveScope = \"all\" | \"none\" | { rowIds: string[] };\n\n/** Narrows the reload after saves: a change to a group, sort, or aggregate column is the only one that moves a row or a group row. */\nexport function groupSaveScope(changes: readonly DataChange<unknown>[], spec: Pick<ServerSpec, \"sorts\" | \"filters\" | \"searchText\" | \"groupBy\" | \"aggregates\">): GroupSaveScope {\n  if (spec.filters.length > 0 || spec.searchText) return \"all\";\n  const wide = new Set([...(spec.groupBy ?? []), ...spec.sorts.map((sort) => sort.columnId)]);\n  const aggregated = new Set((spec.aggregates ?? []).map((aggregate) => aggregate.columnId));\n  const rowIds = new Set<string>();\n  for (const change of changes) {\n    for (const op of change.ops) {\n      if (op.type !== \"update\" || !op.cells) return \"all\";\n      for (const { columnId } of op.cells) {\n        if (wide.has(columnId)) return \"all\";\n        if (aggregated.has(columnId)) rowIds.add(op.rowId);\n      }\n    }\n  }\n  return rowIds.size === 0 ? \"none\" : { rowIds: [...rowIds] };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/group-save-scope.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/use-group-blocks.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport { serverSpecKey, type DataChange, type RowRange } from \"@/registry/default/components/data-grid/data-grid\";\nimport { COLLAPSED, expandedTest, groupIdOf, holeRowId, isDev, normalizeExpanded, type ExpandedState, type ServerGroupLayout } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { blockOf, createGroupStore, evictBlock, landGroups, landRows, layoutView, listFor, type GroupList, type GroupStore, type GroupView } from \"./group-lists\";\nimport { isGroupsAnswer, pageWindowOf, seedGroupStore, useGroupPager, type GroupPagesConfig } from \"./group-pages\";\nimport { assertRowIdsNotReserved, readGroupsAnswer } from \"./read-groups-answer\";\nimport { MAX_ROW_COUNT, readAnswer, type FetchReason, type ServerRowsRequest, type WithRowId } from \"./read-answer\";\nimport { unionIds, useRefreshGuard } from \"./refresh-guard\";\nimport { groupSaveScope } from \"./group-save-scope\";\nimport { useSaveRefresh, type SaveRefreshPolicy, type SaveRefreshReport } from \"./save-refresh\";\nimport type { UseDataGridServerRowsScrollOptions } from \"./scroll-blocks\";\nimport type { UseDataGridServerRowsScrollProviderProps, UseDataGridServerRowsScrollResult } from \"./scroll-types\";\nimport { isolate, scheduleFrame, useControlled, useMountedPlugins, useRegisteredWiring, useReshape, useRevalidation, type ServerSpecState } from \"./server-state\";\nimport type { UseDataGridServerRowsRootProps } from \"./use-data-grid-server-rows\";\n\nconst DEFAULT_BLOCK_SIZE = 50;\nconst DEFAULT_OVERSCAN = 30;\nconst DEFAULT_CONCURRENT = 6;\nconst MAX_CONCURRENT = 16;\nconst DEFAULT_LOAD_DELAY_MS = 100;\nconst DEFAULT_MAX_LOADED_ROWS = 10_000;\nconst NO_GROUPS: readonly string[] = [];\n\n/** The open groups of a grouped server source. */\nexport type UseDataGridServerRowsGroupOptions = {\n  /** Controls the open groups; pair it with `onExpandedChange`. Only `mode: \"collapsed\"` applies: the server lists the children of an open group, so every other group stays closed. */\n  expanded?: ExpandedState;\n  /** Seeds the open groups once. Default: every group closed. */\n  defaultExpanded?: ExpandedState;\n  onExpandedChange?: (next: ExpandedState) => void;\n};\n\ntype Flight = { list: GroupList<never>; block: number; controller: AbortController; ids: ReadonlySet<string> | null; mark: number };\ntype Failure = { listId: string; error: unknown };\nfunction createEngine<TData>() {\n  return {\n    store: null as GroupStore<TData> | null,\n    view: null as ViewState<TData> | null,\n    flight: new Map<string, Flight>(),\n    failed: new Map<string, Failure>(),\n    stale: new Set<string>(),\n    window: null as RowRange | null,\n    reason: \"load\" as FetchReason,\n    tick: 0,\n    idIndex: null as Map<string, { list: GroupList<TData>; offset: number }> | null,\n    landed: [] as { list: GroupList<TData>; start: number; end: number }[],\n    cancelFrame: null as (() => void) | null,\n    pumpTimer: null as ReturnType<typeof setTimeout> | null,\n    warned: new Set<string>(),\n  };\n}\ntype Engine<TData> = ReturnType<typeof createEngine<TData>>;\ntype ViewState<TData> = GroupView<TData> & { loading: boolean; groupCount: number | null };\n\nconst emptyView = <TData,>(): ViewState<TData> => ({ data: [], slots: [], owners: [], offsets: [], leafCount: 0, holes: 0, loading: false, groupCount: null });\n\nconst positiveInteger = (value: number | undefined, fallback: number, min: number) => (typeof value === \"number\" && Number.isFinite(value) ? Math.max(min, Math.floor(value)) : fallback);\n\nconst blockSizeOf = (options: { blockSize?: number }, pages?: GroupPagesConfig) => pages?.pageSize ?? positiveInteger(options.blockSize, DEFAULT_BLOCK_SIZE, 1);\n\n/** Whether the options opt in to grouping; read once per hook, so the choice holds for its life. */\nexport function groupsEnabled(options: { spec?: { groupBy?: unknown }; defaultSpec?: unknown; expanded?: unknown; defaultExpanded?: unknown; onExpandedChange?: unknown }): boolean {\n  const seed = options.defaultSpec;\n  const seeded = typeof seed === \"object\" && seed !== null && (seed as { groupBy?: unknown }).groupBy !== undefined;\n  return options.spec?.groupBy !== undefined || seeded || options.expanded !== undefined || options.defaultExpanded !== undefined || options.onExpandedChange !== undefined;\n}\n\n/**\n * The group engine of scroll mode: one list per open group, loaded by offset in blocks. The core lays the group rows out from the\n * `groupLayout` this hook builds, and `data` holds one entry per view row. Group requests carry offsets, never a cursor.\n */\nexport function useGroupBlocks<TData, TCursor = never>(\n  options: WithRowId<UseDataGridServerRowsScrollOptions<TData, TCursor> & UseDataGridServerRowsGroupOptions, TData>,\n  specState: ServerSpecState,\n  active: boolean,\n  pages?: GroupPagesConfig,\n) {\n  const { spec, onSortChange, onFilterChange, onFilterJoinChange, onSearchTextChange, onGroupByChange } = specState;\n  const groupBy = spec.groupBy ?? NO_GROUPS;\n  const requestKey = serverSpecKey({ ...spec, aggregates: undefined });\n  const engineKey = pages ? `${requestKey}|${pages.pageSize}` : requestKey;\n  const aggregateKey = JSON.stringify(spec.aggregates ?? []);\n  const [rawExpanded, setExpanded] = useControlled(options.expanded, () => options.defaultExpanded ?? COLLAPSED, options.onExpandedChange);\n  const expanded = useMemo(() => (normalizeExpanded(rawExpanded).mode === \"collapsed\" ? normalizeExpanded(rawExpanded) : COLLAPSED), [rawExpanded]);\n  const aggregateIds = () => (spec.aggregates ?? []).map((aggregate) => aggregate.columnId);\n  const [seed] = useState(() => (active && isGroupsAnswer(options.initialAnswer) ? { answer: options.initialAnswer, key: engineKey } : null));\n  const [view, setView] = useState<ViewState<TData>>(() => {\n    const store = seed && seedGroupStore<TData>(seed.answer, groupBy, blockSizeOf(options, pages), (pages?.page ?? 1) - 1, aggregateIds());\n    return store ? { ...layoutView(store, expandedTest(expanded), () => undefined, pageWindowOf(pages)), loading: false, groupCount: store.lists.get(\"\")?.count ?? null } : emptyView();\n  });\n  const [error, setError] = useState<unknown>(null);\n  const { plugins: guardPlugins, protectedRows, savingRows, saveMark, savedSince, pruneSaves, overlayPushed, streamUpdateRow, setSettleListener, setReshapeListener, evictionProtected } = useRefreshGuard({ trackUnacknowledged: true });\n  const { pager, plugins: pagerPlugins } = useGroupPager(pages, view.groupCount);\n  const seedRef = useRef(seed);\n\n  const live = useRef({ options, spec, expanded, groupBy, active, pages, engineKey });\n  useLayoutEffect(() => {\n    live.current = { options, spec, expanded, groupBy, active, pages, engineKey };\n  });\n  const engineRef = useRef<Engine<TData> | null>(null);\n  const getEngine = useCallback((): Engine<TData> => {\n    if (engineRef.current === null) engineRef.current = createEngine<TData>();\n    return engineRef.current;\n  }, []);\n\n  const warn = useCallback(\n    (kind: string, message: string) => {\n      if (!isDev() || getEngine().warned.has(kind)) return;\n      getEngine().warned.add(kind);\n      console.warn(`[data-grid-server] ${message}`);\n    },\n    [getEngine],\n  );\n  /** The pages config with the page cut to the group count of the live store; `view.groupCount` lags one render. */\n  const livePages = (store: GroupStore<TData>) => {\n    const { pages: paging } = live.current;\n    const count = store.lists.get(\"\")?.count;\n    return paging && count ? { ...paging, page: Math.min(paging.page, Math.ceil(count / paging.pageSize)) } : paging;\n  };\n  const blockSize = () => blockSizeOf(live.current.options, live.current.pages);\n  const overscan = () => positiveInteger(live.current.options.overscan, DEFAULT_OVERSCAN, 0);\n  const idOf = (row: TData, index: number) => live.current.options.getRowId(row, index);\n\n  const syncError = () => setError(getEngine().failed.size > 0 ? [...getEngine().failed.values()].at(-1)!.error : null);\n\n  const publish = () => {\n    const store = getEngine().store;\n    if (!store) {\n      getEngine().view = null;\n      setView((prev) => (prev.data.length === 0 && prev.slots.length === 0 && !prev.loading && prev.groupCount === null ? prev : emptyView()));\n      return;\n    }\n    const states = new Map<string, \"loading\" | \"failed\">();\n    for (const { listId } of getEngine().failed.values()) states.set(listId, \"failed\");\n    for (const { list } of getEngine().flight.values()) if (!states.has(list.id)) states.set(list.id, \"loading\");\n    const next = { ...layoutView(store, expandedTest(live.current.expanded), (id) => states.get(id), pageWindowOf(livePages(store)), { onCapped: () => warn(\"view-cap\", `the open groups hold more than ${MAX_ROW_COUNT} view rows; the view stops at ${MAX_ROW_COUNT}. Collapse a group or add a filter`) }), loading: getEngine().flight.size > 0, groupCount: store.lists.get(\"\")?.count ?? null } satisfies ViewState<TData>;\n    getEngine().view = next;\n    setView(next);\n    const { onLoaded } = live.current.options;\n    for (const { list, start, end } of getEngine().landed.splice(0)) {\n      const first = firstViewRow(next, list, start);\n      if (first !== -1 && onLoaded) isolate(\"onLoaded\", () => onLoaded({ start: first, end: first + (end - start) }));\n    }\n  };\n  const schedulePublish = () => {\n    if (getEngine().cancelFrame !== null) return;\n    getEngine().cancelFrame = scheduleFrame(() => {\n      getEngine().cancelFrame = null;\n      publish();\n      pump();\n    });\n  };\n\n  const abortAll = () => {\n    for (const { controller } of getEngine().flight.values()) controller.abort();\n    getEngine().flight.clear();\n  };\n\n  const fail = (key: string, list: GroupList<TData>, error: unknown) => {\n    getEngine().failed.set(key, { listId: list.id, error: error ?? new Error(\"fetchRows rejected\") });\n    syncError();\n    const { onError } = live.current.options;\n    if (onError) isolate(\"onError\", () => onError(error));\n    schedulePublish();\n  };\n\n  const evictOverCap = (store: GroupStore<TData>) => {\n    const cap = live.current.options.maxLoadedRows;\n    const limit = typeof cap === \"number\" && !Number.isNaN(cap) ? Math.max(cap, store.blockSize) : DEFAULT_MAX_LOADED_ROWS;\n    const loaded: { list: GroupList<TData>; block: number; stamp: number }[] = [];\n    for (const list of store.lists.values()) if (list.kind === \"rows\") for (const entry of list.blocks) loaded.push({ list, block: entry[0], stamp: entry[1] });\n    let rows = loaded.length * store.blockSize;\n    if (rows <= limit) return;\n    const protectedIds = evictionProtected();\n    loaded.sort((a, b) => a.stamp - b.stamp);\n    for (const { list, block, stamp } of loaded) {\n      if (rows <= limit || stamp >= getEngine().tick - 1) break;\n      const start = block * store.blockSize;\n      const held = protectedIds && list.entries.slice(start, start + store.blockSize).some((row) => row !== undefined && protectedIds.has(idOf(row as TData, start)));\n      if (held) continue;\n      evictBlock(store, list, block);\n      rows -= store.blockSize;\n      getEngine().idIndex = null;\n    }\n  };\n\n  /** Writes a validated answer into its list; returns the failure instead of throwing, so `land` keeps one try block. */\n  const writeAnswer = (store: GroupStore<TData>, list: GroupList<TData>, flight: Flight, answer: unknown, range: RowRange): Error | null => {\n    const stamp = ++getEngine().tick;\n    if (list.kind === \"groups\") {\n      const aggregateIds = (live.current.spec.aggregates ?? []).map((aggregate) => aggregate.columnId);\n      const read = readGroupsAnswer(answer, range, { topLevel: list.id === \"\", aggregateIds }, warn);\n      if (landGroups(store, list, flight.block, read.groups, read.groupCount, stamp) === \"failed\") return new TypeError(\"fetchRows answered groups that shifted twice since the last reload; make the group order total\");\n      if (list.id === \"\" && read.totalRowCount !== undefined) store.leafCount = read.totalRowCount;\n      return null;\n    }\n    const read = readAnswer<TData, TCursor>(answer, range, warn, idOf);\n    assertRowIdsNotReserved(read.rows.flatMap((row, index) => (row === undefined ? [] : [idOf(row, range.start + index)])));\n    const guarded = unionIds(unionIds(flight.ids, savedSince(flight.mark)), protectedRows());\n    const count = typeof read.totalRowCount === \"number\" ? read.totalRowCount : undefined;\n    landRows(store, list, flight.block, overlayPushed(read.rows as TData[], flight.mark, range.start, idOf), count, stamp, (existing, offset) => guarded?.has(idOf(existing, offset)) === true);\n    return null;\n  };\n\n  const land = (key: string, flight: Flight, answer: unknown, range: RowRange) => {\n    const store = getEngine().store!;\n    const list = flight.list as unknown as GroupList<TData>;\n    getEngine().flight.delete(key);\n    getEngine().stale.delete(key);\n    let failure: unknown = null;\n    try {\n      failure = writeAnswer(store, list, flight, answer, range);\n    } catch (error) {\n      failure = error;\n    }\n    if (failure !== null) {\n      fail(key, list, failure);\n      return;\n    }\n    getEngine().failed.delete(key);\n    syncError();\n    getEngine().idIndex = null;\n    getEngine().landed.push({ list, start: range.start, end: range.start + (range.end - range.start) });\n    evictOverCap(store);\n    pruneSaves([...getEngine().flight.values()].reduce<number | null>((oldest, { mark }) => (oldest === null || mark < oldest ? mark : oldest), null));\n    schedulePublish();\n  };\n\n  const fetchBlock = (list: GroupList<TData>, block: number) => {\n    const key = `${list.id}|${block}`;\n    const size = blockSize();\n    const start = block * size;\n    const range = { start, end: list.count === null ? start + size : Math.max(start, Math.min(start + size, list.count)) };\n    const controller = new AbortController();\n    const flight: Flight = { list: list as unknown as GroupList<never>, block, controller, ids: savingRows(), mark: saveMark() };\n    getEngine().flight.set(key, flight);\n    const base: ServerRowsRequest<TCursor> = { spec: live.current.spec, ...range, cursor: undefined, reason: getEngine().reason, signal: controller.signal, groupPath: list.path, childKind: list.kind };\n    const request = live.current.pages ? { ...base, page: block + 1, pageSize: size } : base;\n    const settled = () => getEngine().flight.get(key)?.controller === controller && !controller.signal.aborted;\n    new Promise<unknown>((resolve) => resolve(live.current.options.fetchRows(request))).then(\n      (answer) => settled() && land(key, flight, answer, range),\n      (error: unknown) => {\n        if (!settled()) return;\n        getEngine().flight.delete(key);\n        fail(key, list, error);\n      },\n    );\n  };\n\n  /** Blocks under the rendered rows plus overscan, nearest to the middle first. */\n  const wantedBlocks = (store: GroupStore<TData>) => {\n    const found = new Map<string, { list: GroupList<TData>; block: number; distance: number }>();\n    const top = listFor(store, [], null);\n    const topBlock = (livePages(store)?.page ?? 1) - 1;\n    found.set(`|${topBlock}`, { list: top, block: topBlock, distance: -1 });\n    const { window: range, view: laid } = getEngine();\n    if (!range || !laid) return found;\n    const middle = (range.start + range.end) / 2;\n    const from = Math.max(0, range.start - overscan());\n    const to = Math.min(laid.data.length, range.end + overscan());\n    for (let row = from; row < to; row++) {\n      const list = laid.owners[row]!;\n      const block = blockOf(laid.offsets[row]!, store.blockSize);\n      const key = `${list.id}|${block}`;\n      if (!found.has(key)) found.set(key, { list, block, distance: Math.abs(row - middle) });\n    }\n    return found;\n  };\n\n  const newStore = () => {\n    const { groupBy: by, pages: paging, engineKey: key } = live.current;\n    const pending = seedRef.current;\n    const seeded = pending?.key === key ? seedGroupStore<TData>(pending.answer, by, blockSize(), (paging?.page ?? 1) - 1, (live.current.spec.aggregates ?? []).map((aggregate) => aggregate.columnId)) : null;\n    return seeded ?? createGroupStore<TData>(by, blockSize());\n  };\n\n  const seedStore = () => {\n    if (seedRef.current?.key === live.current.engineKey) getEngine().store = newStore();\n  };\n\n  const pump = () => {\n    if (!live.current.active) return;\n    const store = getEngine().store ?? newStore();\n    getEngine().store = store;\n    const wanted = wantedBlocks(store);\n    for (const [key, flight] of getEngine().flight) {\n      if (wanted.has(key)) continue;\n      flight.controller.abort();\n      getEngine().flight.delete(key);\n    }\n    const limit = Math.min(positiveInteger(live.current.options.maxConcurrentFetches, DEFAULT_CONCURRENT, 1), MAX_CONCURRENT);\n    const due = [...wanted]\n      .filter(([key, { list, block }]) => !getEngine().flight.has(key) && !getEngine().failed.has(key) && (!list.blocks.has(block) || getEngine().stale.has(key)))\n      .sort((a, b) => a[1].distance - b[1].distance);\n    for (const entry of wanted.values()) if (entry.list.blocks.has(entry.block)) entry.list.blocks.set(entry.block, ++getEngine().tick);\n    let started = false;\n    for (const [, entry] of due) {\n      if (getEngine().flight.size >= limit) break;\n      fetchBlock(entry.list, entry.block);\n      started = true;\n    }\n    if (started) schedulePublish();\n  };\n\n  const pumpSoon = (immediate: boolean) => {\n    const delay = positiveInteger(live.current.options.loadDelayMs, DEFAULT_LOAD_DELAY_MS, 0);\n    const engine = getEngine();\n    if (engine.pumpTimer !== null) clearTimeout(engine.pumpTimer);\n    engine.pumpTimer = null;\n    if (immediate || delay === 0) pump();\n    else engine.pumpTimer = setTimeout(() => ((engine.pumpTimer = null), pump()), delay);\n  };\n\n  const reset = () => {\n    const engine = getEngine();\n    abortAll();\n    if (engine.pumpTimer !== null) clearTimeout(engine.pumpTimer);\n    engine.pumpTimer = null;\n    engine.cancelFrame?.();\n    engine.cancelFrame = null;\n    engine.store = null;\n    engine.view = null;\n    engine.idIndex = null;\n    engine.failed.clear();\n    engine.stale.clear();\n    engine.landed = [];\n    engine.reason = \"load\";\n    pruneSaves(null);\n    setError(null);\n  };\n\n  const staleGroupBlocks = () => {\n    const engine = getEngine();\n    if (!engine.store) return;\n    for (const list of engine.store.lists.values()) if (list.kind === \"groups\") for (const block of list.blocks.keys()) engine.stale.add(`${list.id}|${block}`);\n    pump();\n  };\n\n  const refreshForSaves = (report: SaveRefreshReport) => {\n    const engine = getEngine();\n    const store = engine.store;\n    const total = report.saved + report.rejected + report.failed;\n    const scope = report.rejected + report.failed > 0 || total > report.changes.length ? \"all\" : groupSaveScope(report.changes, live.current.spec);\n    if (!store || scope === \"all\") return refreshFor(\"save\");\n    if (scope === \"none\") return;\n    const index = engine.idIndex ?? indexRows(store, idOf);\n    engine.idIndex = index;\n    const above = new Set<string>();\n    for (const rowId of scope.rowIds) {\n      const at = index.get(rowId);\n      if (!at) return refreshFor(\"save\");\n      for (let depth = 0; depth < at.list.path.length; depth++) above.add(depth === 0 ? \"\" : groupIdOf(at.list.path.slice(0, depth)));\n    }\n    engine.reason = \"save\";\n    for (const id of above) for (const block of store.lists.get(id)?.blocks.keys() ?? []) engine.stale.add(`${id}|${block}`);\n    pump();\n  };\n\n  const loading = view.loading;\n  const apiRef = useRef({ seedStore: noop, pump: noop, pumpSoon: noopFlag, publish: noop, reset: noop, refreshFor: noopReason, refreshForSaves: noopReport, staleGroupBlocks: noop, retry: noop, applyUpdates: noopChange, evictRange: noopRange });\n  const { request: requestReshape, cancel: cancelReshape } = useReshape({ delay: active ? options.reshapeDelayMs : false, ordered: spec.sorts.length + spec.filters.length > 0, run: () => apiRef.current.refreshFor(\"refresh\"), busy: loading, resetKey: requestKey, warn });\n  const restartClock = useRevalidation({ interval: active ? options.revalidateIntervalMs : undefined, onTick: () => apiRef.current.refreshFor(\"refresh\"), busy: loading, resetKey: requestKey });\n\n  const refreshFor = (reason: FetchReason) => {\n    const engine = getEngine();\n    cancelReshape();\n    restartClock();\n    engine.reason = reason;\n    abortAll();\n    engine.failed.clear();\n    engine.stale.clear();\n    syncError();\n    const store = engine.store;\n    if (store) {\n      const keep = wantedBlocks(store);\n      for (const list of store.lists.values()) {\n        list.conflicts = 0;\n        for (const block of Array.from(list.blocks.keys())) {\n          const key = `${list.id}|${block}`;\n          if (list.kind === \"groups\" || keep.has(key)) engine.stale.add(key);\n          else evictBlock(store, list, block);\n        }\n      }\n      engine.idIndex = null;\n    }\n    pump();\n    schedulePublish();\n  };\n\n  const retryFailed = () => {\n    const engine = getEngine();\n    engine.failed.clear();\n    syncError();\n    engine.reason = \"retry\";\n    pump();\n    schedulePublish();\n  };\n\n  const evictRange = (range: RowRange) => {\n    const engine = getEngine();\n    const store = engine.store;\n    const laid = engine.view;\n    if (!store || !laid) return;\n    for (let row = Math.max(0, range.start); row < Math.min(range.end, laid.data.length); row++) {\n      const list = laid.owners[row]!;\n      if (list.kind === \"rows\") evictBlock(store, list, blockOf(laid.offsets[row]!, store.blockSize));\n    }\n    engine.idIndex = null;\n    publish();\n  };\n\n  const applyUpdates = (change: DataChange<TData>) => {\n    const engine = getEngine();\n    const store = engine.store;\n    if (!store) return;\n    const index = engine.idIndex ?? indexRows(store, idOf);\n    engine.idIndex = index;\n    const rowOf = streamUpdateRow(change);\n    let written = false;\n    for (const op of change.ops) {\n      if (op.type !== \"update\") {\n        warn(\"rows-ignored\", \"an insert, delete, or move reached a grouped source and was ignored; the server places rows while the grid is grouped\");\n        continue;\n      }\n      const at = index.get(op.rowId);\n      if (!at) continue;\n      at.list.entries[at.offset] = rowOf ? rowOf(op, at.list.entries[at.offset] as TData) : op.row;\n      written = true;\n    }\n    if (written) publish();\n    if (change.source === \"stream\" && change.ops.some((op) => op.type !== \"update\")) requestReshape(\"soon\");\n  };\n\n  useLayoutEffect(() => {\n    apiRef.current = { seedStore, pump, pumpSoon, publish, reset, refreshFor, refreshForSaves, staleGroupBlocks, retry: retryFailed, applyUpdates: applyUpdates as (change: DataChange<never>) => void, evictRange };\n  });\n\n  const onRenderedRowsChange = useCallback(\n    (range: RowRange) => {\n      getEngine().window = range;\n      apiRef.current.pumpSoon(false);\n      isolate(\"onRenderedRowsChange\", () => live.current.options.onRenderedRowsChange?.(range));\n    },\n    [getEngine],\n  );\n\n  // A new request key drops every list and fetches the top level again; `expanded` stays, because group ids come from the keys.\n  useLayoutEffect(() => {\n    if (seedRef.current && seedRef.current.key !== engineKey) seedRef.current = null;\n    apiRef.current.reset();\n    if (active) apiRef.current.seedStore();\n    apiRef.current.publish();\n    if (!active) return;\n    const timer = setTimeout(() => apiRef.current.pump(), 0);\n    return () => {\n      clearTimeout(timer);\n      apiRef.current.reset();\n    };\n  }, [engineKey, active]);\n\n  useEffect(() => {\n    if (active && options.source === \"sequential\") warn(\"sequential\", 'source: \"sequential\" has no effect while grouped: groups load by offset. Use source: \"random\" (or omit it) with groupBy.');\n  }, [active, options.source, warn]);\n\n  // Aggregates change the group rows only: reload their blocks in place and keep the lists and the scroll position.\n  const firstAggregates = useRef(aggregateKey);\n  useEffect(() => {\n    if (firstAggregates.current === aggregateKey) return;\n    firstAggregates.current = aggregateKey;\n    apiRef.current.staleGroupBlocks();\n  }, [aggregateKey]);\n\n  // A toggle lays the view out again and asks for the rows the open group shows.\n  useLayoutEffect(() => {\n    if (!getEngine().store) return;\n    apiRef.current.publish();\n    apiRef.current.pumpSoon(true);\n  }, [expanded, pages?.page, getEngine]);\n\n  const refresh = useCallback(() => apiRef.current.refreshFor(\"refresh\"), []);\n  const retry = useCallback(() => apiRef.current.retry(), []);\n  const reshape = useCallback(() => requestReshape(\"soon\"), [requestReshape]);\n  useEffect(() => {\n    setReshapeListener(requestReshape);\n    return () => setReshapeListener(null);\n  }, [setReshapeListener, requestReshape]);\n  useEffect(() => {\n    setSettleListener(() => {\n      if (live.current.options.refreshAfterSave !== false) apiRef.current.refreshFor(\"save\");\n    });\n    return () => setSettleListener(null);\n  }, [setSettleListener]);\n\n  const handledChanges = useRef(new WeakSet<object>());\n  const onDataChange = useCallback(\n    (next: readonly TData[], change: DataChange<TData>) => {\n      if (handledChanges.current.has(change)) return;\n      handledChanges.current.add(change);\n      apiRef.current.applyUpdates(change as DataChange<never>);\n      const onChange = live.current.options.onDataChange;\n      if (onChange) isolate(\"onDataChange\", () => onChange(next, change));\n    },\n    [],\n  );\n\n  const refreshAfterSave = useCallback((report: SaveRefreshReport) => apiRef.current.refreshForSaves(report), []);\n  const { onSave, wrapSave } = useSaveRefresh({ onSave: options.onSave, refreshAfterSave: options.refreshAfterSave as SaveRefreshPolicy | undefined }, refreshAfterSave);\n  const paged = pages !== undefined;\n  const ownPlugins = useMemo(() => (paged ? [...guardPlugins, ...pagerPlugins] : guardPlugins), [paged, guardPlugins, pagerPlugins]);\n  const plugins = useMountedPlugins(ownPlugins, options.plugins);\n  const getRowId = useCallback((row: TData, index: number) => (row === undefined ? holeRowId(index) : live.current.options.getRowId(row, index)), []);\n  const groupLayout = useMemo<ServerGroupLayout>(() => ({ rows: view.slots, leafCount: view.leafCount }), [view]);\n\n  const providerProps = useMemo<UseDataGridServerRowsScrollProviderProps<TData>>(\n    () => ({\n      data: view.data as TData[],\n      getRowId,\n      onDataChange,\n      ...(onSave ? { onSave } : {}),\n      onRenderedRowsChange,\n      sortMode: \"server\",\n      filterMode: \"server\",\n      sortState: spec.sorts as UseDataGridServerRowsScrollProviderProps<TData>[\"sortState\"],\n      onSortChange,\n      filterState: spec.filters as UseDataGridServerRowsScrollProviderProps<TData>[\"filterState\"],\n      onFilterChange,\n      filterJoin: spec.filterJoin ?? \"and\",\n      onFilterJoinChange,\n      searchText: spec.searchText,\n      onSearchTextChange,\n      totalRowCount: view.data.length,\n      checkedRowsLifetime: \"across-filters\",\n      headerClickBehavior: \"sort\",\n      plugins,\n      groupBy,\n      onGroupByChange,\n      expanded,\n      onExpandedChange: setExpanded,\n      groupMode: \"server\",\n      groupLayout,\n    }),\n    [view, getRowId, onDataChange, onSave, onRenderedRowsChange, spec, onSortChange, onFilterChange, onFilterJoinChange, onSearchTextChange, plugins, groupBy, onGroupByChange, expanded, setExpanded, groupLayout],\n  );\n  useRegisteredWiring(providerProps, wrapSave);\n  const rootProps = useMemo<UseDataGridServerRowsRootProps>(() => ({ loading, error, onRetry: retry }), [loading, error, retry]);\n  const gridProps = useMemo(() => ({ ...providerProps, ...rootProps }), [providerProps, rootProps]);\n\n  const getLoadedRanges = useCallback((): readonly RowRange[] => {\n    const ranges: RowRange[] = [];\n    const data = getEngine().view?.data ?? [];\n    const slots = new Set(getEngine().view?.slots.map((slot) => slot.viewRow));\n    data.forEach((row, index) => {\n      if (row === undefined && !slots.has(index)) return;\n      const last = ranges.at(-1);\n      if (last && last.end === index) last.end = index + 1;\n      else ranges.push({ start: index, end: index + 1 });\n    });\n    return ranges;\n  }, [getEngine]);\n  const evict = useCallback((range: RowRange) => apiRef.current.evictRange(range), []);\n\n  const status = error !== null ? \"error\" : loading ? \"loading\" : \"ready\";\n  const result: UseDataGridServerRowsScrollResult<TData> = { gridProps, providerProps, rootProps, spec, totalRowCount: view.leafCount, status, loading, error, retry, refresh, reshape, canRevalidate: () => true, unloadedCount: view.holes, getLoadedRanges, evict };\n  const groupProps = useMemo(() => ({ groupBy, onGroupByChange, expanded, onExpandedChange: setExpanded }), [groupBy, onGroupByChange, expanded, setExpanded]);\n  return { result, groupProps, pager, pagerPlugins, groupCount: view.groupCount };\n}\n\nfunction noop() {}\nconst noopFlag = (_immediate: boolean) => {};\nconst noopReason = (_reason: FetchReason) => {};\nconst noopReport = (_report: SaveRefreshReport) => {};\nconst noopChange = (_change: DataChange<never>) => {};\nconst noopRange = (_range: RowRange) => {};\n\nfunction firstViewRow<TData>(view: GroupView<TData>, list: GroupList<TData>, offset: number): number {\n  for (let row = 0; row < view.owners.length; row++) if (view.owners[row] === list && view.offsets[row] === offset) return row;\n  return -1;\n}\n\nfunction indexRows<TData>(store: GroupStore<TData>, idOf: (row: TData, index: number) => string) {\n  const index = new Map<string, { list: GroupList<TData>; offset: number }>();\n  for (const list of store.lists.values()) {\n    if (list.kind !== \"rows\") continue;\n    list.entries.forEach((row, offset) => {\n      if (row !== undefined) index.set(idOf(row as TData, offset), { list, offset });\n    });\n  }\n  return index;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/use-group-blocks.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/use-scroll-rows.ts",
      "content": "\"use client\";\n\nimport { useMemo, useState } from \"react\";\nimport type { WithRowId } from \"./read-answer\";\nimport { useScrollBlocks, type UseDataGridServerRowsScrollOptions } from \"./scroll-blocks\";\nimport type { UseDataGridServerRowsScrollResult } from \"./scroll-types\";\nimport { useServerSpec } from \"./server-state\";\nimport { groupsEnabled, useGroupBlocks, type UseDataGridServerRowsGroupOptions } from \"./use-group-blocks\";\n\nfunction noop() {}\n\ntype Options<TData, TCursor> = WithRowId<UseDataGridServerRowsScrollOptions<TData, TCursor> & UseDataGridServerRowsGroupOptions, TData>;\n\n/**\n * Scroll mode: the flat block engine, plus the group engine when the options opt in to grouping. Both read one spec. While the\n * spec groups, the flat engine waits (`ready: false`) and the group engine fetches; an empty `groupBy` hands the rows back.\n */\nexport function useScrollRows<TData, TCursor = never>(options: Options<TData, TCursor>): UseDataGridServerRowsScrollResult<TData> {\n  const [grouping] = useState(() => groupsEnabled(options));\n  const specState = useServerSpec(options, noop, grouping);\n  const grouped = grouping && (specState.spec.groupBy?.length ?? 0) > 0;\n  const flatSpec = useMemo(() => (grouped ? { ...specState, ready: false } : specState), [grouped, specState]);\n  const flat = useScrollBlocks(options, flatSpec);\n  const groups = useGroupBlocks(options, specState, grouped);\n  const extra = grouping ? groups.groupProps : undefined;\n  const gridProps = useMemo(() => (extra ? { ...flat.gridProps, ...extra } : flat.gridProps), [flat.gridProps, extra]);\n  const providerProps = useMemo(() => (extra ? { ...flat.providerProps, ...extra } : flat.providerProps), [flat.providerProps, extra]);\n  const ungrouped = useMemo(() => ({ ...flat, gridProps, providerProps }), [flat, gridProps, providerProps]);\n  return grouped ? groups.result : ungrouped;\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/use-scroll-rows.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/refresh-guard.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport type { DataChange, DataGridPlugin, DataGridReadState, DataGridStoreWrapper } from \"@/registry/default/components/data-grid/data-grid\";\nimport { rowIdAtViewRow, setCellValue, setServerReshapeHandler, useDataGridStoreApi } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\n/**\n * The rule: a block that lands (refresh, retry or window load) replaces every row it carries, except a row that has a pending\n * cell edit or a save that was in flight at any moment since the request was sent: that row keeps its local value. A row with\n * a pending delete is gone: the answer's copy is dropped and its slot stays empty. A protected row that the answer lacks, such as a\n * pending insert, returns to its own slot when no answer row sits there; otherwise it is hidden, and a counted source refreshes\n * when no pending insert or delete is left. A pages refresh appends such a row at the page end (the page can exceed `pageSize`\n * by pending inserts); a sequential refresh that ends before a pending insert may drop it until its save settles.\n * Everything else is replaced, except the cells that a push wrote after the request was sent: those keep the pushed value. A block shows each id once (the first row of a repeated id in an answer wins) and leaves no hole in its\n * loaded range; rows that moved on the server can mix with older rows until the next refresh settles.\n */\n\n/** The rows an answer must not overwrite: a save is pending, or an edit session is open. */\nexport type ProtectedRows = ReadonlySet<string> | null;\n\ntype Holder = {\n  store: DataGridStoreWrapper | null;\n  generation: number;\n  /** Saves are tracked only while a request is open. */\n  recording: boolean;\n  /** Row id -> generation of its latest save start; holds one entry per saved row, dropped when no request is open. */\n  savedAt: Map<string, number>;\n  /** Rows of a local insert or delete whose save is pending. */\n  structural: Set<string>;\n  /** Called when the last pending insert or delete save settled. */\n  onStructuralSettled: (() => void) | null;\n  /** Called when a row's save starts. */\n  onSaveStarted: (() => void) | null;\n  /** Called when the last saving row leaves `\"saving\"`. */\n  onSavesSettled: (() => void) | null;\n  /** Called when the grid asks for a reshape: `reconcileView()`, an immediate push, or a deferred push that marked a row. */\n  onReshape: ((trigger: \"urgent\" | \"stale\") => void) | null;\n  /** Cells that a push wrote while a request was open: row id -> column id -> value and the generation of the push. Dropped when no request is open. */\n  pushed: Map<string, Map<string, { value: unknown; at: number }>>;\n  trackUnacknowledged: boolean;\n  /** Rows with a local edit or insert that no save and no landed block has acknowledged; eviction keeps them. */\n  unacknowledged: Set<string>;\n};\n\nfunction setListenerOn(holder: Holder, listener: (() => void) | null) {\n  holder.onStructuralSettled = listener;\n}\n\nfunction setSaveListenerOn(holder: Holder, listener: (() => void) | null) {\n  holder.onSaveStarted = listener;\n}\n\nfunction setSettledListenerOn(holder: Holder, listener: (() => void) | null) {\n  holder.onSavesSettled = listener;\n}\n\nfunction setReshapeOn(holder: Holder, listener: ((trigger: \"urgent\" | \"stale\") => void) | null) {\n  holder.onReshape = listener;\n}\n\nfunction hasSaving(status: ReadonlyMap<string, string>): boolean {\n  for (const value of status.values()) if (value === \"saving\") return true;\n  return false;\n}\n\nfunction trackStructural(holder: Holder, change: { source: string; ops: readonly { type: string; rowId: string }[] }) {\n  if (change.source === \"stream\" || change.source === \"rollback\") return;\n  const status = holder.store?.getState().saveStatus;\n  for (const op of change.ops) if ((op.type === \"insert\" || op.type === \"delete\") && status?.get(op.rowId) === \"saving\") holder.structural.add(op.rowId);\n}\n\nfunction trackUnacknowledgedRows(holder: Holder, change: { source: string; ops: readonly { type: string; rowId: string }[] }) {\n  if (!holder.trackUnacknowledged || change.source === \"stream\" || change.source === \"rollback\") return;\n  for (const op of change.ops) {\n    if (op.type === \"update\" || op.type === \"insert\") holder.unacknowledged.add(op.rowId);\n    else if (op.type === \"delete\") holder.unacknowledged.delete(op.rowId);\n  }\n}\n\nfunction trackPushedCells(holder: Holder, change: { source: string; ops: readonly { type: string; rowId: string; cells?: readonly { columnId: string; value: unknown }[] }[] }) {\n  if (!holder.recording || change.source !== \"stream\") return;\n  for (const op of change.ops) {\n    if (op.type !== \"update\" || !op.cells) continue;\n    const at = ++holder.generation;\n    let cells = holder.pushed.get(op.rowId);\n    if (!cells) holder.pushed.set(op.rowId, (cells = new Map<string, { value: unknown; at: number }>()));\n    for (const cell of op.cells) cells.set(cell.columnId, { value: cell.value, at });\n  }\n}\n\nfunction pushedSinceOn(holder: Holder, generation: number): ReadonlyMap<string, ReadonlyMap<string, unknown>> | null {\n  let rows: Map<string, Map<string, unknown>> | null = null;\n  for (const [rowId, cells] of holder.pushed) {\n    let fresh: Map<string, unknown> | null = null;\n    for (const [columnId, cell] of cells) if (cell.at > generation) (fresh ??= new Map()).set(columnId, cell.value);\n    if (fresh) (rows ??= new Map()).set(rowId, fresh);\n  }\n  return rows;\n}\n\nfunction trackSaves(holder: Holder, state: DataGridReadState, prev: DataGridReadState) {\n  if (state.saveStatus === prev.saveStatus) return;\n  if (holder.unacknowledged.size > 0) {\n    for (const [id, status] of prev.saveStatus) if (status === \"saving\" && state.saveStatus.get(id) !== \"saving\") holder.unacknowledged.delete(id);\n  }\n  if (holder.structural.size > 0) {\n    for (const [id, status] of prev.saveStatus) {\n      if (status === \"saving\" && state.saveStatus.get(id) !== \"saving\" && holder.structural.delete(id) && holder.structural.size === 0) holder.onStructuralSettled?.();\n    }\n  }\n  let started = false;\n  for (const [id, status] of state.saveStatus) {\n    if (status !== \"saving\" || prev.saveStatus.get(id) === \"saving\") continue;\n    started = true;\n    if (holder.recording) holder.savedAt.set(id, ++holder.generation);\n  }\n  if (started) {\n    holder.onSaveStarted?.();\n  }\n  if (holder.onSavesSettled && hasSaving(prev.saveStatus) && !hasSaving(state.saveStatus)) holder.onSavesSettled();\n}\n\nfunction savedSinceOn(holder: Holder, generation: number): ProtectedRows {\n  let ids: Set<string> | null = null;\n  for (const [id, at] of holder.savedAt) if (at > generation) (ids ??= new Set()).add(id);\n  return ids;\n}\n\nfunction markSavesOn(holder: Holder): number {\n  holder.recording = true;\n  return holder.generation;\n}\n\nfunction pruneSavesOn(holder: Holder, oldestGeneration: number | null) {\n  holder.recording = oldestGeneration !== null;\n  if (oldestGeneration === null) {\n    holder.savedAt.clear();\n    holder.pushed.clear();\n    return;\n  }\n  for (const [id, at] of holder.savedAt) if (at <= oldestGeneration) holder.savedAt.delete(id);\n  for (const [id, cells] of holder.pushed) {\n    for (const [columnId, cell] of cells) if (cell.at <= oldestGeneration) cells.delete(columnId);\n    if (cells.size === 0) holder.pushed.delete(id);\n  }\n}\n\nfunction createGuardPlugin(holder: Holder): DataGridPlugin<unknown> {\n  function RefreshGuardMount() {\n    const store = useDataGridStoreApi();\n    useEffect(() => {\n      holder.store = store;\n      const unsubscribe = store.subscribe((state, prev) => trackSaves(holder, state, prev));\n      setServerReshapeHandler(store, (trigger) => holder.onReshape?.(trigger));\n      return () => {\n        setServerReshapeHandler(store, null);\n        unsubscribe();\n        holder.store = null;\n      };\n    }, [store]);\n    return null;\n  }\n  return {\n    name: \"server-rows-refresh-guard\",\n    Mount: RefreshGuardMount,\n    onDataChange: (_next, change) => {\n      trackStructural(holder, change);\n      trackUnacknowledgedRows(holder, change);\n      trackPushedCells(holder, change);\n    },\n  };\n}\n\nexport type RefreshGuardOptions = {\n  /** Remember rows with a local change that no save acknowledged, for `evictionProtected`. Scroll mode only. */\n  trackUnacknowledged?: boolean;\n};\n\n/** A plugin that gives the hook, which sits outside the provider, read access to the grid's save status and edit session. */\nexport function useRefreshGuard({ trackUnacknowledged = false }: RefreshGuardOptions = {}) {\n  const [holder] = useState<Holder>(() => ({ store: null, generation: 0, recording: false, savedAt: new Map(), structural: new Set(), onStructuralSettled: null, onSaveStarted: null, onSavesSettled: null, onReshape: null, pushed: new Map(), trackUnacknowledged, unacknowledged: new Set() }));\n  const [plugins] = useState(() => [createGuardPlugin(holder)]);\n  const savingRows = useCallback((): ProtectedRows => {\n    const state = holder.store?.getState();\n    if (!state) return null;\n    const ids = new Set<string>();\n    for (const [rowId, status] of state.saveStatus) if (status === \"saving\") ids.add(rowId);\n    return ids.size > 0 ? ids : null;\n  }, [holder]);\n  const protectedRows = useCallback((): ProtectedRows => {\n    const editing = holder.store?.getState().editing;\n    return editing ? unionIds(savingRows(), new Set([editing.rowId])) : savingRows();\n  }, [holder, savingRows]);\n  const saveMark = useCallback(() => markSavesOn(holder), [holder]);\n  const savedSince = useCallback((mark: number) => savedSinceOn(holder, mark), [holder]);\n  const setSettleListener = useCallback((listener: (() => void) | null) => setListenerOn(holder, listener), [holder]);\n  const setSaveStartListener = useCallback((listener: (() => void) | null) => setSaveListenerOn(holder, listener), [holder]);\n  const setSavesSettledListener = useCallback((listener: (() => void) | null) => setSettledListenerOn(holder, listener), [holder]);\n  const setReshapeListener = useCallback((listener: ((trigger: \"urgent\" | \"stale\") => void) | null) => setReshapeOn(holder, listener), [holder]);\n  const forgetStructural = useCallback(() => {\n    holder.structural.clear();\n    holder.unacknowledged.clear();\n  }, [holder]);\n  const evictionProtected = useCallback((): ProtectedRows => {\n    const ids = holder.unacknowledged.size > 0 ? unionIds(protectedRows(), holder.unacknowledged) : protectedRows();\n    const state = holder.store?.getState();\n    const active = state?.activeCell ? rowIdAtViewRow(state, state.activeCell.row) : undefined;\n    return active === undefined ? ids : unionIds(ids, new Set([active]));\n  }, [holder, protectedRows]);\n  const acknowledge = useCallback((rowId: string) => holder.unacknowledged.delete(rowId), [holder]);\n  const unacknowledgedRows = useCallback((): ReadonlySet<string> | null => (holder.unacknowledged.size > 0 ? holder.unacknowledged : null), [holder]);\n  const pruneSaves = useCallback((oldestMark: number | null) => pruneSavesOn(holder, oldestMark), [holder]);\n  const streamUpdateRow = useCallback(\n    <TData,>(change: DataChange<TData>) => {\n      const columns = holder.store?.getState().columns;\n      return columns ? rowOfStreamUpdate(change, columns) : undefined;\n    },\n    [holder],\n  );\n  const overlayPushed = useCallback(\n    <TData,>(rows: readonly TData[], mark: number, start: number, idOf: (row: TData, index: number) => string): TData[] => {\n      const pushed = pushedSinceOn(holder, mark);\n      const columns = holder.store?.getState().columns;\n      if (pushed === null || !columns) return rows as TData[];\n      const byId = new Map(columns.map((column) => [column.id, column] as const));\n      return rows.map((row, index) => {\n        const cells = row === undefined ? undefined : pushed.get(idOf(row, start + index));\n        if (!cells) return row;\n        let next = row;\n        for (const [columnId, value] of cells) {\n          const column = byId.get(columnId);\n          if (column) next = setCellValue(next, column as never, value as never);\n        }\n        return next;\n      });\n    },\n    [holder],\n  );\n  return { plugins, protectedRows, savingRows, saveMark, savedSince, pruneSaves, overlayPushed, streamUpdateRow, setSettleListener, setSaveStartListener, setSavesSettledListener, setReshapeListener, forgetStructural, evictionProtected, acknowledge, unacknowledgedRows };\n}\n\n/**\n * The row a stream update writes onto the row that `data` holds now. A push made on a row that a block has replaced since carries\n * the whole row it was made on; writing only its cells keeps the old values of the other cells from coming back.\n * `applyChange` calls it with the current row, so it needs no pass of its own over the rows.\n */\nexport function rowOfStreamUpdate<TData>(change: DataChange<TData>, columns: readonly { id: string }[]) {\n  if (change.source !== \"stream\") return undefined;\n  const byId = new Map(columns.map((column) => [column.id, column] as const));\n  return (op: Extract<DataChange<TData>[\"ops\"][number], { type: \"update\" }>, current: TData): TData => {\n    if (!op.cells || current === op.prev) return op.row;\n    let row = current;\n    for (const cell of op.cells) {\n      const column = byId.get(cell.columnId);\n      if (column) row = setCellValue(row, column as never, cell.value as never);\n    }\n    return row;\n  };\n}\n\n/** Applies the rule to an incoming page: a deleted row is dropped, a protected row keeps its local value by id, and a protected row the page lacks stays at the end. */\nexport function keepProtectedRows<TData>(\n  incoming: readonly TData[],\n  current: readonly TData[],\n  guarded: ProtectedRows,\n  deleted: ReadonlySet<string>,\n  keepMissing: boolean,\n  idOf: (row: TData, index: number) => string,\n): TData[] {\n  if (guarded === null && deleted.size === 0) return incoming as TData[];\n  const local = new Map<string, TData>();\n  current.forEach((row, index) => {\n    const id = idOf(row, index);\n    if (guarded?.has(id)) local.set(id, row);\n  });\n  const placed = new Set<string>();\n  const page: TData[] = [];\n  incoming.forEach((row, index) => {\n    const id = idOf(row, index);\n    if (deleted.has(id)) return;\n    placed.add(id);\n    page.push(local.get(id) ?? row);\n  });\n  if (keepMissing) for (const [id, row] of local) if (!placed.has(id) && !deleted.has(id)) page.push(row);\n  return page;\n}\n\n/** Notes the rows a change deleted, and forgets a row that a change inserted again. */\nexport function trackDeletes(deleted: Set<string>, change: { ops: readonly { type: string; rowId: string }[] }) {\n  for (const op of (change.ops as typeof change.ops | undefined) ?? []) {\n    if (op.type === \"delete\") deleted.add(op.rowId);\n    else if (op.type === \"insert\") deleted.delete(op.rowId);\n  }\n}\n\n/** Drops the rows whose delete is no longer pending. */\nexport function pruneIds(ids: Set<string>, stillSaving: ProtectedRows) {\n  for (const id of ids) if (!stillSaving?.has(id)) ids.delete(id);\n}\n\n/** The union of two protected sets; either may be `null`. */\nexport function unionIds(a: ProtectedRows, b: ProtectedRows): ProtectedRows {\n  if (a === null) return b;\n  if (b === null || a === b) return a;\n  return new Set([...a, ...b]);\n}\n\nexport type GuardedBlock<TData> = { start: number; rows: readonly (TData | undefined)[]; guard: ProtectedRows };\n\n/** Moves the guarded rows in the given index ranges into `into`, for the block that brings their ids back. */\nexport function stashGuardedRows<TData>(\n  rows: readonly (TData | undefined)[],\n  ranges: readonly { start: number; end: number }[],\n  guarded: ReadonlySet<string>,\n  into: Map<string, TData>,\n  idOf: (row: TData, index: number) => string,\n  orphans: Map<string, { row: TData; slot: number }>,\n) {\n  for (const { start, end } of ranges) {\n    for (let index = start; index < Math.min(end, rows.length); index++) {\n      const row = rows[index];\n      if (row !== undefined && guarded.has(idOf(row, index))) {\n        into.set(idOf(row, index), row);\n        orphans.set(idOf(row, index), { row, slot: index });\n      }\n    }\n  }\n}\n\nfunction findSlot<TData>(rows: readonly (TData | undefined)[], ranges: readonly { start: number; end: number }[], id: string, idOf: (row: TData, index: number) => string, near: number): number {\n  for (const index of [near - 1, near + 1]) {\n    const row = rows[index];\n    if (row !== undefined && idOf(row, index) === id) return index;\n  }\n  for (const { start, end } of ranges) {\n    for (let index = start; index < Math.min(end, rows.length); index++) {\n      const row = rows[index];\n      if (row !== undefined && idOf(row, index) === id) return index;\n    }\n  }\n  return -1;\n}\n\n/**\n * Writes blocks into a copy of `prev`. A block guards the ids it was requested with plus the `live` ones: such a row keeps its\n * local value and appears once, at the index the answer gives it. `displaced` holds a guarded row that an earlier block overwrote,\n * for the block that brings its id back. `cleared` lists the slots left empty because a row moved away from them.\n */\nexport function writeBlocks<TData>(\n  prev: readonly (TData | undefined)[],\n  blocks: readonly GuardedBlock<TData>[],\n  live: ProtectedRows,\n  displaced: Map<string, TData>,\n  ranges: readonly { start: number; end: number }[],\n  idOf: (row: TData, index: number) => string,\n  memory: { orphans: Map<string, { row: TData; slot: number }>; carried: Set<string> },\n  final = false,\n): { rows: (TData | undefined)[]; cleared: number[]; restored: number[] } {\n  const next = prev.slice();\n  const emptied: number[] = [];\n  const restored: number[] = [];\n  const { carried, orphans: overwritten } = memory;\n  const stillProtected = new Set<string>();\n  for (const { start, rows, guard } of blocks) {\n    const guarded = unionIds(guard, live);\n    if (guarded !== null) for (const id of guarded) stillProtected.add(id);\n    for (let i = 0; i < rows.length && start + i < next.length; i++) {\n      const slot = start + i;\n      const incoming = rows[i];\n      if (guarded === null) {\n        next[slot] = incoming;\n        continue;\n      }\n      const occupant = next[slot];\n      const occupantId = occupant === undefined ? undefined : idOf(occupant, slot);\n      const incomingId = incoming === undefined ? undefined : idOf(incoming, slot);\n      if (incomingId !== undefined) carried.add(incomingId);\n      if (incomingId !== undefined && guarded.has(incomingId)) {\n        if (occupantId === incomingId) continue;\n        if (occupantId !== undefined && guarded.has(occupantId)) {\n          displaced.set(occupantId, occupant as TData);\n          overwritten.set(occupantId, { row: occupant as TData, slot });\n        }\n        const from = findSlot(next, ranges, incomingId, idOf, slot);\n        const local = from >= 0 ? next[from] : displaced.get(incomingId);\n        next[slot] = local ?? incoming;\n        if (local !== undefined && from >= 0) {\n          next[from] = undefined;\n          emptied.push(from);\n        }\n        continue;\n      }\n      if (occupantId !== undefined && guarded.has(occupantId)) {\n        displaced.set(occupantId, occupant as TData);\n        overwritten.set(occupantId, { row: occupant as TData, slot });\n      }\n      next[slot] = incoming;\n    }\n  }\n  // Nothing else is loading: a protected row that the answer does not carry (a pending insert) returns to its own slot when no answer row sits there.\n  if (final) {\n    for (const [id, { row, slot }] of overwritten) {\n      if (carried.has(id) || !stillProtected.has(id) || slot >= next.length || next[slot] !== undefined) continue;\n      next[slot] = row;\n      restored.push(slot);\n    }\n  }\n  return { rows: next, cleared: emptied.filter((slot) => next[slot] === undefined), restored };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/refresh-guard.tsx"
    },
    {
      "path": "registry/default/blocks/data-grid-server/parse-server-spec.ts",
      "content": "import type { FilterGroup, FilterNode, FilterOperator, FilterOperatorInput, FilterSpec, ServerSpec, SortSpec } from \"@/registry/default/components/data-grid/data-grid\";\nimport type { GroupKey, GroupPathSegment, ServerAggregate } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { MAX_FILTER_GROUP_DEPTH, MAX_SPEC_SEARCH_LENGTH, MAX_SPEC_SORTS, filterOperatorInput, isBuiltInOperator } from \"@/registry/default/components/data-grid/data-grid-sdk\";\n\n/** What a request may do with one column. Every field is optional. */\nexport type ServerSpecColumnRules = {\n  /** `false` rejects a sort on the column. Default `true`. */\n  sortable?: boolean;\n  /** `false` rejects a filter on the column. Default `true`. */\n  filterable?: boolean;\n  /** Allowed operators. Default: every built-in operator. A custom operator in `customOperators` is allowed whether or not this list names it. */\n  operators?: readonly FilterOperator[];\n  /** Custom operators the column accepts, with the value shape of each. */\n  customOperators?: Readonly<Record<string, FilterOperatorInput>>;\n  /** `false` rejects `groupBy` on the column. Default `true`. */\n  groupable?: boolean;\n  /** `false` rejects an aggregate on the column. Default `true`. */\n  aggregatable?: boolean;\n};\n\n/** Bounds that apply to the whole request. Every field is optional; a negative or non-finite value keeps the default. Groups nest at most 2 levels deep. */\nexport type ServerSpecLimits = {\n  /** Most sort entries. Default 64. */\n  maxSorts?: number;\n  /** Most filter rows in the tree. Default 64. */\n  maxFilters?: number;\n  /** Most filter groups in the tree. Default 16. */\n  maxGroups?: number;\n  /** Longest text of one filter value, one list entry, or one range bound. Default 1000. */\n  maxValueLength?: number;\n  /** Most entries of an `isAnyOf` or `isNoneOf` list. Default 1000. */\n  maxListLength?: number;\n  /** Longest `searchText`. Default 500. */\n  maxSearchLength?: number;\n  /** Most `groupBy` columns. Default 4. */\n  maxGroupLevels?: number;\n  /** Longest group key of a group path. Default 1024. */\n  maxGroupKeyLength?: number;\n  /** Most `aggregates` entries. Default 32. */\n  maxGroupAggregates?: number;\n};\n\nexport type ParseServerSpecOptions = {\n  /** The columns a request may name: a list of ids (no extra rules), or a map from id to its rules. */\n  columns: readonly string[] | Readonly<Record<string, ServerSpecColumnRules>>;\n  limits?: ServerSpecLimits;\n};\n\n/** Thrown by {@link parseServerSpec}. `path` names the offending part of the request, such as `filters[2].value`. */\nexport class ServerSpecError extends Error {\n  readonly path: string;\n  constructor(path: string, message: string) {\n    super(`${path}: ${message}`);\n    this.name = \"ServerSpecError\";\n    this.path = path;\n  }\n}\n\nconst DEFAULT_LIMITS = { maxSorts: MAX_SPEC_SORTS, maxFilters: 64, maxGroups: 16, maxValueLength: 1000, maxListLength: 1000, maxSearchLength: MAX_SPEC_SEARCH_LENGTH, maxGroupLevels: 4, maxGroupKeyLength: 1024, maxGroupAggregates: 32 } satisfies Required<ServerSpecLimits>;\n\ntype Budget = { filters: number; groups: number };\n\ntype Raw = { sorts?: unknown; filters?: unknown; filterJoin?: unknown; not?: unknown; searchText?: unknown; groupBy?: unknown; aggregates?: unknown; columnId?: unknown; direction?: unknown; join?: unknown; operator?: unknown; value?: unknown; matchCase?: unknown };\n\nconst isRecord = (value: unknown): value is Raw => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Turns an untrusted request body into a bounded, typed {@link ServerSpec}, or throws {@link ServerSpecError}. It checks the\n * shape, the column ids, the operators, the value shapes, and the size of the tree, and drops every key it does not know.\n * It does not build a query: map the result to your query layer.\n *\n * @example\n * const spec = parseServerSpec(body.spec, { columns: [\"name\", \"status\", \"age\"] });\n */\nexport function parseServerSpec(input: unknown, options: ParseServerSpecOptions): ServerSpec {\n  const limits = limitsOf(options);\n  const rules = columnRules(options.columns);\n  if (!isRecord(input)) throw new ServerSpecError(\"spec\", \"must be an object\");\n  const spec: ServerSpec = {\n    sorts: parseSorts(input.sorts, rules, limits),\n    filters: parseFilters(input.filters, rules, limits),\n    searchText: parseSearch(input.searchText, limits),\n  };\n  const filterJoin = parseFilterJoin(input.filterJoin);\n  const groupBy = parseGroupBy(input.groupBy, rules, limits);\n  const aggregates = parseAggregates(input.aggregates, groupBy.length > 0, rules, limits);\n  return { ...spec, ...(filterJoin === \"or\" ? { filterJoin } : null), ...(groupBy.length > 0 ? { groupBy } : null), ...(aggregates.length > 0 ? { aggregates } : null) };\n}\n\n/**\n * Reads the `groupPath` and `childKind` of a grouped request against its parsed `spec`, or throws {@link ServerSpecError}. The path follows\n * `spec.groupBy` in order and is not longer; the kind is `\"groups\"` while the path is shorter than `groupBy`, else `\"rows\"`.\n * A spec without `groupBy` accepts an empty path only.\n *\n * @example\n * const { groupPath, childKind } = parseGroupPath(body, spec);\n */\nexport function parseGroupPath(input: unknown, spec: ServerSpec, options: { limits?: ServerSpecLimits } = {}): { groupPath: GroupPathSegment[]; childKind: \"groups\" | \"rows\" } {\n  const groupBy = spec.groupBy ?? [];\n  const limits = limitsOf(options);\n  const body = isRecord(input) ? (input as { groupPath?: unknown; childKind?: unknown }) : {};\n  const rawPath = body.groupPath ?? [];\n  if (!Array.isArray(rawPath)) throw new ServerSpecError(\"groupPath\", \"must be an array\");\n  if (rawPath.length > groupBy.length) throw new ServerSpecError(\"groupPath\", \"is longer than groupBy\");\n  const groupPath = rawPath.map((segment: unknown, index): GroupPathSegment => {\n    const path = `groupPath[${index}]`;\n    if (!isRecord(segment)) throw new ServerSpecError(path, \"must be an object\");\n    const raw = segment as { columnId?: unknown; key?: unknown };\n    if (raw.columnId !== groupBy[index]) throw new ServerSpecError(`${path}.columnId`, \"must follow groupBy in order\");\n    return { columnId: groupBy[index]!, key: groupKey(raw.key, `${path}.key`, limits) };\n  });\n  const childKind = groupPath.length < groupBy.length ? \"groups\" : \"rows\";\n  if (body.childKind !== undefined && body.childKind !== childKind) throw new ServerSpecError(\"childKind\", `must be \"${childKind}\" for a path of ${groupPath.length} of ${groupBy.length} levels`);\n  return { groupPath, childKind };\n}\n\nfunction parseFilterJoin(value: unknown): \"and\" | \"or\" {\n  if (value === undefined || value === \"and\" || value === \"or\") return value ?? \"and\";\n  throw new ServerSpecError(\"filterJoin\", 'must be \"and\" or \"or\"');\n}\n\nfunction limitsOf(options: { limits?: ServerSpecLimits }): Required<ServerSpecLimits> {\n  const limits = { ...DEFAULT_LIMITS };\n  for (const key of Object.keys(DEFAULT_LIMITS) as (keyof ServerSpecLimits)[]) {\n    const wanted = options.limits?.[key];\n    if (wanted !== undefined && Number.isFinite(wanted) && wanted >= 0) limits[key] = wanted;\n  }\n  return limits;\n}\n\nfunction groupKey(value: unknown, path: string, limits: Required<ServerSpecLimits>): GroupKey {\n  if (value === null || typeof value === \"boolean\" || (typeof value === \"number\" && Number.isFinite(value))) return value;\n  if (typeof value !== \"string\") throw new ServerSpecError(path, \"must be a string, a finite number, a boolean, or null\");\n  if (value.length > limits.maxGroupKeyLength) throw new ServerSpecError(path, `is longer than ${limits.maxGroupKeyLength}`);\n  return value;\n}\n\nfunction parseGroupBy(value: unknown, rules: ReadonlyMap<string, ServerSpecColumnRules>, limits: Required<ServerSpecLimits>): string[] {\n  if (value === undefined || value === null) return [];\n  if (!Array.isArray(value)) throw new ServerSpecError(\"groupBy\", \"must be an array\");\n  if (value.length > limits.maxGroupLevels) throw new ServerSpecError(\"groupBy\", `holds more than ${limits.maxGroupLevels} columns`);\n  const seen = new Set<string>();\n  return value.map((entry: unknown, index) => {\n    const path = `groupBy[${index}]`;\n    const columnId = knownColumn(entry, rules, path);\n    if (rules.get(columnId)!.groupable === false) throw new ServerSpecError(path, `\"${columnId}\" cannot be grouped`);\n    if (seen.has(columnId)) throw new ServerSpecError(path, `repeats \"${columnId}\"`);\n    seen.add(columnId);\n    return columnId;\n  });\n}\n\nconst REDUCERS: readonly string[] = [\"sum\", \"avg\", \"min\", \"max\", \"count\"];\n\nfunction parseAggregates(value: unknown, grouped: boolean, rules: ReadonlyMap<string, ServerSpecColumnRules>, limits: Required<ServerSpecLimits>): ServerAggregate[] {\n  if (value === undefined || value === null) return [];\n  if (!Array.isArray(value)) throw new ServerSpecError(\"aggregates\", \"must be an array\");\n  if (value.length === 0) return [];\n  if (!grouped) throw new ServerSpecError(\"aggregates\", \"needs groupBy\");\n  if (value.length > limits.maxGroupAggregates) throw new ServerSpecError(\"aggregates\", `holds more than ${limits.maxGroupAggregates} entries`);\n  const seen = new Set<string>();\n  return value.map((entry: unknown, index) => {\n    const path = `aggregates[${index}]`;\n    if (!isRecord(entry)) throw new ServerSpecError(path, \"must be an object\");\n    const raw = entry as { columnId?: unknown; reducer?: unknown };\n    const columnId = knownColumn(raw.columnId, rules, `${path}.columnId`);\n    if (rules.get(columnId)!.aggregatable === false) throw new ServerSpecError(`${path}.columnId`, `\"${columnId}\" cannot be aggregated`);\n    if (seen.has(columnId)) throw new ServerSpecError(`${path}.columnId`, `repeats \"${columnId}\"`);\n    seen.add(columnId);\n    if (typeof raw.reducer !== \"string\" || !REDUCERS.includes(raw.reducer)) throw new ServerSpecError(`${path}.reducer`, `must be one of ${REDUCERS.join(\", \")}`);\n    return { columnId, reducer: raw.reducer as ServerAggregate[\"reducer\"] };\n  });\n}\n\nfunction columnRules(columns: ParseServerSpecOptions[\"columns\"]): ReadonlyMap<string, ServerSpecColumnRules> {\n  if (Array.isArray(columns)) return new Map((columns as readonly string[]).map((id) => [id, {}]));\n  return new Map(Object.entries(columns as Readonly<Record<string, ServerSpecColumnRules>>));\n}\n\nfunction parseSearch(value: unknown, limits: Required<ServerSpecLimits>): string {\n  if (value === undefined || value === null) return \"\";\n  if (typeof value !== \"string\") throw new ServerSpecError(\"searchText\", \"must be a string\");\n  if (value.length > limits.maxSearchLength) throw new ServerSpecError(\"searchText\", `is longer than ${limits.maxSearchLength}`);\n  return value;\n}\n\nfunction parseSorts(value: unknown, rules: ReadonlyMap<string, ServerSpecColumnRules>, limits: Required<ServerSpecLimits>): SortSpec[] {\n  if (value === undefined || value === null) return [];\n  if (!Array.isArray(value)) throw new ServerSpecError(\"sorts\", \"must be an array\");\n  if (value.length > limits.maxSorts) throw new ServerSpecError(\"sorts\", `holds more than ${limits.maxSorts} entries`);\n  return value.map((entry: unknown, index) => {\n    const path = `sorts[${index}]`;\n    if (!isRecord(entry)) throw new ServerSpecError(path, \"must be an object\");\n    const columnId = knownColumn(entry.columnId, rules, `${path}.columnId`);\n    if (rules.get(columnId)!.sortable === false) throw new ServerSpecError(`${path}.columnId`, `\"${columnId}\" cannot be sorted`);\n    if (entry.direction !== \"asc\" && entry.direction !== \"desc\") throw new ServerSpecError(`${path}.direction`, 'must be \"asc\" or \"desc\"');\n    return { columnId, direction: entry.direction };\n  });\n}\n\nfunction knownColumn(value: unknown, rules: ReadonlyMap<string, ServerSpecColumnRules>, path: string): string {\n  if (typeof value !== \"string\" || !rules.has(value)) throw new ServerSpecError(path, \"names an unknown column\");\n  return value;\n}\n\nfunction parseFilters(value: unknown, rules: ReadonlyMap<string, ServerSpecColumnRules>, limits: Required<ServerSpecLimits>): FilterNode[] {\n  if (value === undefined || value === null) return [];\n  const budget: Budget = { filters: 0, groups: 0 };\n  return parseNodes(value, \"filters\", 0, rules, limits, budget);\n}\n\nfunction parseNodes(value: unknown, path: string, depth: number, rules: ReadonlyMap<string, ServerSpecColumnRules>, limits: Required<ServerSpecLimits>, budget: Budget): FilterNode[] {\n  if (!Array.isArray(value)) throw new ServerSpecError(path, \"must be an array\");\n  return value.map((node: unknown, index) => {\n    const nodePath = `${path}[${index}]`;\n    if (!isRecord(node)) throw new ServerSpecError(nodePath, \"must be an object\");\n    if (Object.hasOwn(node, \"filters\")) return parseGroup(node, nodePath, depth + 1, rules, limits, budget);\n    return parseRow(node, nodePath, rules, limits, budget);\n  });\n}\n\nfunction parseGroup(node: Raw, path: string, depth: number, rules: ReadonlyMap<string, ServerSpecColumnRules>, limits: Required<ServerSpecLimits>, budget: Budget): FilterGroup {\n  if (depth > MAX_FILTER_GROUP_DEPTH) throw new ServerSpecError(path, `nests groups deeper than ${MAX_FILTER_GROUP_DEPTH}`);\n  budget.groups += 1;\n  if (budget.groups > limits.maxGroups) throw new ServerSpecError(path, `holds more than ${limits.maxGroups} groups`);\n  if (node.join !== \"and\" && node.join !== \"or\") throw new ServerSpecError(`${path}.join`, 'must be \"and\" or \"or\"');\n  if (node.not !== undefined && typeof node.not !== \"boolean\") throw new ServerSpecError(`${path}.not`, \"must be a boolean\");\n  const filters = parseNodes(node.filters, `${path}.filters`, depth, rules, limits, budget);\n  return node.not === true ? { join: node.join, not: true, filters } : { join: node.join, filters };\n}\n\nfunction parseRow(node: Raw, path: string, rules: ReadonlyMap<string, ServerSpecColumnRules>, limits: Required<ServerSpecLimits>, budget: Budget): FilterSpec {\n  budget.filters += 1;\n  if (budget.filters > limits.maxFilters) throw new ServerSpecError(path, `holds more than ${limits.maxFilters} filters`);\n  const columnId = knownColumn(node.columnId, rules, `${path}.columnId`);\n  const column = rules.get(columnId)!;\n  if (column.filterable === false) throw new ServerSpecError(`${path}.columnId`, `\"${columnId}\" cannot be filtered`);\n  if (typeof node.operator !== \"string\") throw new ServerSpecError(`${path}.operator`, \"must be a string\");\n  const operator = node.operator;\n  const custom = column.customOperators && Object.hasOwn(column.customOperators, operator) ? column.customOperators[operator] : undefined;\n  const allowed = column.operators ? column.operators.includes(operator) || custom !== undefined : isBuiltInOperator(operator) || custom !== undefined;\n  if (!allowed) throw new ServerSpecError(`${path}.operator`, `\"${operator.slice(0, 40)}\" is not allowed on \"${columnId.slice(0, 40)}\"`);\n  const input = custom ?? filterOperatorInput(operator);\n  const value = parseValue(node.value, input, `${path}.value`, limits);\n  const row: FilterSpec = value === undefined ? { columnId, operator } : { columnId, operator, value };\n  return node.matchCase === true ? { ...row, matchCase: true } : row;\n}\n\nfunction text(value: unknown, path: string, limits: Required<ServerSpecLimits>): string {\n  if (typeof value !== \"string\") throw new ServerSpecError(path, \"must be a string\");\n  if (value.length > limits.maxValueLength) throw new ServerSpecError(path, `is longer than ${limits.maxValueLength}`);\n  return value;\n}\n\nfunction parseValue(value: unknown, input: FilterOperatorInput, path: string, limits: Required<ServerSpecLimits>): FilterSpec[\"value\"] {\n  if (input === \"none\") return undefined;\n  if (input === \"single\") return text(value, path, limits);\n  if (!Array.isArray(value)) throw new ServerSpecError(path, \"must be an array\");\n  if (input === \"range\") {\n    if (value.length !== 2) throw new ServerSpecError(path, \"must hold two bounds\");\n    return [text(value[0], `${path}[0]`, limits), text(value[1], `${path}[1]`, limits)];\n  }\n  if (value.length > limits.maxListLength) throw new ServerSpecError(path, `holds more than ${limits.maxListLength} entries`);\n  return value.map((entry: unknown, index) => text(entry, `${path}[${index}]`, limits));\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/parse-server-spec.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/save-refresh.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useLayoutEffect, useRef } from \"react\";\nimport type { DataChange, SaveAck, SaveContext } from \"@/registry/default/components/data-grid/data-grid\";\n\n/** What `refreshAfterSave` sees when it decides: the saves that settled since the last refresh. */\nexport type SaveRefreshReport = {\n  /** Saves the server accepted (`onSave` returned a promise that resolved with nothing or without `rejected`). */\n  saved: number;\n  /** Saves that resolved with `{ rejected }`. */\n  rejected: number;\n  /** Saves whose `onSave` threw or whose promise rejected. */\n  failed: number;\n  /** The changes of those saves, oldest first, at most 100, for a policy that decides per change. */\n  changes: readonly DataChange<unknown>[];\n  /** Saves still in flight when the decision runs; above 0 only when the 10 second wait forced it. */\n  pending: number;\n};\n\n/**\n * When the hook fetches again after `onSave` settles.\n * - `\"settled\"`: once, after every save in flight has settled (or after 10 seconds, so one stuck save cannot stop the refresh). A burst of saves costs one request. After the 10 seconds, each save still in flight refreshes when it settles, until a new save starts a new wait.\n * - `\"each\"`: after saves settle, without waiting for the saves still in flight. Saves that settle in the same task share one refresh.\n * - `false`: never. Call `refresh()` yourself.\n * - a function: once after every save in flight has settled (or after the same 10 seconds), when it returns `true`. A throw counts as `false`.\n *\n * Only a promise from `onSave` counts as a save: a handler that returns nothing has not told the grid when the server has the change, so it never triggers a refresh (call `refresh()` yourself). A refresh needs at least one save the server answered; saves that all threw skip it.\n */\nexport type SaveRefreshPolicy = false | \"each\" | \"settled\" | ((report: SaveRefreshReport) => boolean);\n\nexport type SaveRefreshOptions<TData> = {\n  /** Saves a change. Spread through `gridProps.onSave`; it behaves as the `DataGridProvider` prop of the same name. */\n  onSave?: (change: DataChange<TData>, ctx: SaveContext) => void | Promise<SaveAck<TData>>;\n  /** Default `\"settled\"` while `onSave` is set. */\n  refreshAfterSave?: SaveRefreshPolicy;\n};\n\nconst isThenable = (value: unknown): value is PromiseLike<unknown> => typeof (value as PromiseLike<unknown> | null)?.then === \"function\";\n\n/** Longest wait for saves in flight before the `\"settled\"` policies decide anyway, so one save that never settles cannot stop every later refresh. */\nexport const SAVE_REFRESH_MAX_WAIT_MS = 10_000;\n\ntype SaveFn<TData> = (change: DataChange<TData>, ctx: SaveContext) => void | Promise<SaveAck<TData>>;\n\n/**\n * Wraps the caller's `onSave` so the hook refreshes after saves settle by the caller's policy. `onSave` is `undefined` without an\n * `onSave` option, so spreading `gridProps` never overrides a provider `onSave` of your own. `wrapSave` tracks a provider `onSave` the same way.\n */\nexport function useSaveRefresh<TData>(options: SaveRefreshOptions<TData> = {}, refresh: (report: SaveRefreshReport) => void): { onSave: SaveFn<TData> | undefined; wrapSave: (save: SaveFn<TData>) => SaveFn<TData> } {\n  const live = useRef({ options, refresh });\n  useLayoutEffect(() => {\n    live.current = { options, refresh };\n  });\n  const state = useRef({ inflight: 0, counts: { saved: 0, rejected: 0, failed: 0 }, changes: [] as DataChange<unknown>[], scheduled: false, settleTimer: null as ReturnType<typeof setTimeout> | null, mounted: true, waitExpired: false, maxWait: null as ReturnType<typeof setTimeout> | null });\n  useEffect(() => {\n    state.current.mounted = true;\n    return () => {\n      const current = state.current;\n      current.mounted = false;\n      if (current.maxWait !== null) clearTimeout(current.maxWait);\n      if (current.settleTimer !== null) clearTimeout(current.settleTimer);\n      current.maxWait = null;\n      current.settleTimer = null;\n      current.scheduled = false;\n    };\n  }, []);\n\n  const decide = useCallback((force = false) => {\n    const current = state.current;\n    current.scheduled = false;\n    current.settleTimer = null;\n    if (current.maxWait !== null && (force || current.inflight === 0)) {\n      clearTimeout(current.maxWait);\n      current.maxWait = null;\n    }\n    if (!current.mounted) return;\n    const policy = live.current.options.refreshAfterSave ?? \"settled\";\n    if (policy === false) {\n      current.counts = { saved: 0, rejected: 0, failed: 0 };\n      current.changes = [];\n      return;\n    }\n    if (policy !== \"each\" && current.inflight > 0 && !force) return;\n    if (current.counts.saved + current.counts.rejected === 0) {\n      current.counts = { saved: 0, rejected: 0, failed: 0 };\n      current.changes = [];\n      if (force) current.waitExpired = true;\n      return;\n    }\n    current.waitExpired = (force || current.waitExpired) && current.inflight > 0;\n    const report: SaveRefreshReport = { ...current.counts, changes: current.changes, pending: current.inflight };\n    current.counts = { saved: 0, rejected: 0, failed: 0 };\n    current.changes = [];\n    if (typeof policy === \"function\") {\n      let wanted = false;\n      try {\n        wanted = policy(report);\n      } catch (error) {\n        console.error(\"[data-grid-server] refreshAfterSave threw\", error);\n      }\n      if (!wanted) return;\n    }\n    live.current.refresh(report);\n  }, []);\n\n  const settle = useCallback(\n    (kind: \"saved\" | \"rejected\" | \"failed\", change: DataChange<TData>) => {\n      const current = state.current;\n      current.counts[kind] += 1;\n      if (current.changes.length < 100) current.changes.push(change);\n      if (current.scheduled) return;\n      current.scheduled = true;\n      current.settleTimer = setTimeout(() => decide(current.waitExpired), 0); // after the grid has settled the row, so the refresh sees it as saved\n    },\n    [decide],\n  );\n\n  const hasSave = options.onSave !== undefined;\n  const track = useCallback(\n    (run: SaveFn<TData>, change: DataChange<TData>, ctx: SaveContext): void | Promise<SaveAck<TData>> => {\n      let result: void | Promise<SaveAck<TData>>;\n      try {\n        result = run(change, ctx);\n      } catch (error) {\n        settle(\"failed\", change);\n        throw error;\n      }\n      if (!isThenable(result)) return result;\n      state.current.inflight += 1;\n      if (state.current.maxWait === null) {\n        state.current.waitExpired = false;\n        state.current.maxWait = setTimeout(() => decide(true), SAVE_REFRESH_MAX_WAIT_MS);\n      }\n      return Promise.resolve(result).then(\n        (ack) => {\n          state.current.inflight -= 1;\n          settle(ack && (ack.rejected?.length ?? 0) > 0 ? \"rejected\" : \"saved\", change);\n          return ack;\n        },\n        (error: unknown) => {\n          state.current.inflight -= 1;\n          settle(\"failed\", change);\n          throw error;\n        },\n      );\n    },\n    [settle, decide],\n  );\n  const onSave = useCallback(\n    (change: DataChange<TData>, ctx: SaveContext) => {\n      const run = live.current.options.onSave;\n      return run ? track(run, change, ctx) : undefined;\n    },\n    [track],\n  );\n  const wrapSave = useCallback((save: SaveFn<TData>): SaveFn<TData> => (change, ctx) => track(save, change, ctx), [track]);\n  return { onSave: hasSave ? onSave : undefined, wrapSave };\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/save-refresh.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/read-answer.ts",
      "content": "import type { RowRange, ServerSpec } from \"@/registry/default/components/data-grid/data-grid\";\nimport type { GroupPathSegment } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport type { ServerGroupsAnswer } from \"./read-groups-answer\";\n\n/** Largest row count the server contract accepts; a bigger count clamps to it. */\nexport const MAX_ROW_COUNT = 10_000_000;\n\n/** Why a request runs: `\"load\"` for a window, page, or spec; `\"refresh\"` for `refresh()`, a timed refresh, or a reshape; `\"save\"` after a save settled; `\"retry\"` for `retry()`. */\nexport type FetchReason = \"load\" | \"refresh\" | \"save\" | \"retry\";\n\n/** What `fetchRows` receives in every mode. */\nexport type ServerRowsRequest<TCursor = never> = {\n  /** The sort, filter, and search of this request. */\n  spec: ServerSpec;\n  /** Index of the first requested row in the result. */\n  start: number;\n  /** One past the last requested row; `end - start` is the limit. */\n  end: number;\n  /** Cursor sources: the `nextCursor` of the block or page before; `undefined` for the first one and for every other source. */\n  cursor: TCursor | undefined;\n  /** Why this request runs. The hook sends it to nobody: read it to bypass a cache on a refresh. */\n  reason: FetchReason;\n  /** Aborted when a newer request replaces this one, when a scroll-mode block leaves the rendered rows by more than `overscan` plus one block, on a spec change, and on unmount. */\n  signal: AbortSignal;\n  /** Only while `spec.groupBy` is not empty: the group whose children this request reads, outermost first; `[]` is the top level. */\n  groupPath?: readonly GroupPathSegment[];\n  /** Only while `spec.groupBy` is not empty: `\"groups\"` while `groupPath` is shorter than `groupBy`, else `\"rows\"`. */\n  childKind?: \"groups\" | \"rows\";\n};\n\n/** Pages mode adds the page address; `start` is `(page - 1) * pageSize`. */\nexport type ServerRowsPageRequest<TCursor = never> = ServerRowsRequest<TCursor> & {\n  /** 1-based page. */\n  page: number;\n  pageSize: number;\n};\n\n/** What `fetchRows` resolves with in every mode. */\nexport type ServerRowsAnswer<TData, TCursor = never> = {\n  /** At most `end - start` rows, in order from `start`; extra rows are dropped with a development warning. A repeated row id keeps its first row; the later copy leaves its slot empty in random-access scroll mode (a skeleton row), and a sequential source and pages mode drop it. Make the sort total. */\n  rows: TData[];\n  /** Row count of the result. Omitted keeps the last known count; `null` declares it unknown. A value that is not a non-negative integer reads as `null` (dev-warned); a count above 10,000,000 clamps to it. */\n  totalRowCount?: number | null;\n  /** Rows exist after this block. Default: the block came back full. Random access and pages mode ignore it when a count is known; a sequential source ends on `false` also with a count. */\n  hasMore?: boolean;\n  /** Cursor sources: passed back as `cursor`. `null` ends the source. */\n  nextCursor?: TCursor | null;\n};\n\n/** What `fetchRows` of a grouped scroll source resolves with: groups for `childKind: \"groups\"`, rows for `\"rows\"`. */\nexport type ServerFetchAnswer<TData, TCursor = never> = ServerRowsAnswer<TData, TCursor> | ServerGroupsAnswer;\n\n/** An answer after validation. */\nexport type ReadAnswer<TData, TCursor = never> = {\n  /** The answer's rows in order; a later copy of a repeated id is `undefined`, so the other rows keep their positions. */\n  rows: (TData | undefined)[];\n  /** `undefined` keeps the last known count. */\n  totalRowCount: number | null | undefined;\n  hasMore: boolean;\n  /** The `hasMore` the answer carried, if any. */\n  hasMoreSent: boolean | undefined;\n  nextCursor: TCursor | null | undefined;\n};\n\n/**\n * Validates an untrusted answer: `rows` must be an array and is cut to the requested size, `totalRowCount` must be a\n * non-negative safe integer (else unknown) and clamps to {@link MAX_ROW_COUNT}. Throws when the answer has no rows array.\n */\nexport function readAnswer<TData, TCursor = never>(\n  answer: unknown,\n  range: RowRange,\n  warn: (kind: string, message: string) => void,\n  idOf?: (row: TData, index: number) => string,\n): ReadAnswer<TData, TCursor> {\n  const raw = answer as Partial<ServerRowsAnswer<TData, TCursor>> | null | undefined;\n  if (!Array.isArray(raw?.rows)) throw new TypeError(\"fetchRows of useDataGridServerRows must resolve with { rows: TData[] }\");\n  const limit = range.end - range.start;\n  let rows: (TData | undefined)[] = raw.rows;\n  if (rows.length > limit) {\n    warn(\"long\", `fetchRows returned ${rows.length} rows for a request of ${limit}; only the first ${limit} are used`);\n    rows = rows.slice(0, limit);\n  }\n  const legacy = raw as { total?: unknown; hasNextPage?: unknown };\n  if ((\"total\" in legacy && !(\"totalRowCount\" in raw)) || \"hasNextPage\" in legacy) {\n    warn(\"legacy\", \"the answer of fetchRows uses `total` or `hasNextPage`; rename them to `totalRowCount` and `hasMore`\");\n  }\n  let totalRowCount: number | null | undefined;\n  if (raw.totalRowCount === undefined) totalRowCount = undefined;\n  else if (raw.totalRowCount === null) totalRowCount = null;\n  else if (typeof raw.totalRowCount === \"number\" && Number.isSafeInteger(raw.totalRowCount) && raw.totalRowCount >= 0) {\n    totalRowCount = Math.min(raw.totalRowCount, MAX_ROW_COUNT);\n    if (totalRowCount !== raw.totalRowCount) warn(\"count\", `totalRowCount ${raw.totalRowCount} is above ${MAX_ROW_COUNT}; using ${MAX_ROW_COUNT}`);\n  } else {\n    totalRowCount = null;\n    warn(\"count\", \"totalRowCount must be a non-negative integer or null; treating the count as unknown\");\n  }\n  const full = rows.length === limit;\n  if (idOf) rows = firstCopies(rows as TData[], idOf, range.start, warn);\n  return {\n    rows,\n    totalRowCount,\n    hasMore: typeof raw.hasMore === \"boolean\" ? raw.hasMore : full,\n    hasMoreSent: typeof raw.hasMore === \"boolean\" ? raw.hasMore : undefined,\n    nextCursor: raw.nextCursor,\n  };\n}\n\n/** Keeps the first row of each id and blanks the later copies, so one answer never puts the same id twice into the grid. */\nfunction firstCopies<TData>(rows: TData[], idOf: (row: TData, index: number) => string, start: number, warn: (kind: string, message: string) => void): (TData | undefined)[] {\n  const seen = new Set<string>();\n  let repeated = false;\n  const kept = rows.map((row, index) => {\n    const id = idOf(row, start + index);\n    if (seen.has(id)) {\n      repeated = true;\n      return undefined;\n    }\n    seen.add(id);\n    return row;\n  });\n  if (repeated) warn(\"duplicate\", \"fetchRows returned a duplicate row id; only the first row of each id is used, so make the sort total (add the row id as a last sort key)\");\n  return kept;\n}\n\n/** Options after the hook filled in the default `getRowId`. */\nexport type WithRowId<TOptions, TData> = TOptions & { getRowId: (row: TData, index: number) => string };\n",
      "type": "registry:component",
      "target": "components/data-grid-server/read-answer.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/read-groups-answer.ts",
      "content": "import type { RowRange } from \"@/registry/default/components/data-grid/data-grid\";\nimport { groupKeyText, type GroupKey, type GroupPathSegment } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { MAX_ROW_COUNT } from \"./read-answer\";\n\n/** What a request asks of the server while the grid is grouped: the children of one group. */\nexport type ServerChildKind = \"groups\" | \"rows\";\n\n/** The group a request reads the children of, outermost first; `[]` is the top level. */\nexport type ServerGroupPath = readonly GroupPathSegment[];\n\n/** One group row of a {@link ServerGroupsAnswer}. */\nexport type ServerGroupRow = {\n  /** The stored value the group shares. `null` is the empty group; the server merges `null` and `\"\"` into it. */\n  key: GroupKey;\n  /** Display text of the key. Default: the text of the column's cell type. Cut to 1,024 characters. */\n  label?: string;\n  /** Direct children: groups of the next level, or rows in a group of the last level. */\n  childCount: number;\n  /** Rows of the result under this group; equals `childCount` on the last level. */\n  totalRowCount: number;\n  /** One value per requested aggregate column id: a finite number, or `null` when no value counted. */\n  aggregates?: Readonly<Record<string, unknown>>;\n};\n\n/** What `fetchRows` resolves with for a request of `childKind: \"groups\"`. */\nexport type ServerGroupsAnswer = {\n  /** At most `end - start` group rows of one level, in order from `start`. */\n  groups: readonly ServerGroupRow[];\n  /** Group rows under the parent. */\n  groupCount: number;\n  /** Top level: the row count of the result. Required there. */\n  totalRowCount?: number;\n};\n\n/** A groups answer after validation. */\nexport type ReadGroupsAnswer = {\n  groups: ServerGroupRow[];\n  groupCount: number;\n  totalRowCount: number | undefined;\n};\n\n/** Longest group key and label the grid accepts. */\nexport const MAX_GROUP_TEXT_LENGTH = 1024;\n\nconst RESERVED_ROW_ID_PREFIXES = [\"__group:\", \"__pinned-\", \"__lazy-unloaded-\"] as const;\n\ntype Warn = (kind: string, message: string) => void;\n\nconst isCount = (value: unknown): value is number => typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n\nfunction count(value: unknown, field: string, warn: Warn): number {\n  if (!isCount(value)) throw new TypeError(`fetchRows answered ${field} that is not a non-negative integer`);\n  if (value <= MAX_ROW_COUNT) return value;\n  warn(\"count\", `${field} ${value} is above ${MAX_ROW_COUNT}; using ${MAX_ROW_COUNT}`);\n  return MAX_ROW_COUNT;\n}\n\nfunction readKey(key: unknown, field: string): GroupKey {\n  if (key === null || typeof key === \"boolean\" || (typeof key === \"number\" && Number.isFinite(key))) return key;\n  if (typeof key === \"string\" && key.length <= MAX_GROUP_TEXT_LENGTH) return key;\n  throw new TypeError(`fetchRows answered ${field} that is not a string of at most ${MAX_GROUP_TEXT_LENGTH} characters, a finite number, a boolean, or null`);\n}\n\nfunction readAggregates(raw: unknown, ids: readonly string[], field: string, warn: Warn): Record<string, unknown> | undefined {\n  if (typeof raw !== \"object\" || raw === null) return undefined;\n  const out = Object.create(null) as Record<string, unknown>;\n  for (const id of ids) {\n    if (!Object.hasOwn(raw, id)) continue;\n    const value = (raw as Record<string, unknown>)[id];\n    if (typeof value === \"number\" && Number.isFinite(value)) out[id] = value;\n    else {\n      out[id] = null;\n      if (value !== null) warn(`aggregate ${id}`, `${field}.aggregates.${id} must be a finite number or null; showing null`);\n    }\n  }\n  return out;\n}\n\n/**\n * Validates an untrusted groups answer. It cuts `groups` to the requested size, bounds keys, labels, counts, and aggregates,\n * and reads only the aggregate ids that the request named. Throws a `TypeError` that names the group and the field when the\n * answer has no `groups` array, a key is invalid or repeated (`1` and `\"1\"` repeat), a count is invalid, or the top level lacks `totalRowCount`.\n */\nexport function readGroupsAnswer(answer: unknown, range: RowRange, options: { topLevel: boolean; aggregateIds: readonly string[] }, warn: Warn): ReadGroupsAnswer {\n  const raw = answer as { groups?: unknown; groupCount?: unknown; totalRowCount?: unknown; rows?: unknown } | null | undefined;\n  if (!Array.isArray(raw?.groups)) {\n    const kind = Array.isArray(raw?.rows) ? \" (it answered rows)\" : \"\";\n    throw new TypeError(`fetchRows must resolve with { groups, groupCount } for childKind \"groups\"${kind}`);\n  }\n  const limit = range.end - range.start;\n  let list: unknown[] = raw.groups;\n  if (list.length > limit) {\n    warn(\"long\", `fetchRows returned ${list.length} groups for a request of ${limit}; only the first ${limit} are used`);\n    list = list.slice(0, limit);\n  }\n  const seen = new Set<string>();\n  const groups = list.map((entry, index): ServerGroupRow => {\n    const field = `groups[${index}]`;\n    if (typeof entry !== \"object\" || entry === null) throw new TypeError(`fetchRows answered ${field} that is not an object`);\n    const item = entry as { key?: unknown; label?: unknown; childCount?: unknown; totalRowCount?: unknown; aggregates?: unknown };\n    const key = readKey(item.key, `${field}.key`);\n    const keyText = groupKeyText(key);\n    if (seen.has(keyText)) throw new TypeError(`fetchRows answered the key ${JSON.stringify(keyText.slice(0, 40))} twice (${field}.key); null and \"\" are one group, and 1 and \"1\" are one group`);\n    seen.add(keyText);\n    let label: string | undefined;\n    if (typeof item.label === \"string\") {\n      label = item.label.slice(0, MAX_GROUP_TEXT_LENGTH);\n      if (label.length !== item.label.length) warn(\"label\", `${field}.label is longer than ${MAX_GROUP_TEXT_LENGTH}; cut`);\n    }\n    const aggregates = readAggregates(item.aggregates, options.aggregateIds, field, warn);\n    return {\n      key,\n      ...(label === undefined ? null : { label }),\n      childCount: count(item.childCount, `${field}.childCount`, warn),\n      totalRowCount: count(item.totalRowCount, `${field}.totalRowCount`, warn),\n      ...(aggregates ? { aggregates } : null),\n    };\n  });\n  const groupCount = count(raw.groupCount, \"groupCount\", warn);\n  if (options.topLevel && raw.totalRowCount === undefined) throw new TypeError(\"fetchRows must answer totalRowCount with the top level of groups\");\n  return { groups, groupCount, totalRowCount: raw.totalRowCount === undefined ? undefined : count(raw.totalRowCount, \"totalRowCount\", warn) };\n}\n\n/** Throws when a row id starts with a prefix the grid reserves for group rows, pinned rows, and unloaded rows. */\nexport function assertRowIdsNotReserved(ids: Iterable<string>): void {\n  for (const id of ids) {\n    if (RESERVED_ROW_ID_PREFIXES.some((prefix) => id.startsWith(prefix))) throw new TypeError(`fetchRows returned the row id ${JSON.stringify(id.slice(0, 40))}, which starts with a prefix the grid reserves (${RESERVED_ROW_ID_PREFIXES.join(\", \")})`);\n  }\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/read-groups-answer.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/server-state.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { DataGridPlugin, FilterNode, ServerSpec, SortSpec } from \"@/registry/default/components/data-grid/data-grid\";\nimport { isDev, registerServerWiring } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { DEFAULT_RESHAPE_DELAY, MIN_RESHAPE_DELAY, MIN_REVALIDATE_INTERVAL, readReshapeDelay, readRevalidateInterval } from \"./fetch-hygiene\";\n\n/** The request state every mode of `useDataGridServerRows` returns. */\nexport type DataSourceState = {\n  /** `\"error\"` wins over `\"loading\"`. */\n  status: \"loading\" | \"error\" | \"ready\";\n  /** A request of the current spec is in flight. */\n  loading: boolean;\n  /** The latest failure of the current spec, or `null`. */\n  error: unknown;\n  /** Repeats the failed requests. Does nothing without an error. */\n  retry: () => void;\n  /** Fetches what is in view again and keeps it on screen until the answer lands. The hook calls it after saves settle by `refreshAfterSave`. */\n  refresh: () => void;\n  /** Asks the server to place the rows again after a push: one `refresh()` on the next frame, or after `reshapeDelayMs`. Calls in one frame join. */\n  reshape: () => void;\n};\n\n/** Runs `callback` on the next animation frame, or after 16 ms where there is none. Returns the cancel. */\nexport function scheduleFrame(callback: () => void): () => void {\n  if (typeof requestAnimationFrame === \"function\") {\n    const id = requestAnimationFrame(callback);\n    return () => cancelAnimationFrame(id);\n  }\n  const id = setTimeout(callback, 16);\n  return () => clearTimeout(id);\n}\n\nconst EMPTY_SPEC: ServerSpec = { sorts: [], filters: [], searchText: \"\" };\n\n/** Controlled or uncontrolled state with a stable setter that always calls the latest `onChange`. */\nexport function useControlled<T>(controlled: T | undefined, initial: () => T, onChange: ((next: T) => void) | undefined) {\n  const [inner, setInner] = useState(initial);\n  const latest = useRef({ controlled, onChange });\n  useLayoutEffect(() => {\n    latest.current = { controlled, onChange };\n  });\n  const set = useCallback((next: T) => {\n    if (latest.current.controlled === undefined) setInner(next);\n    latest.current.onChange?.(next);\n  }, []);\n  return [controlled ?? inner, set, setInner] as const;\n}\n\n/** Runs a consumer callback so that a throw cannot break the caller's bookkeeping. */\nexport function isolate(label: string, call: () => void) {\n  try {\n    call();\n  } catch (error) {\n    console.error(`[data-grid-server] ${label} threw`, error);\n  }\n}\n\n/** The refresh guard first, then the consumer's plugins; the array keeps its identity while `own` does. */\nexport function useMountedPlugins(guard: readonly DataGridPlugin<unknown>[], own?: readonly DataGridPlugin<unknown>[]) {\n  return useMemo(() => (own && own.length > 0 ? [...guard, ...own] : guard), [guard, own]);\n}\n\nexport type ServerSpecOptions = {\n  spec?: ServerSpec;\n  defaultSpec?: Partial<ServerSpec> | (() => Partial<ServerSpec> | undefined);\n  onSpecChange?: (spec: ServerSpec) => void;\n};\n\n/** The sort, filter, and search of a server source, with stable change handlers for the grid's controlled state. */\nexport function useServerSpec(source: ServerSpecOptions, afterChange: () => void, groups = false) {\n  const lateSeed = typeof source.defaultSpec === \"function\" && source.spec === undefined ? source.defaultSpec : null;\n  const [spec, setSpec, seedSpec] = useControlled<ServerSpec>(source.spec, () => specOf(lateSeed ? undefined : (source.defaultSpec as Partial<ServerSpec> | undefined), groups), source.onSpecChange);\n  const [ready, setReady] = useState(lateSeed === null);\n  const lateSeedRef = useRef(lateSeed);\n  // A function seed runs after mount, on the client only, so the server render and the first client render match.\n  useLayoutEffect(() => {\n    const seed = lateSeedRef.current;\n    if (seed) {\n      let value: Partial<ServerSpec> | undefined;\n      isolate(\"defaultSpec\", () => (value = seed()));\n      if (value) seedSpec(specOf(value, groups));\n    }\n    setReady(true);\n  }, [seedSpec, groups]);\n  const live = useRef({ spec, afterChange });\n  useLayoutEffect(() => {\n    live.current = { spec, afterChange };\n  });\n  const changeSpec = useCallback(\n    (next: Partial<ServerSpec>) => {\n      const merged = { ...live.current.spec, ...next };\n      if (merged.groupBy?.length === 0) delete merged.groupBy;\n      if (merged.filterJoin !== \"or\") delete merged.filterJoin;\n      // Two changes in one effect (a URL restore) merge instead of overwriting each other.\n      live.current.spec = merged;\n      setSpec(merged);\n      live.current.afterChange();\n    },\n    [setSpec],\n  );\n  const onSortChange = useCallback((sorts: SortSpec[]) => changeSpec({ sorts }), [changeSpec]);\n  const onFilterChange = useCallback((filters: FilterNode[]) => changeSpec({ filters }), [changeSpec]);\n  const onFilterJoinChange = useCallback((join: \"and\" | \"or\") => changeSpec({ filterJoin: join === \"or\" ? \"or\" : undefined }), [changeSpec]);\n  const onSearchTextChange = useCallback((searchText: string) => changeSpec({ searchText }), [changeSpec]);\n  const onGroupByChange = useCallback((groupBy: readonly string[]) => changeSpec({ groupBy }), [changeSpec]);\n  return { spec, ready, onSortChange, onFilterChange, onFilterJoinChange, onSearchTextChange, onGroupByChange };\n}\n\n/** The result of {@link useServerSpec}: the scroll hook takes it from its caller so the group engine and the flat engine share one spec. */\nexport type ServerSpecState = ReturnType<typeof useServerSpec>;\n\nconst specOf = (seed?: Partial<ServerSpec>, groups = false): ServerSpec => ({\n  sorts: [...(seed?.sorts ?? EMPTY_SPEC.sorts)],\n  filters: [...(seed?.filters ?? EMPTY_SPEC.filters)],\n  ...(seed?.filterJoin === \"or\" ? { filterJoin: \"or\" as const } : null),\n  searchText: seed?.searchText ?? EMPTY_SPEC.searchText,\n  ...(groups && seed?.groupBy?.length ? { groupBy: [...seed.groupBy] } : null),\n  ...(groups && seed?.aggregates?.length ? { aggregates: [...seed.aggregates] } : null),\n});\n\ntype RevalidationInput = {\n  /** The `revalidateIntervalMs` option as the consumer passed it. */\n  interval: unknown;\n  /** Runs the refresh when a tick is due. */\n  onTick: () => void;\n  /** A request is in flight: a due tick waits until this turns false and then runs once. */\n  busy: boolean;\n  /** `false` skips the tick and waits for the next one. */\n  canTick?: () => boolean;\n  /** A change restarts the clock. */\n  resetKey: string;\n};\n\n/**\n * Runs `onTick` every `interval` ms while the page is visible. The clock chains `setTimeout`, so ticks never stack, and\n * `restart` (called by every refresh) pushes the next tick a full interval away. Returns `restart`.\n */\nexport function useRevalidation({ interval: raw, onTick, busy, canTick, resetKey }: RevalidationInput) {\n  const { interval, invalid, raised } = readRevalidateInterval(raw);\n  const live = useRef({ interval, onTick, busy, canTick });\n  useLayoutEffect(() => {\n    live.current = { interval, onTick, busy, canTick };\n  });\n  const clock = useRef<{ timer: ReturnType<typeof setTimeout> | null; deadline: number; waiting: boolean; warned: boolean; warnedRaised: boolean }>({ timer: null, deadline: 0, waiting: false, warned: false, warnedRaised: false });\n\n  const fireRef = useRef<() => void>(() => {});\n  const arm = useCallback(() => {\n    const state = clock.current;\n    if (state.timer !== null) clearTimeout(state.timer);\n    state.timer = null;\n    const { interval: ms } = live.current;\n    if (ms === null || typeof document === \"undefined\" || document.visibilityState === \"hidden\") return;\n    state.timer = setTimeout(() => {\n      state.timer = null;\n      fireRef.current();\n    }, Math.max(0, state.deadline - Date.now()));\n  }, []);\n\n  const restart = useCallback(() => {\n    clock.current.deadline = Date.now() + (live.current.interval ?? 0);\n    clock.current.waiting = false;\n    arm();\n  }, [arm]);\n\n  const fire = useCallback(() => {\n    if (live.current.busy) {\n      clock.current.waiting = true;\n      return;\n    }\n    if (!live.current.canTick || live.current.canTick()) live.current.onTick();\n    restart();\n  }, [restart]);\n  useLayoutEffect(() => {\n    fireRef.current = fire;\n  }, [fire]);\n\n  useEffect(() => {\n    if (invalid && isDev() && !clock.current.warned) {\n      clock.current.warned = true;\n      console.warn(\"[data-grid-server] revalidateIntervalMs must be a number of milliseconds above 0, so revalidation is off\");\n    }\n  }, [invalid]);\n\n  useEffect(() => {\n    if (raised && isDev() && !clock.current.warnedRaised) {\n      clock.current.warnedRaised = true;\n      console.warn(`[data-grid-server] revalidateIntervalMs below ${MIN_REVALIDATE_INTERVAL} ms is raised to ${MIN_REVALIDATE_INTERVAL} ms`);\n    }\n  }, [raised]);\n\n  useEffect(() => {\n    if (interval === null || typeof document === \"undefined\") return;\n    restart();\n    const onVisibility = () => {\n      if (document.visibilityState === \"hidden\") {\n        if (clock.current.timer !== null) clearTimeout(clock.current.timer);\n        clock.current.timer = null;\n      } else if (Date.now() >= clock.current.deadline) fire();\n      else arm();\n    };\n    document.addEventListener(\"visibilitychange\", onVisibility);\n    return () => {\n      document.removeEventListener(\"visibilitychange\", onVisibility);\n      if (clock.current.timer !== null) clearTimeout(clock.current.timer);\n      clock.current.timer = null;\n    };\n    // `resetKey` restarts the clock.\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [interval, resetKey, restart, arm, fire]);\n\n  useEffect(() => {\n    if (!busy && clock.current.waiting) {\n      clock.current.waiting = false;\n      // A hidden page leaves the due tick to the visibility handler.\n      if (typeof document !== \"undefined\" && document.visibilityState !== \"hidden\") fire();\n    }\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [busy]);\n\n  return restart;\n}\n\ntype ReshapeInput = {\n  /** The `reshapeDelayMs` option as the consumer passed it. */\n  delay: unknown;\n  /** The spec has a sort or a filter, so a pushed row can belong elsewhere: `delay` defaults to {@link DEFAULT_RESHAPE_DELAY}. */\n  ordered: boolean;\n  /** Runs the refresh when a reshape is due. */\n  run: () => void;\n  /** A request is in flight: a due reshape waits until this turns false and then runs once. */\n  busy: boolean;\n  /** `false` drops a due reshape. */\n  canRun?: () => boolean;\n  /** A change cancels the pending reshape: the request it starts fetches the rows anyway. */\n  resetKey: string;\n  warn: (kind: string, message: string) => void;\n};\n\n/** `\"stale\"` comes from a deferred push, `\"soon\"` from a stream delete or `reshape()`, `\"urgent\"` from `reconcileView()` or an immediate push. */\nexport type ReshapeTrigger = \"stale\" | \"soon\" | \"urgent\";\n\n/**\n * Schedules the refresh that places pushed rows again. With `reshapeDelayMs`, `\"stale\"` and `\"soon\"` triggers start or join one\n * timer, so a steady feed reshapes at most once per delay; without it `\"stale\"` triggers do nothing and `\"soon\"` runs on the next\n * frame. `\"urgent\"` always runs on the next frame. A reshape that falls due during a request or while the page is hidden waits and runs once.\n */\nexport function useReshape({ delay: raw, ordered, run, busy, canRun, resetKey, warn }: ReshapeInput) {\n  const { delay, invalid, raised } = readReshapeDelay(raw);\n  const staleDelay = delay ?? (raw === undefined && ordered ? DEFAULT_RESHAPE_DELAY : null);\n  const live = useRef({ delay, staleDelay, run, busy, canRun, warn });\n  useLayoutEffect(() => {\n    live.current = { delay, staleDelay, run, busy, canRun, warn };\n  });\n  const pending = useRef<{ timer: ReturnType<typeof setTimeout> | null; cancelFrame: (() => void) | null; waiting: boolean }>({ timer: null, cancelFrame: null, waiting: false });\n\n  const cancel = useCallback(() => {\n    const state = pending.current;\n    if (state.timer !== null) clearTimeout(state.timer);\n    state.cancelFrame?.();\n    state.timer = null;\n    state.cancelFrame = null;\n    state.waiting = false;\n  }, []);\n\n  const due = useCallback(() => {\n    const state = pending.current;\n    if (live.current.busy || (typeof document !== \"undefined\" && document.visibilityState === \"hidden\")) {\n      state.waiting = true;\n      return;\n    }\n    state.waiting = false;\n    if (!live.current.canRun || live.current.canRun()) live.current.run();\n  }, []);\n\n  const request = useCallback(\n    (trigger: ReshapeTrigger) => {\n      const state = pending.current;\n      const ms = trigger === \"stale\" ? live.current.staleDelay : live.current.delay;\n      if (trigger === \"stale\" || (trigger === \"soon\" && ms !== null)) {\n        if (ms === null || state.timer !== null) return;\n        state.timer = setTimeout(() => {\n          state.timer = null;\n          due();\n        }, ms);\n        return;\n      }\n      if (state.cancelFrame !== null) return;\n      state.cancelFrame = scheduleFrame(() => {\n        state.cancelFrame = null;\n        due();\n      });\n    },\n    [due],\n  );\n\n  useEffect(() => {\n    if (invalid) live.current.warn(\"reshapeDelayMs\", \"reshapeDelayMs must be a number of milliseconds above 0, so the reshape delay is off\");\n    else if (raised) live.current.warn(\"reshapeDelayMs\", `reshapeDelayMs below ${MIN_RESHAPE_DELAY} ms is raised to ${MIN_RESHAPE_DELAY} ms`);\n  }, [invalid, raised]);\n\n  useEffect(() => {\n    const onVisibility = () => {\n      if (document.visibilityState !== \"hidden\" && pending.current.waiting) due();\n    };\n    document.addEventListener(\"visibilitychange\", onVisibility);\n    return () => {\n      document.removeEventListener(\"visibilitychange\", onVisibility);\n      cancel();\n    };\n  }, [due, cancel]);\n\n  useEffect(() => {\n    cancel();\n  }, [resetKey, cancel]);\n\n  useEffect(() => {\n    if (!busy && pending.current.waiting) due();\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [busy]);\n\n  return { request, cancel };\n}\n\ntype WiringSave = Parameters<typeof registerServerWiring>[1][\"wrapSave\"];\n\n/** Registers during render, not in `useMemo`: the React Compiler drops a memo whose result is unused. */\nexport function useRegisteredWiring(props: { data: readonly unknown[] }, wrapSave: unknown) {\n  registerServerWiring(props.data, { props, wrapSave: wrapSave as WiringSave });\n}\n",
      "type": "registry:component",
      "target": "components/data-grid-server/server-state.ts"
    },
    {
      "path": "registry/default/blocks/data-grid-server/use-data-grid-server-rows.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport { applyChangeWith, defaultGetRowId, isDev, type ExpandedState, type ServerGroupLayout } from \"@/registry/default/components/data-grid/data-grid-sdk\";\nimport { serverSpecKey, type DataChange, type DataGridPlugin, type FilterNode, type RowRange, type ServerSpec, type SortSpec } from \"@/registry/default/components/data-grid/data-grid\";\nimport { useDataGridServerPager, type DataGridPaginationControls } from \"@/registry/default/components/data-grid-pagination/data-grid-pagination\";\nimport { DEFAULT_PAGE_SIZES } from \"@/registry/default/components/data-grid-pagination/pagination-math\";\nimport { readRevalidateInterval } from \"./fetch-hygiene\";\nimport { MAX_ROW_COUNT, readAnswer, type FetchReason, type ReadAnswer, type ServerFetchAnswer, type ServerRowsAnswer, type ServerRowsPageRequest, type WithRowId } from \"./read-answer\";\nimport { isGroupsAnswer } from \"./group-pages\";\nimport type { ServerGroupsAnswer } from \"./read-groups-answer\";\nimport type { UseDataGridServerRowsScrollOptions } from \"./scroll-blocks\";\nimport type { UseDataGridServerRowsScrollResult } from \"./scroll-types\";\nimport { useScrollRows } from \"./use-scroll-rows\";\nimport { groupsEnabled, useGroupBlocks, type UseDataGridServerRowsGroupOptions } from \"./use-group-blocks\";\nimport { keepProtectedRows, pruneIds, trackDeletes, unionIds, useRefreshGuard, type ProtectedRows } from \"./refresh-guard\";\nimport { useSaveRefresh, type SaveRefreshOptions, type SaveRefreshPolicy } from \"./save-refresh\";\nimport { isolate, scheduleFrame, useControlled, useMountedPlugins, useRegisteredWiring, useReshape, useRevalidation, useServerSpec } from \"./server-state\";\n\nexport type { DataSourceState } from \"./server-state\";\nexport type { FetchReason, ServerRowsAnswer, ServerRowsPageRequest, ServerRowsRequest } from \"./read-answer\";\nexport type { UseDataGridServerRowsScrollOptions, UseDataGridServerRowsScrollProviderProps, UseDataGridServerRowsScrollResult } from \"./scroll-blocks\";\n\n/** Options of {@link useDataGridServerRows} in pages mode. */\nexport type UseDataGridServerRowsOptions<TData, TCursor = never> = {\n  /** `\"pages\"` fetches one page per state and drives `pager`. Fixed for the life of the hook. Default `\"pages\"`. */\n  mode?: \"pages\";\n  /** Identifies a row. Default: the row's `id` field (a string or number), the same default as `DataGridProvider`; a row without one throws. */\n  getRowId?: (row: TData, index: number) => string;\n  fetchRows: (request: ServerRowsPageRequest<TCursor>) => Promise<ServerFetchAnswer<TData, TCursor>>;\n  /** Rows per page while `pageSize` is not controlled. Default: the first of `pageSizeOptions`. */\n  defaultPageSize?: number;\n  /** Controls the page size; pair it with `onPageSizeChange`. */\n  pageSize?: number;\n  onPageSizeChange?: (pageSize: number) => void;\n  /** Page sizes the footer offers. Default 10, 25, 50, 100. */\n  pageSizeOptions?: readonly number[];\n  /** First page while `page` is not controlled. Default 1. */\n  defaultPage?: number;\n  /** Controls the current page; pair it with `onPageChange`. A page that is not a whole number of at least 1 reads as page 1. */\n  page?: number;\n  onPageChange?: (page: number) => void;\n  /**\n   * The sort, filter, and search while `spec` is not controlled. A function runs once on the client after mount, so it can read\n   * `localStorage`; it returns the spec or `undefined`. The first request waits for it. An `initialAnswer` is the answer for the empty spec in that case.\n   */\n  defaultSpec?: Partial<ServerSpec> | (() => Partial<ServerSpec> | undefined);\n  /** Controls the sort, filter, and search; pair it with `onSpecChange`. */\n  spec?: ServerSpec;\n  onSpecChange?: (spec: ServerSpec) => void;\n  /** Fires after a request fails. */\n  onError?: (error: unknown) => void;\n  /**\n   * Milliseconds between `refresh()` calls the hook runs itself while the page is visible. A tick waits for a request in flight,\n   * and every refresh restarts the clock. At least 1000. Off by default.\n   */\n  revalidateIntervalMs?: number;\n  /**\n   * Milliseconds to wait after a push marked a row stale before the hook runs a `refresh()` (a reshape) so the server places the\n   * rows again. The first push starts the wait and later pushes join it, so a steady feed reshapes at most once per delay. A\n   * reshape that falls due during a request, or while the page is hidden, waits and runs once. At least 250. Default 1000 while the\n   * spec has a sort or a filter, and off otherwise; `false` turns it off, and a stale row then waits for `reshape()`, `refresh()`, or a spec change.\n   */\n  reshapeDelayMs?: number | false;\n  /**\n   * Fetches the page after the current one in the background once the current page has landed. The pager shows that page with no\n   * request. The prefetch is a plain page request; a failure is silent. A refresh, a revalidation tick, a spec or page size change,\n   * a local insert, delete, or move, and the start of a save drop it. A landed page that the pager does not reach within\n   * `revalidateIntervalMs` (30 seconds without it) is dropped too. While a save is pending, the prefetch waits. Default `false`.\n   */\n  prefetchNextPage?: boolean;\n  /** Fires after the rows of a request land, with the range they cover. */\n  onLoaded?: (range: RowRange) => void;\n  /** Fires after the hook keeps an edit, insert, delete, or revert. A provider `onDataChange` after the spread runs next to the merge. */\n  onDataChange?: (next: readonly TData[], change: DataChange<TData>) => void;\n  /** Saves a change; spread to the provider through `gridProps.onSave`, where it behaves as the `DataGridProvider` prop of the same name. The hook refreshes after saves settle by `refreshAfterSave`. */\n  onSave?: SaveRefreshOptions<TData>[\"onSave\"];\n  /** When the hook calls `refresh()` after `onSave` settles: `\"settled\"` once after every save in flight (default), `\"each\"` after saves settle without waiting for the saves in flight, `false` never, or a function that gets the counts and returns whether to refresh. */\n  refreshAfterSave?: SaveRefreshPolicy;\n  /** Plugins the hook mounts after its refresh guard, through `gridProps.plugins`. */\n  plugins?: readonly DataGridPlugin<unknown>[];\n  /**\n   * The answer for the first state (`defaultSpec`, `defaultPage`, the first page size), for example from a Server Component.\n   * The hook shows it without a request, so the server HTML holds the rows; the next state fetches as usual. It counts as\n   * untrusted input like any answer. `onLoaded` does not fire for it.\n   */\n  initialAnswer?: ServerRowsAnswer<TData, TCursor> | ServerGroupsAnswer;\n};\n\n/** Return value of {@link useDataGridServerRows}. */\nexport type UseDataGridServerRowsResult<TData> = {\n  /** Spread onto `<DataGrid {...server.gridProps} columns={columns} />`. */\n  gridProps: UseDataGridServerRowsProviderProps<TData> & UseDataGridServerRowsRootProps;\n  /** The part of `gridProps` for `<DataGridProvider>` in a composed layout. */\n  providerProps: UseDataGridServerRowsProviderProps<TData>;\n  /** The part of `gridProps` for `<DataGridRoot>` in a composed layout: the loading flag and the error state. */\n  rootProps: UseDataGridServerRowsRootProps;\n  /** The sort, filter, and search text of the current request. */\n  spec: ServerSpec;\n  /** The row count of the result; `null` when the server sends none. */\n  totalRowCount: number | null;\n  /** Spread onto `<DataGridPaginationBar {...server.pager} />`. */\n  pager: DataGridPaginationControls;\n  /** `\"error\"` wins over `\"loading\"`. */\n  status: \"loading\" | \"error\" | \"ready\";\n  /** A request of the current spec is in flight. */\n  loading: boolean;\n  /** The failure of the current request, or `null`. It clears when a new request starts. */\n  error: unknown;\n  /** Repeats the request that failed. Does nothing without an error. */\n  retry: () => void;\n  /**\n   * Fetches the current page again and keeps the rows on screen until the answer lands. A row with a pending edit, delete, or in-flight save keeps its local state.\n   * A pending insert stays at the end of the page, so the page can exceed `pageSize` until its save settles; when the last pending insert or delete settles, the hook calls it once, unless `refreshAfterSave` is `false`.\n   * The hook also calls it after saves settle by `refreshAfterSave`; call it yourself with `refreshAfterSave: false` or a void `onSave`.\n   */\n  refresh: () => void;\n  /** Asks the server to place the pushed rows again: one `refresh()` on the next frame, or after `reshapeDelayMs` when it is set. Calls in one frame join. */\n  reshape: () => void;\n};\n\n/** Props of {@link UseDataGridServerRowsResult.gridProps} that belong to `DataGridProvider`. */\nexport type UseDataGridServerRowsProviderProps<TData> = {\n  data: readonly TData[];\n  getRowId: (row: TData, index: number) => string;\n  /** Keeps the rows in step with edits, inserts, deletes, and reverts of a refused save. Send changes to your API from `onSave`. */\n  onDataChange: (next: readonly TData[], change: DataChange<TData>) => void;\n  /** Present when the hook got an `onSave`. */\n  onSave?: SaveRefreshOptions<TData>[\"onSave\"];\n  sortMode: \"server\";\n  filterMode: \"server\";\n  sortState: SortSpec[];\n  onSortChange: (next: SortSpec[]) => void;\n  filterState: FilterNode[];\n  onFilterChange: (next: FilterNode[]) => void;\n  filterJoin: \"and\" | \"or\";\n  onFilterJoinChange: (next: \"and\" | \"or\") => void;\n  searchText: string;\n  onSearchTextChange: (next: string) => void;\n  /** The row count of the result; `null` when the server sends none. */\n  totalRowCount: number | null;\n  /** Keeps checks by row id across pages and server sorts and filters. */\n  checkedRowsLifetime: \"across-filters\";\n  /** The refresh guard that keeps a refresh from overwriting a row with a pending save or an open edit, then the `plugins` option. */\n  plugins: readonly DataGridPlugin<unknown>[];\n  /** Sorts on a header click. Override it after the spread. */\n  headerClickBehavior: \"sort\";\n  /** @internal Present while the source groups: reports the rendered rows so the open groups load their rows. */\n  onRenderedRowsChange?: (range: RowRange) => void;\n  /** Present while the source groups: the group columns, outermost first. */\n  groupBy?: readonly string[];\n  /** Present while the source groups. */\n  onGroupByChange?: (next: readonly string[]) => void;\n  /** Present while the source groups: the open groups. */\n  expanded?: ExpandedState;\n  /** Present while the source groups. */\n  onExpandedChange?: (next: ExpandedState) => void;\n  /** Present while `groupBy` is not empty. */\n  groupMode?: \"server\";\n  /** Present while `groupBy` is not empty. */\n  groupLayout?: ServerGroupLayout;\n};\n\n/** Props of {@link UseDataGridServerRowsResult.gridProps} that belong to `DataGridRoot`. */\nexport type UseDataGridServerRowsRootProps = {\n  loading: boolean;\n  error: unknown;\n  onRetry: () => void;\n};\n\ntype CursorChain<TCursor> = { key: string; cursors: Map<number, TCursor | undefined> };\n\nconst furthestPage = (cursors: ReadonlyMap<number, unknown>) => [...cursors.keys()].reduce((a, b) => Math.max(a, b), 1);\n\nfunction resetChain<TCursor>(chain: CursorChain<TCursor>, key: string) {\n  if (chain.key === key) return;\n  chain.key = key;\n  chain.cursors.clear();\n  chain.cursors.set(1, undefined);\n}\n\n/** Stores the cursor of the page after `page`, and drops the cursors that hung off the old one. */\nfunction recordCursor<TCursor>(cursors: Map<number, TCursor | undefined>, page: number, nextCursor: TCursor | null) {\n  if (!cursors.has(page) || Object.is(cursors.get(page + 1), nextCursor)) return;\n  for (const known of cursors.keys()) if (known > page) cursors.delete(known);\n  if (nextCursor !== null) cursors.set(page + 1, nextCursor);\n}\n\ntype Settled<TData> = { key: string; view: string; rows: TData[]; totalRowCount: number | null; hasMore: boolean; error: unknown; chainKey: string; furthestPage: number; cursorSource: boolean };\n\nconst PREFETCH_MAX_AGE = 30_000;\n\n/** A landed prefetch waiting for the pager to reach its page. */\ntype Landed<TData, TCursor> = { view: string; rows: TData[]; read: ReadAnswer<TData, TCursor>; guard: ProtectedRows; mark: number };\n\n/** The page request after the current page. `adopted` is set when the user reached the page while the request ran. */\ntype PrefetchEntry = {\n  view: string;\n  controller: AbortController;\n  guard: ProtectedRows;\n  mark: number;\n  landed: boolean;\n  expiry: ReturnType<typeof setTimeout> | null;\n  adopted: { key: string } | null;\n};\n\n/**\n * One server data source for the grid. It owns the sort, filter, and search unless you control them, aborts the request a\n * newer state replaces, and keeps the last good rows on screen while the next request runs or after an error. The state is\n * the grid's controlled state, so it works outside the provider and needs no bridge component.\n *\n * `mode: \"pages\"` (default) fetches one page per state and goes back to page 1 when the spec or the page size changes.\n * An answer with `nextCursor` makes pages a cursor source: the hook keeps the cursor of every page it reached, sends it back\n * as `cursor`, and drops the chain when the spec or the page size changes. Such a pager has no count and no jump past the chain.\n * `mode: \"scroll\"` fetches fixed-size blocks as the rendered rows move. An answer with `totalRowCount` makes it random access;\n * an answer with `nextCursor`, or with neither, makes it sequential: the loaded rows plus one block of skeletons.\n * The mode is fixed for the life of the hook.\n */\nexport function useDataGridServerRows<TData, TCursor = never>(options: UseDataGridServerRowsScrollOptions<TData, TCursor> & UseDataGridServerRowsGroupOptions): UseDataGridServerRowsScrollResult<TData>;\nexport function useDataGridServerRows<TData, TCursor = never>(options: UseDataGridServerRowsOptions<TData, TCursor> & UseDataGridServerRowsGroupOptions): UseDataGridServerRowsResult<TData>;\nexport function useDataGridServerRows<TData, TCursor = never>(options: (UseDataGridServerRowsOptions<TData, TCursor> & UseDataGridServerRowsGroupOptions) | (UseDataGridServerRowsScrollOptions<TData, TCursor> & UseDataGridServerRowsGroupOptions)) {\n  const firstMode = useRef({ mode: options.mode ?? \"pages\", warned: false });\n  if (isDev() && !firstMode.current.warned && (options.mode ?? \"pages\") !== firstMode.current.mode) {\n    firstMode.current.warned = true;\n    console.warn(`[data-grid-server] mode changed from \"${firstMode.current.mode}\" to \"${options.mode ?? \"pages\"}\"; the mode is fixed for the life of the hook, so remount it with a key`);\n  }\n  // The mode never changes for a mounted hook, so each render calls the same hooks in the same order.\n  // eslint-disable-next-line react-hooks/rules-of-hooks\n  // oxlint-disable-next-line react-hooks/rules-of-hooks\n  const [pagerWatch] = useState(() => new PagerWatch());\n  const resolved = options.getRowId ? options : { ...options, getRowId: defaultGetRowId };\n  return resolved.mode === \"scroll\" ? useScrollRows(resolved as WithRowId<UseDataGridServerRowsScrollOptions<TData, TCursor> & UseDataGridServerRowsGroupOptions, TData>) : pagerWatch.attach(usePagesRows(resolved as WithRowId<UseDataGridServerRowsOptions<TData, TCursor> & UseDataGridServerRowsGroupOptions, TData>, pagerWatch));\n}\n\nfunction usePagesRows<TData, TCursor>(options: WithRowId<UseDataGridServerRowsOptions<TData, TCursor> & UseDataGridServerRowsGroupOptions, TData>, pagerWatch: PagerWatch): UseDataGridServerRowsResult<TData> {\n  const { pageSizeOptions = DEFAULT_PAGE_SIZES } = options;\n  const [pageSize, setPageSize] = useControlled(options.pageSize, () => options.defaultPageSize ?? pageSizeOptions[0] ?? DEFAULT_PAGE_SIZES[0], options.onPageSizeChange);\n  const [rawPage, setPage] = useControlled(options.page, () => options.defaultPage ?? 1, options.onPageChange);\n  const maxPage = Math.max(1, Math.ceil(MAX_ROW_COUNT / Math.max(1, pageSize)));\n  const wantedPage = Number.isSafeInteger(rawPage) && rawPage >= 1 ? Math.min(rawPage, maxPage) : 1;\n  const live = useRef({ options, spec: EMPTY_LIVE_SPEC, page: wantedPage, pageSize, settledOnce: false, requested: false, error: null as unknown, leftInitial: false });\n  const [grouping] = useState(() => groupsEnabled(options));\n  const specState = useServerSpec(\n    options,\n    () => {\n      if (live.current.settledOnce) setPage(1);\n    },\n    grouping,\n  );\n  const { spec, ready: specReady, onSortChange, onFilterChange, onFilterJoinChange, onSearchTextChange } = specState;\n  const grouped = grouping && (spec.groupBy?.length ?? 0) > 0;\n  const chainKey = `${serverSpecKey(spec)}|${pageSize}`;\n  const chain = useRef<CursorChain<TCursor>>({ key: chainKey, cursors: new Map([[1, undefined]]) });\n  const [initial] = useState(() => {\n    if (options.initialAnswer === undefined || isGroupsAnswer(options.initialAnswer)) return null;\n    const start = (wantedPage - 1) * pageSize;\n    const read = readAnswer<TData, TCursor>(options.initialAnswer as ServerRowsAnswer<TData, TCursor>, { start, end: start + pageSize }, (_, message) => isDev() && console.warn(`[data-grid-server] ${message}`), options.getRowId);\n    const view = `${serverSpecKey(spec)}|${wantedPage}|${pageSize}`;\n    return { read, view, key: `${view}|0`, page: wantedPage };\n  });\n  const [settled, setSettled] = useState<Settled<TData>>(() => {\n    const empty: Settled<TData> = { key: \"\", view: \"\", rows: [], totalRowCount: null, hasMore: false, error: null, chainKey: \"\", furthestPage: 1, cursorSource: false };\n    if (initial === null) return empty;\n    const { read } = initial;\n    const cursorAnswer = read.nextCursor !== undefined;\n    const rows = read.rows.filter((row) => row !== undefined) as TData[];\n    // A fresh chain knows only page 1, so only a first-page cursor answer reaches page 2.\n    const furthest = cursorAnswer && initial.page === 1 && read.nextCursor !== null ? 2 : 1;\n    return { ...empty, key: initial.key, view: initial.view, rows, totalRowCount: read.totalRowCount ?? null, hasMore: cursorAnswer ? read.nextCursor !== null : read.hasMore, chainKey, furthestPage: furthest, cursorSource: cursorAnswer };\n  });\n  const cursorSource = settled.chainKey === chainKey && settled.cursorSource;\n  const awaitingChain = !cursorSource && settled.cursorSource;\n  const page = cursorSource ? Math.min(wantedPage, settled.furthestPage) : awaitingChain ? 1 : wantedPage;\n  const [tick, setTick] = useState(0);\n  const { plugins: guardPlugins, protectedRows, saveMark, savedSince, pruneSaves, overlayPushed, streamUpdateRow, savingRows, setSaveStartListener, setSavesSettledListener, setReshapeListener, setSettleListener } = useRefreshGuard();\n  const [landed, setLanded] = useState<Landed<TData, TCursor> | null>(null);\n\n  const specKey = serverSpecKey(spec);\n  const view = `${specKey}|${page}|${pageSize}`;\n  const key = `${view}|${tick}${specReady ? \"\" : \"|seeding\"}`;\n  const deleted = useRef(new Set<string>());\n  const prefetch = useRef<PrefetchEntry | null>(null);\n  const openMarks = useRef<{ main: number | null; prefetch: number | null }>({ main: null, prefetch: null });\n  const adoptedKey = useRef<string | null>(null);\n  const nextReason = useRef<FetchReason>(\"load\");\n\n  const warned = useRef(new Set<string>());\n  const warn = useCallback((kind: string, message: string) => {\n    if (!isDev() || warned.current.has(kind)) return;\n    warned.current.add(kind);\n    console.warn(`[data-grid-server] ${message}`);\n  }, []);\n\n  const releaseMarks = useCallback(() => {\n    const { main, prefetch: ahead } = openMarks.current;\n    pruneSaves(main === null ? ahead : ahead === null ? main : Math.min(main, ahead));\n    if (main === null && ahead === null) pruneIds(deleted.current, savingRows());\n  }, [pruneSaves, savingRows]);\n\n  const commitLanding = useCallback(\n    (read: ReadAnswer<TData, TCursor>, landing: { key: string; view: string; page: number; start: number; guard: ProtectedRows; mark: number }) => {\n      live.current.settledOnce = true;\n      const cursorAnswer = read.nextCursor !== undefined;\n      if (cursorAnswer) recordCursor(chain.current.cursors, landing.page, read.nextCursor as TCursor | null);\n      const furthest = furthestPage(chain.current.cursors);\n      const guarded = unionIds(unionIds(landing.guard, savedSince(landing.mark)), protectedRows());\n      const gone = deleted.current.size > 0 ? new Set(deleted.current) : deleted.current;\n      const answerRows = overlayPushed(read.rows.filter((row) => row !== undefined) as TData[], landing.mark, 0, live.current.options.getRowId);\n      setSettled((prev) => ({\n        key: landing.key,\n        view: landing.view,\n        rows: keepProtectedRows(answerRows, prev.rows, guarded, gone, prev.view === landing.view, live.current.options.getRowId),\n        totalRowCount: read.totalRowCount === undefined ? prev.totalRowCount : read.totalRowCount,\n        hasMore: cursorAnswer ? read.nextCursor !== null : read.hasMore,\n        error: null,\n        chainKey,\n        furthestPage: furthest,\n        cursorSource: cursorAnswer,\n      }));\n      const onLoaded = live.current.options.onLoaded;\n      if (onLoaded) isolate(\"onLoaded\", () => onLoaded({ start: landing.start, end: landing.start + read.rows.length }));\n    },\n    [savedSince, protectedRows, overlayPushed, chainKey],\n  );\n\n  const failRequest = useCallback((requestKey: string, error: unknown) => {\n    const failure = error ?? new Error(\"fetchRows rejected\");\n    live.current.settledOnce = true;\n    setSettled((prev) => ({ ...prev, key: requestKey, error: failure }));\n    const onError = live.current.options.onError;\n    if (onError) isolate(\"onError\", () => onError(failure));\n  }, []);\n\n  const dropPrefetch = useCallback(() => {\n    const entry = prefetch.current;\n    if (entry === null) return;\n    prefetch.current = null;\n    if (entry.expiry !== null) clearTimeout(entry.expiry);\n    if (!entry.landed) entry.controller.abort();\n    openMarks.current.prefetch = null;\n    releaseMarks();\n    setLanded(null);\n    if (entry.adopted !== null) setTick((n) => n + 1);\n  }, [releaseMarks]);\n\n  // A save can move a row to another page, so a page requested before it is stale.\n  useEffect(() => {\n    setSaveStartListener(dropPrefetch);\n    return () => setSaveStartListener(null);\n  }, [setSaveStartListener, dropPrefetch]);\n\n  // The prefetch waits for pending saves; it runs again when the last one settles.\n  const [savesSettled, setSavesSettled] = useState(0);\n  useEffect(() => {\n    setSavesSettledListener(() => setSavesSettled((n) => n + 1));\n    return () => setSavesSettledListener(null);\n  }, [setSavesSettledListener]);\n\n  useEffect(() => {\n    if (!specReady || grouped) return;\n    const reason = nextReason.current;\n    nextReason.current = \"load\";\n    const adoptedRequest = adoptedKey.current === key;\n    adoptedKey.current = null;\n    if (adoptedRequest) return;\n    if (initial !== null && !live.current.leftInitial && key === initial.key) {\n      if (initial.read.nextCursor !== undefined) recordCursor(chain.current.cursors, initial.page, initial.read.nextCursor as TCursor | null);\n      live.current.settledOnce = true;\n      live.current.requested = true;\n      return;\n    }\n    live.current.leftInitial = true;\n    const ahead = prefetch.current;\n    if (ahead !== null && ahead.view === view && !ahead.landed) {\n      ahead.adopted = { key };\n      live.current.requested = true;\n      return () => {\n        if (prefetch.current !== ahead || ahead.adopted?.key !== key) return;\n        ahead.controller.abort();\n        prefetch.current = null;\n        openMarks.current.prefetch = null;\n        releaseMarks();\n      };\n    }\n    if (ahead !== null) dropPrefetch();\n    const controller = new AbortController();\n    const { page: requestPage, pageSize: requestSize } = live.current;\n    const requestSpec = spec;\n    resetChain(chain.current, chainKey);\n    const protectedAtStart = savingRows();\n    const markAtStart = saveMark();\n    openMarks.current.main = markAtStart;\n    releaseMarks();\n    pruneIds(deleted.current, protectedAtStart);\n    const start = (requestPage - 1) * requestSize;\n    const range: RowRange = { start, end: start + requestSize };\n    const settleMountState = live.current.requested ? Promise.resolve() : new Promise<void>((resolve) => setTimeout(resolve, 0));\n    live.current.requested = true;\n    // A state restored in a mount effect (URL state) replaces this request before it leaves.\n    settleMountState\n      .then(() => {\n        if (controller.signal.aborted) return Promise.reject(controller.signal.reason);\n        return live.current.options.fetchRows({ spec: requestSpec, page: requestPage, pageSize: requestSize, start, end: range.end, cursor: chain.current.cursors.get(requestPage), reason, signal: controller.signal });\n      })\n      .then((answer) => {\n        if (controller.signal.aborted) return;\n        const read = readAnswer<TData, TCursor>(answer, range, warn, live.current.options.getRowId);\n        commitLanding(read, { key, view, page: requestPage, start, guard: protectedAtStart, mark: markAtStart });\n        openMarks.current.main = null;\n        releaseMarks();\n      })\n      .catch((error: unknown) => {\n        if (controller.signal.aborted) return;\n        openMarks.current.main = null;\n        releaseMarks();\n        failRequest(key, error);\n      });\n    return () => controller.abort();\n    // `key` stands for spec, page, pageSize, and tick.\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [key]);\n\n  const prefetchOn = options.prefetchNextPage === true && !grouped;\n  const startPrefetch = useCallback(() => {\n    const { page: current, pageSize: size, spec: currentSpec } = live.current;\n    const ahead = `${serverSpecKey(currentSpec)}|${current + 1}|${size}`;\n    if (prefetch.current?.view === ahead || savingRows() !== null) return;\n    dropPrefetch();\n    const controller = new AbortController();\n    const entry: PrefetchEntry = { view: ahead, controller, guard: savingRows(), mark: saveMark(), landed: false, expiry: null, adopted: null };\n    prefetch.current = entry;\n    openMarks.current.prefetch = entry.mark;\n    const start = current * size;\n    const range: RowRange = { start, end: start + size };\n    new Promise<ServerFetchAnswer<TData, TCursor>>((resolve) => resolve(live.current.options.fetchRows({ spec: currentSpec, page: current + 1, pageSize: size, start, end: range.end, cursor: chain.current.cursors.get(current + 1), reason: \"load\", signal: controller.signal })))\n      .then((answer) => {\n        if (controller.signal.aborted) return;\n        const read = readAnswer<TData, TCursor>(answer, range, warn, live.current.options.getRowId);\n        entry.landed = true;\n        if (entry.adopted !== null) {\n          commitLanding(read, { key: entry.adopted.key, view: ahead, page: current + 1, start, guard: entry.guard, mark: entry.mark });\n          prefetch.current = null;\n          openMarks.current.prefetch = null;\n          releaseMarks();\n          return;\n        }\n        const maxAge = readRevalidateInterval(live.current.options.revalidateIntervalMs).interval ?? PREFETCH_MAX_AGE;\n        entry.expiry = setTimeout(dropPrefetch, maxAge);\n        setLanded({ view: ahead, rows: read.rows.filter((row) => row !== undefined) as TData[], read, guard: entry.guard, mark: entry.mark });\n      })\n      .catch((error: unknown) => {\n        if (controller.signal.aborted) return;\n        if (entry.adopted === null) {\n          dropPrefetch();\n          return;\n        }\n        prefetch.current = null;\n        openMarks.current.prefetch = null;\n        releaseMarks();\n        failRequest(entry.adopted.key, error);\n      });\n  }, [dropPrefetch, savingRows, saveMark, commitLanding, failRequest, releaseMarks, warn]);\n\n  const adoptable = landed !== null && landed.view === view && settled.key !== key ? landed : null;\n  const shown: Settled<TData> =\n    adoptable === null ? settled : { key, view, rows: adoptable.rows, totalRowCount: adoptable.read.totalRowCount === undefined ? settled.totalRowCount : adoptable.read.totalRowCount, hasMore: adoptable.read.nextCursor !== undefined ? adoptable.read.nextCursor !== null : adoptable.read.hasMore, error: null, chainKey: settled.chainKey, furthestPage: settled.furthestPage, cursorSource: settled.cursorSource };\n\n  const loading = shown.key !== key;\n  const error = shown.key === key ? shown.error : null;\n  useLayoutEffect(() => {\n    Object.assign(live.current, { options, spec, page, pageSize, error });\n  });\n\n  // The pager reached the prefetched page: the landing runs without a request.\n  useLayoutEffect(() => {\n    const entry = prefetch.current;\n    if (adoptable === null || entry === null || entry.view !== adoptable.view) return;\n    adoptedKey.current = key;\n    if (entry.expiry !== null) clearTimeout(entry.expiry);\n    prefetch.current = null;\n    pruneIds(deleted.current, savingRows());\n    const { page: landedPage, pageSize: landedSize } = live.current;\n    commitLanding(adoptable.read, { key, view, page: landedPage, start: (landedPage - 1) * landedSize, guard: adoptable.guard, mark: adoptable.mark });\n    openMarks.current.prefetch = null;\n    releaseMarks();\n    setLanded(null);\n    // The effect adopts once per landed entry and key.\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [adoptable]);\n\n  useEffect(() => {\n    if (!prefetchOn || settled.key !== key || settled.error !== null) {\n      if (!prefetchOn) dropPrefetch();\n      return;\n    }\n    const hasNext = settled.totalRowCount !== null ? page * pageSize < settled.totalRowCount : settled.hasMore;\n    if (!hasNext || page + 1 > maxPage) return;\n    const timer = setTimeout(startPrefetch, 0);\n    return () => clearTimeout(timer);\n    // The effect follows landings, not local edits of the rows.\n    // oxlint-disable-next-line react-hooks/exhaustive-deps\n  }, [prefetchOn, settled.key, settled.error, settled.totalRowCount, settled.hasMore, key, savesSettled]);\n\n  useEffect(\n    () => () => {\n      const entry = prefetch.current;\n      prefetch.current = null;\n      if (entry === null) return;\n      if (entry.expiry !== null) clearTimeout(entry.expiry);\n      entry.controller.abort();\n    },\n    [],\n  );\n\n  const status = error !== null ? \"error\" : loading ? \"loading\" : \"ready\";\n  const pagerNeeded = options.page === undefined && settled.key !== \"\" && (cursorSource ? settled.hasMore : settled.totalRowCount !== null && settled.totalRowCount > pageSize);\n  useEffect(() => {\n    if (pagerNeeded && !pagerWatch.seen) warn(\"pager\", \"pages mode has more rows than one page, but nothing read `pager`; spread `server.pager` onto DataGridPaginationBar or control `page`\");\n  }, [pagerNeeded, pagerWatch, warn]);\n  useEffect(() => {\n    if (grouped && options.prefetchNextPage === true) warn(\"prefetch-grouped\", \"`prefetchNextPage` has no effect while `groupBy` is set: a grouped page loads when the pager moves to it\");\n  }, [grouped, options.prefetchNextPage, warn]);\n  useLayoutEffect(() => {\n    if (page !== wantedPage) setPage(page);\n  }, [page, wantedPage, setPage]);\n\n  const seenSpecKey = useRef(specKey);\n  const seenPage = useRef(page);\n  useLayoutEffect(() => {\n    const pageMoved = seenPage.current !== page;\n    seenPage.current = page;\n    if (seenSpecKey.current === specKey) return;\n    seenSpecKey.current = specKey;\n    // A spec the consumer changed from outside (browser back) lands here; a grid change already reset the page.\n    if (live.current.settledOnce && !pageMoved && page !== 1) setPage(1);\n  }, [specKey, page, setPage]);\n\n  const retry = useCallback(() => {\n    if (live.current.error === null) return;\n    nextReason.current = \"retry\";\n    setTick((n) => n + 1);\n  }, []);\n  const restartClockRef = useRef<() => void>(() => {});\n  const refreshRef = useRef<(reason: FetchReason) => void>(() => {});\n  const { request: requestReshape, cancel: cancelReshape } = useReshape({ delay: grouped ? false : options.reshapeDelayMs, ordered: spec.sorts.length + spec.filters.length > 0, run: () => refreshRef.current(\"refresh\"), busy: loading, resetKey: view, warn });\n  const reshape = useCallback(() => requestReshape(\"soon\"), [requestReshape]);\n  useEffect(() => {\n    setReshapeListener(requestReshape);\n    return () => setReshapeListener(null);\n  }, [setReshapeListener, requestReshape]);\n  const refreshFor = useCallback(\n    (reason: FetchReason) => {\n      cancelReshape();\n      restartClockRef.current();\n      nextReason.current = reason;\n      setTick((n) => n + 1);\n    },\n    [cancelReshape],\n  );\n  const refresh = useCallback(() => refreshFor(\"refresh\"), [refreshFor]);\n  const refreshAfterSave = useCallback(() => refreshFor(\"save\"), [refreshFor]);\n  useLayoutEffect(() => {\n    refreshRef.current = refreshFor;\n  }, [refreshFor]);\n  const keyRef = useRef(key);\n  useLayoutEffect(() => {\n    keyRef.current = key;\n  }, [key]);\n  // A settled insert or delete moves rows between pages; one frame later the page loads again, unless a request of its own already ran.\n  useEffect(() => {\n    let cancel: (() => void) | null = null;\n    setSettleListener(() => {\n      if (cancel !== null || live.current.options.refreshAfterSave === false) return;\n      const keyAtSettle = keyRef.current;\n      cancel = scheduleFrame(() => {\n        cancel = null;\n        if (keyRef.current === keyAtSettle) refreshRef.current(\"save\");\n      });\n    });\n    return () => {\n      setSettleListener(null);\n      cancel?.();\n    };\n  }, [setSettleListener]);\n  const restartClock = useRevalidation({ interval: grouped ? undefined : options.revalidateIntervalMs, onTick: () => refreshRef.current(\"refresh\"), busy: loading, resetKey: specKey });\n  useLayoutEffect(() => {\n    restartClockRef.current = restartClock;\n  }, [restartClock]);\n\n  const handledChanges = useRef(new WeakSet<object>());\n  const onDataChange = useCallback(\n    (next: readonly TData[], change: DataChange<TData>) => {\n      if (handledChanges.current.has(change)) return;\n      handledChanges.current.add(change);\n      trackDeletes(deleted.current, change);\n      if (((change.ops as typeof change.ops | undefined) ?? []).some((op) => op.type !== \"update\")) dropPrefetch();\n      // `next` is the grid's snapshot and can predate a page that landed since; replaying the operations on the latest rows keeps it.\n      setSettled((prev) => ({ ...prev, rows: (change.ops as typeof change.ops | undefined)?.length ? applyChangeWith(prev.rows, change, live.current.options.getRowId, { rowOfUpdate: streamUpdateRow(change) }) : (next as TData[]) }));\n      if (change.source === \"stream\" && ((change.ops as typeof change.ops | undefined) ?? []).some((op) => op.type === \"delete\")) requestReshape(\"soon\");\n      live.current.options.onDataChange?.(next, change);\n    },\n    [dropPrefetch, requestReshape, streamUpdateRow],\n  );\n  const getRowId = useCallback((row: TData, index: number) => live.current.options.getRowId(row, index), []);\n\n  const onPageSizeChange = useCallback(\n    (next: number) => {\n      setPageSize(next);\n      setPage(1);\n    },\n    [setPageSize, setPage],\n  );\n  const { pager, gridProps: pagerGridProps } = useDataGridServerPager({\n    page,\n    pageSize,\n    pageSizeOptions,\n    totalRowCount: grouped || cursorSource ? null : shown.totalRowCount,\n    hasMore: shown.hasMore && !awaitingChain,\n    onPageChange: setPage,\n    onPageSizeChange,\n  });\n\n  const { onSave, wrapSave } = useSaveRefresh(options, refreshAfterSave);\n\n  const groupPages = useGroupBlocks(options as unknown as Parameters<typeof useGroupBlocks<TData, TCursor>>[0], specState, grouped, { page, pageSize, pageSizeOptions, onPageChange: setPage, onPageSizeChange });\n  useLayoutEffect(() => {\n    if (groupPages.groupCount !== null) live.current.settledOnce = true;\n  });\n  useMemo(() => armPagerRead(groupPages.pagerPlugins, pagerWatch), [groupPages.pagerPlugins, pagerWatch]);\n\n  const pagerGuardPlugins = useMemo(() => {\n    // a bare DataGridPaginationBar under this grid reads the pager through the stash plugin\n    armPagerRead(pagerGridProps.plugins, pagerWatch);\n    return [...guardPlugins, ...pagerGridProps.plugins];\n  }, [guardPlugins, pagerGridProps.plugins, pagerWatch]);\n  const plugins = useMountedPlugins(pagerGuardPlugins, options.plugins);\n\n  const providerProps = useMemo<UseDataGridServerRowsProviderProps<TData>>(\n    () => ({\n      data: shown.rows,\n      getRowId,\n      onDataChange,\n      ...(onSave ? { onSave } : {}),\n      sortMode: \"server\",\n      filterMode: \"server\",\n      sortState: spec.sorts as SortSpec[],\n      onSortChange,\n      filterState: spec.filters as FilterNode[],\n      onFilterChange,\n      filterJoin: spec.filterJoin ?? \"and\",\n      onFilterJoinChange,\n      searchText: spec.searchText,\n      onSearchTextChange,\n      totalRowCount: shown.totalRowCount,\n      checkedRowsLifetime: \"across-filters\",\n      headerClickBehavior: \"sort\",\n      plugins,\n    }),\n    [shown.rows, shown.totalRowCount, spec, getRowId, onDataChange, onSave, onSortChange, onFilterChange, onFilterJoinChange, onSearchTextChange, plugins],\n  );\n  useRegisteredWiring(providerProps, wrapSave);\n  const rootProps = useMemo<UseDataGridServerRowsRootProps>(() => ({ loading, error, onRetry: retry }), [loading, error, retry]);\n  const gridProps = useMemo(() => ({ ...providerProps, ...rootProps }), [providerProps, rootProps]);\n\n  if (grouped) {\n    const { gridProps: groupedGrid, providerProps: groupedProvider, rootProps: groupedRoot, totalRowCount, status: groupedStatus, loading: groupedLoading, error: groupedError, retry: groupedRetry, refresh: groupedRefresh, reshape: groupedReshape } = groupPages.result;\n    return { gridProps: groupedGrid, providerProps: groupedProvider, rootProps: groupedRoot, spec, totalRowCount, pager: groupPages.pager, status: groupedStatus, loading: groupedLoading, error: groupedError, retry: groupedRetry, refresh: groupedRefresh, reshape: groupedReshape } as UseDataGridServerRowsResult<TData>;\n  }\n  return { gridProps, providerProps, rootProps, spec, totalRowCount: shown.totalRowCount, pager, status, loading, error, retry, refresh, reshape };\n}\n\n/** Records whether the consumer read `pager`, so the hook can warn about a pager that nothing reads. */\nconst PAGER_READ = Symbol.for(\"gridcn.pager-read\");\n\nfunction armPagerRead(plugins: readonly object[], watch: PagerWatch) {\n  for (const plugin of plugins) Object.assign(plugin, { [PAGER_READ]: () => void (watch.seen = true) });\n}\n\nclass PagerWatch {\n  seen = false;\n\n  attach<T extends { pager: DataGridPaginationControls }>(result: T): T {\n    const { pager } = result;\n    const markSeen = () => {\n      this.seen = true;\n    };\n    return {\n      ...result,\n      get pager() {\n        markSeen();\n        return pager;\n      },\n    };\n  }\n}\n\nconst EMPTY_LIVE_SPEC: ServerSpec = { sorts: [], filters: [], searchText: \"\" };\n",
      "type": "registry:component",
      "target": "components/data-grid-server/use-data-grid-server-rows.ts"
    }
  ],
  "categories": [
    "data"
  ],
  "type": "registry:block"
}
