@pretable/core 0.14.1 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["_a","nodeHeight","dataRef","nodeHeight","createColumnHelper","isRuntimeFilterGroup","readDateTimestamp","collator","fail","attachInstrumentation","iterateEntries","attachInstrumentation","createDeferredMeasureDraft","DEVELOPMENT","factory","dataRef","DEVELOPMENT","createLocalRowModel","previousSnapshot","createInternalColumnHelper","createInternalLocalRowModel"],"sources":["../../layout-core/dist/dense-membership.js","../../layout-core/dist/row-height-index.js","../../grid-core/dist/indexed-selection.js","../../grid-core/dist/indexed-focus.js","../../grid-core/dist/create-grid-ui-core.js","../../grid-core/dist/group-column.js","../src/create-grid.ts","../../row-model/dist/column-types.js","../../calendar-date/dist/calendar-date.js","../../row-model/dist/calendar-date-aggregates.js","../../row-model/dist/errors.js","../../row-model/dist/query-equality.js","../../row-model/dist/compiled-query.js","../../row-model/dist/membership-bitset.js","../../row-model/dist/persistent/transient.js","../../row-model/dist/persistent/persistent-map.js","../../row-model/dist/persistent/order-statistic-tree.js","../../row-model/dist/slot-vector.js","../../row-model/dist/ordered-row-entry.js","../../row-model/dist/persistent/aggregate-tree.js","../../row-model/dist/group-index.js","../../row-model/dist/visible-index.js","../../row-model/dist/filter-rebuild.js","../../row-model/dist/filter-membership.js","../../row-model/dist/sort-rebuild.js","../../row-model/dist/flat-cooperative-candidate.js","../../row-model/dist/cooperative-transition.js","../../row-model/dist/distinct-values.js","../../row-model/dist/change-journal.js","../../row-model/dist/row-integrity.js","../../row-model/dist/row-store.js","../../row-model/dist/slot-allocator.js","../../row-model/dist/transaction-draft.js","../../row-model/dist/create-local-row-model.js","../../row-model/dist/aggregate-overrides.js","../../row-model/dist/aggregator-law.js","../src/create-column-helper.ts","../src/create-local-row-model.ts","../src/number-formats.ts"],"sourcesContent":["/**\n * Membership bitset: one bit per dense key (row-model SLOT). Duplicated from\n * `@pretable-internal/row-model`'s `membership-bitset.ts` BY DESIGN —\n * layout-core stays dependency-free (it cannot import row-model), so this\n * ~40-line primitive is hand-copied rather than shared. Keep the two files\n * in sync by hand; if one changes shape, mirror the change in the other.\n *\n * See `docs/superpowers/specs/2026-08-24-dense-handle-amendment-i-layout-seam.md`\n * for the dense lane this backs.\n */\nexport function createDenseMembership(capacity) {\n return new Uint32Array((capacity + 31) >>> 5);\n}\n/** Clone, growing to `capacity` when it exceeds the source's words. */\nexport function cloneDenseMembership(bits, capacity) {\n const words = Math.max(bits.length, (capacity + 31) >>> 5);\n const next = new Uint32Array(words);\n next.set(bits);\n return next;\n}\nexport function setDenseBit(bits, slot) {\n bits[slot >>> 5] |= 1 << (slot & 31);\n}\nexport function clearDenseBit(bits, slot) {\n bits[slot >>> 5] &= ~(1 << (slot & 31));\n}\n/** Out-of-range slots read as false. */\nexport function testDenseBit(bits, slot) {\n const word = bits[slot >>> 5];\n return word === undefined ? false : ((word >>> (slot & 31)) & 1) === 1;\n}\n","var _a;\nimport { clearDenseBit, cloneDenseMembership, createDenseMembership, setDenseBit, testDenseBit, } from \"./dense-membership\";\nfunction createWork(entriesVisited = 0) {\n return {\n nodesCreated: 0,\n entriesVisited,\n identityLookups: 0,\n identityComparisons: 0,\n measurementEntriesScanned: 0,\n previousEntriesScanned: 0,\n sortComparisons: 0,\n reorderEntriesReused: 0,\n reorderEntriesRemeasured: 0,\n refilterEntriesReused: 0,\n refilterEntriesInserted: 0,\n refilterEntriesRetired: 0,\n };\n}\nconst DEFAULT_MAX_RETAINED_MEASUREMENTS = 100_000;\nconst TICKET_KEY_WIDTH = String(Number.MAX_SAFE_INTEGER).length;\nexport class RowHeightReplacementLifecycleError extends Error {\n code;\n constructor(code, message) {\n super(message);\n this.name = \"RowHeightReplacementLifecycleError\";\n this.code = code;\n }\n}\nfunction nodeHeight(node) {\n return node?.height ?? 0;\n}\nfunction nodeCount(node) {\n return node?.count ?? 0;\n}\nfunction nodePixels(node) {\n return node?.pixels ?? 0;\n}\nfunction sequenceNode(value, left, right, work) {\n work.nodesCreated += 1;\n return {\n value,\n left,\n right,\n height: 1 + Math.max(nodeHeight(left), nodeHeight(right)),\n count: nodeCount(left) + 1 + nodeCount(right),\n pixels: nodePixels(left) + value.height + nodePixels(right),\n };\n}\nfunction rebalanceSequence(value, left, right, work) {\n if (nodeHeight(left) > nodeHeight(right) + 1) {\n const pivot = left;\n if (nodeHeight(pivot.left) >= nodeHeight(pivot.right)) {\n return sequenceNode(pivot.value, pivot.left, sequenceNode(value, pivot.right, right, work), work);\n }\n const middle = pivot.right;\n return sequenceNode(middle.value, sequenceNode(pivot.value, pivot.left, middle.left, work), sequenceNode(value, middle.right, right, work), work);\n }\n if (nodeHeight(right) > nodeHeight(left) + 1) {\n const pivot = right;\n if (nodeHeight(pivot.right) >= nodeHeight(pivot.left)) {\n return sequenceNode(pivot.value, sequenceNode(value, left, pivot.left, work), pivot.right, work);\n }\n const middle = pivot.left;\n return sequenceNode(middle.value, sequenceNode(value, left, middle.left, work), sequenceNode(pivot.value, middle.right, pivot.right, work), work);\n }\n return sequenceNode(value, left, right, work);\n}\nfunction insertSequence(root, index, value, work) {\n if (root === null)\n return sequenceNode(value, null, null, work);\n const leftCount = nodeCount(root.left);\n if (index <= leftCount) {\n return rebalanceSequence(root.value, insertSequence(root.left, index, value, work), root.right, work);\n }\n return rebalanceSequence(root.value, root.left, insertSequence(root.right, index - leftCount - 1, value, work), work);\n}\nfunction extractSequenceMinimum(root, work) {\n if (root.left === null)\n return { root: root.right, minimum: root.value };\n const extracted = extractSequenceMinimum(root.left, work);\n return {\n minimum: extracted.minimum,\n root: rebalanceSequence(root.value, extracted.root, root.right, work),\n };\n}\nfunction removeSequence(root, index, work) {\n const leftCount = nodeCount(root.left);\n if (index < leftCount) {\n const removed = removeSequence(root.left, index, work);\n return {\n value: removed.value,\n root: rebalanceSequence(root.value, removed.root, root.right, work),\n };\n }\n if (index > leftCount) {\n const removed = removeSequence(root.right, index - leftCount - 1, work);\n return {\n value: removed.value,\n root: rebalanceSequence(root.value, root.left, removed.root, work),\n };\n }\n if (root.left === null)\n return { root: root.right, value: root.value };\n if (root.right === null)\n return { root: root.left, value: root.value };\n const extracted = extractSequenceMinimum(root.right, work);\n return {\n value: root.value,\n root: rebalanceSequence(extracted.minimum, root.left, extracted.root, work),\n };\n}\nfunction updateSequence(root, index, value, work) {\n const leftCount = nodeCount(root.left);\n if (index < leftCount) {\n return rebalanceSequence(root.value, updateSequence(root.left, index, value, work), root.right, work);\n }\n if (index > leftCount) {\n return rebalanceSequence(root.value, root.left, updateSequence(root.right, index - leftCount - 1, value, work), work);\n }\n return sequenceNode(value, root.left, root.right, work);\n}\nfunction sequenceAt(root, index) {\n let current = root;\n let rank = index;\n while (current !== null) {\n const leftCount = nodeCount(current.left);\n if (rank < leftCount)\n current = current.left;\n else if (rank > leftCount) {\n rank -= leftCount + 1;\n current = current.right;\n }\n else\n return current.value;\n }\n return undefined;\n}\n/**\n * One-pass balanced build over an already-ordered value array — the\n * synchronous counterpart of the replacement builder's `build-sequence` phase\n * (same midpoint convention, so both produce the same shape). Depth is\n * logarithmic, so the recursion is stack-safe at any realistic row count.\n */\nfunction buildBalancedSequence(values, start, end, work) {\n if (start >= end)\n return null;\n const middle = Math.floor((start + end) / 2);\n return sequenceNode(values[middle], buildBalancedSequence(values, start, middle, work), buildBalancedSequence(values, middle + 1, end, work), work);\n}\nfunction hashIdentity(identity) {\n let hash = 0x811c9dc5;\n for (let index = 0; index < identity.length; index += 1) {\n hash ^= identity.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\nfunction hashCount(root) {\n return root?.count ?? 0;\n}\n/** Total of a map's numeric values; see {@link HashLeaf}. */\nfunction hashSum(root) {\n return root?.sum ?? 0;\n}\nfunction entryWeight(value) {\n return typeof value === \"number\" ? value : 0;\n}\nfunction popCount(value) {\n let remaining = value >>> 0;\n remaining -= (remaining >>> 1) & 0x55555555;\n remaining = (remaining & 0x33333333) + ((remaining >>> 2) & 0x33333333);\n return (((remaining + (remaining >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24;\n}\nfunction hashFragment(hash, shift) {\n return (hash >>> shift) & 31;\n}\nfunction hashBit(fragment) {\n return (1 << fragment) >>> 0;\n}\nfunction hashPosition(bitmap, bit) {\n return popCount((bitmap & (bit - 1)) >>> 0);\n}\nfunction hashLeaf(hash, entry, work) {\n work.nodesCreated += 1;\n return { kind: \"leaf\", hash, entry, count: 1, sum: entryWeight(entry.value) };\n}\nfunction collisionCount(root) {\n return root?.count ?? 0;\n}\nfunction collisionSum(root) {\n return root?.sum ?? 0;\n}\nfunction collisionNode(entry, left, right, work) {\n work.nodesCreated += 1;\n return {\n entry,\n left,\n right,\n height: 1 + Math.max(nodeHeight(left), nodeHeight(right)),\n count: collisionCount(left) + 1 + collisionCount(right),\n sum: collisionSum(left) + entryWeight(entry.value) + collisionSum(right),\n };\n}\nfunction rebalanceCollision(entry, left, right, work) {\n if (nodeHeight(left) > nodeHeight(right) + 1) {\n const pivot = left;\n if (nodeHeight(pivot.left) >= nodeHeight(pivot.right)) {\n return collisionNode(pivot.entry, pivot.left, collisionNode(entry, pivot.right, right, work), work);\n }\n const middle = pivot.right;\n return collisionNode(middle.entry, collisionNode(pivot.entry, pivot.left, middle.left, work), collisionNode(entry, middle.right, right, work), work);\n }\n if (nodeHeight(right) > nodeHeight(left) + 1) {\n const pivot = right;\n if (nodeHeight(pivot.right) >= nodeHeight(pivot.left)) {\n return collisionNode(pivot.entry, collisionNode(entry, left, pivot.left, work), pivot.right, work);\n }\n const middle = pivot.left;\n return collisionNode(middle.entry, collisionNode(entry, left, middle.left, work), collisionNode(pivot.entry, middle.right, pivot.right, work), work);\n }\n return collisionNode(entry, left, right, work);\n}\nfunction compareIdentity(left, right, work) {\n work.identityComparisons += 1;\n return left < right ? -1 : left > right ? 1 : 0;\n}\nfunction collisionGet(root, key, work) {\n let current = root;\n while (current !== null) {\n const comparison = work === undefined\n ? key < current.entry.key\n ? -1\n : key > current.entry.key\n ? 1\n : 0\n : compareIdentity(key, current.entry.key, work);\n if (comparison < 0)\n current = current.left;\n else if (comparison > 0)\n current = current.right;\n else\n return current.entry.value;\n }\n return undefined;\n}\nfunction collisionSet(root, entry, work) {\n if (root === null)\n return collisionNode(entry, null, null, work);\n const comparison = compareIdentity(entry.key, root.entry.key, work);\n if (comparison < 0) {\n return rebalanceCollision(root.entry, collisionSet(root.left, entry, work), root.right, work);\n }\n if (comparison > 0) {\n return rebalanceCollision(root.entry, root.left, collisionSet(root.right, entry, work), work);\n }\n if (Object.is(root.entry.value, entry.value))\n return root;\n return collisionNode(entry, root.left, root.right, work);\n}\nfunction extractCollisionMinimum(root, work) {\n if (root.left === null)\n return { root: root.right, minimum: root.entry };\n const extracted = extractCollisionMinimum(root.left, work);\n return {\n minimum: extracted.minimum,\n root: rebalanceCollision(root.entry, extracted.root, root.right, work),\n };\n}\nfunction collisionDelete(root, key, work) {\n if (root === null)\n return null;\n const comparison = compareIdentity(key, root.entry.key, work);\n if (comparison < 0) {\n const left = collisionDelete(root.left, key, work);\n if (left === root.left)\n return root;\n return rebalanceCollision(root.entry, left, root.right, work);\n }\n if (comparison > 0) {\n const right = collisionDelete(root.right, key, work);\n if (right === root.right)\n return root;\n return rebalanceCollision(root.entry, root.left, right, work);\n }\n if (root.left === null)\n return root.right;\n if (root.right === null)\n return root.left;\n const extracted = extractCollisionMinimum(root.right, work);\n return rebalanceCollision(extracted.minimum, root.left, extracted.root, work);\n}\nfunction minimumCollisionEntry(root) {\n let current = root;\n while (current.left !== null)\n current = current.left;\n return current.entry;\n}\nfunction hashCollision(hash, root, work) {\n work.nodesCreated += 1;\n return { kind: \"collision\", hash, root, count: root.count, sum: root.sum };\n}\nfunction hashBranch(bitmap, children, work) {\n work.nodesCreated += 1;\n return {\n kind: \"branch\",\n bitmap: bitmap >>> 0,\n children,\n count: children.reduce((count, child) => count + child.count, 0),\n sum: children.reduce((sum, child) => sum + child.sum, 0),\n };\n}\nfunction mergeHashTerminals(left, right, shift, work) {\n const leftFragment = hashFragment(left.hash, shift);\n const rightFragment = hashFragment(right.hash, shift);\n if (leftFragment === rightFragment) {\n const child = mergeHashTerminals(left, right, shift + 5, work);\n return hashBranch(hashBit(leftFragment), [child], work);\n }\n const leftBit = hashBit(leftFragment);\n const rightBit = hashBit(rightFragment);\n return hashBranch((leftBit | rightBit) >>> 0, leftFragment < rightFragment ? [left, right] : [right, left], work);\n}\nfunction hashGetNode(root, key, hash, shift, work) {\n if (root === null)\n return undefined;\n if (root.kind !== \"branch\") {\n if (root.hash !== hash)\n return undefined;\n if (root.kind === \"leaf\") {\n if (work !== undefined)\n work.identityComparisons += 1;\n return root.entry.key === key ? root.entry.value : undefined;\n }\n return collisionGet(root.root, key, work);\n }\n const bit = hashBit(hashFragment(hash, shift));\n if ((root.bitmap & bit) === 0)\n return undefined;\n return hashGetNode(root.children[hashPosition(root.bitmap, bit)], key, hash, shift + 5, work);\n}\nfunction hashGet(root, key, work) {\n if (work !== undefined)\n work.identityLookups += 1;\n return hashGetNode(root, key, hashIdentity(key), 0, work);\n}\nfunction hashSetNode(root, key, value, hash, shift, work) {\n if (root === null)\n return hashLeaf(hash, { key, value }, work);\n if (root.kind !== \"branch\") {\n if (root.hash !== hash) {\n return mergeHashTerminals(root, hashLeaf(hash, { key, value }, work), shift, work);\n }\n if (root.kind === \"leaf\") {\n work.identityComparisons += 1;\n if (root.entry.key === key) {\n return Object.is(root.entry.value, value)\n ? root\n : hashLeaf(hash, { key, value }, work);\n }\n let collisionRoot = collisionSet(null, root.entry, work);\n collisionRoot = collisionSet(collisionRoot, { key, value }, work);\n return hashCollision(hash, collisionRoot, work);\n }\n const collisionRoot = collisionSet(root.root, { key, value }, work);\n return collisionRoot === root.root\n ? root\n : hashCollision(hash, collisionRoot, work);\n }\n const bit = hashBit(hashFragment(hash, shift));\n const position = hashPosition(root.bitmap, bit);\n if ((root.bitmap & bit) === 0) {\n const children = [...root.children];\n children.splice(position, 0, hashLeaf(hash, { key, value }, work));\n return hashBranch((root.bitmap | bit) >>> 0, children, work);\n }\n const child = hashSetNode(root.children[position], key, value, hash, shift + 5, work);\n if (child === root.children[position])\n return root;\n const children = [...root.children];\n children[position] = child;\n return hashBranch(root.bitmap, children, work);\n}\nfunction hashSet(root, key, value, work) {\n work.identityLookups += 1;\n return hashSetNode(root, key, value, hashIdentity(key), 0, work);\n}\nfunction hashDeleteNode(root, key, hash, shift, work) {\n if (root === null)\n return null;\n if (root.kind !== \"branch\") {\n if (root.hash !== hash)\n return root;\n if (root.kind === \"leaf\") {\n work.identityComparisons += 1;\n return root.entry.key === key ? null : root;\n }\n const collisionRoot = collisionDelete(root.root, key, work);\n if (collisionRoot === root.root)\n return root;\n if (collisionRoot === null)\n return null;\n if (collisionRoot.count === 1) {\n return hashLeaf(hash, minimumCollisionEntry(collisionRoot), work);\n }\n return hashCollision(hash, collisionRoot, work);\n }\n const bit = hashBit(hashFragment(hash, shift));\n if ((root.bitmap & bit) === 0)\n return root;\n const position = hashPosition(root.bitmap, bit);\n const child = hashDeleteNode(root.children[position], key, hash, shift + 5, work);\n if (child === root.children[position])\n return root;\n if (child === null) {\n if (root.children.length === 1)\n return null;\n const children = root.children.filter((_, childIndex) => childIndex !== position);\n if (children.length === 1 && children[0]?.kind !== \"branch\") {\n return children[0];\n }\n return hashBranch((root.bitmap & ~bit) >>> 0, children, work);\n }\n const children = [...root.children];\n children[position] = child;\n return hashBranch(root.bitmap, children, work);\n}\nfunction hashDelete(root, key, work) {\n work.identityLookups += 1;\n return hashDeleteNode(root, key, hashIdentity(key), 0, work);\n}\nfunction mapNode(key, value, left, right, work) {\n work.nodesCreated += 1;\n return {\n key,\n value,\n left,\n right,\n height: 1 + Math.max(nodeHeight(left), nodeHeight(right)),\n };\n}\nfunction rebalanceMap(key, value, left, right, work) {\n if (nodeHeight(left) > nodeHeight(right) + 1) {\n const pivot = left;\n if (nodeHeight(pivot.left) >= nodeHeight(pivot.right)) {\n return mapNode(pivot.key, pivot.value, pivot.left, mapNode(key, value, pivot.right, right, work), work);\n }\n const middle = pivot.right;\n return mapNode(middle.key, middle.value, mapNode(pivot.key, pivot.value, pivot.left, middle.left, work), mapNode(key, value, middle.right, right, work), work);\n }\n if (nodeHeight(right) > nodeHeight(left) + 1) {\n const pivot = right;\n if (nodeHeight(pivot.right) >= nodeHeight(pivot.left)) {\n return mapNode(pivot.key, pivot.value, mapNode(key, value, left, pivot.left, work), pivot.right, work);\n }\n const middle = pivot.left;\n return mapNode(middle.key, middle.value, mapNode(key, value, left, middle.left, work), mapNode(pivot.key, pivot.value, middle.right, pivot.right, work), work);\n }\n return mapNode(key, value, left, right, work);\n}\nfunction mapSet(root, key, value, work) {\n if (root === null)\n return mapNode(key, value, null, null, work);\n if (key < root.key) {\n return rebalanceMap(root.key, root.value, mapSet(root.left, key, value, work), root.right, work);\n }\n if (key > root.key) {\n return rebalanceMap(root.key, root.value, root.left, mapSet(root.right, key, value, work), work);\n }\n if (Object.is(root.value, value))\n return root;\n return mapNode(key, value, root.left, root.right, work);\n}\nfunction extractMapMinimum(root, work) {\n if (root.left === null)\n return { root: root.right, minimum: root };\n const extracted = extractMapMinimum(root.left, work);\n return {\n minimum: extracted.minimum,\n root: rebalanceMap(root.key, root.value, extracted.root, root.right, work),\n };\n}\nfunction mapDelete(root, key, work) {\n if (root === null)\n return null;\n if (key < root.key) {\n const left = mapDelete(root.left, key, work);\n if (left === root.left)\n return root;\n return rebalanceMap(root.key, root.value, left, root.right, work);\n }\n if (key > root.key) {\n const right = mapDelete(root.right, key, work);\n if (right === root.right)\n return root;\n return rebalanceMap(root.key, root.value, root.left, right, work);\n }\n if (root.left === null)\n return root.right;\n if (root.right === null)\n return root.left;\n const extracted = extractMapMinimum(root.right, work);\n return rebalanceMap(extracted.minimum.key, extracted.minimum.value, root.left, extracted.root, work);\n}\nfunction minimumMapEntry(root) {\n let current = root;\n while (current?.left !== null && current?.left !== undefined) {\n current = current.left;\n }\n return current ?? undefined;\n}\nfunction normalizeHeight(height, label) {\n if (!Number.isFinite(height) || height <= 0) {\n throw new RangeError(`${label} must be a finite number greater than zero.`);\n }\n return height;\n}\nfunction encodeStableKey(key) {\n if (typeof key === \"string\")\n return `s:${key.length}:${key}`;\n if (typeof key !== \"number\") {\n throw new TypeError(\"A row-height stable key must be a string or number.\");\n }\n if (Number.isNaN(key))\n return \"n:NaN\";\n if (key === 0)\n return \"n:0\";\n return `n:${String(key)}`;\n}\nfunction assertExistingIndex(index, count, label) {\n if (!Number.isSafeInteger(index) || index < 0 || index >= count) {\n throw new RangeError(`${label} ${index} is out of bounds.`);\n }\n}\nfunction assertInsertIndex(index, count) {\n if (!Number.isSafeInteger(index) || index < 0 || index > count) {\n throw new RangeError(`Row insertion index ${index} is out of bounds.`);\n }\n}\nfunction ticketKey(ticket) {\n return String(ticket).padStart(TICKET_KEY_WIDTH, \"0\");\n}\nfunction takeNextTicket(ticket) {\n if (!Number.isSafeInteger(ticket) ||\n ticket < 0 ||\n ticket >= Number.MAX_SAFE_INTEGER) {\n throw new RangeError(\"Removed-measurement retention ticket space is exhausted.\");\n }\n return ticket + 1;\n}\nclass PersistentRowHeightIndex {\n #defaultHeight;\n #getKey;\n #root;\n #visibleKeys;\n /**\n * INVARIANT (Amendment I §1): `#visibleSlots !== undefined` ⇔ this\n * generation is DENSE ⇔ every sequence entry carries a `denseKey` less\n * than `#denseCapacity`. A dense generation does NOT maintain\n * `#visibleKeys` (it stays `null`); a string generation never allocates\n * `#visibleSlots`. Measurements, tombstones, and retention order stay\n * string-identity-keyed in BOTH lanes — slot reuse must never touch\n * retention (the amendment's §3 trap).\n */\n #denseCapacity;\n #visibleSlots;\n #measurements;\n #tombstones;\n #tombstoneOrder;\n #nextTicket;\n #maxRetainedMeasurements;\n diagnostics;\n constructor(options) {\n this.#defaultHeight = options.defaultHeight;\n this.#getKey = options.getKey;\n this.#root = options.root;\n this.#visibleKeys = options.visibleKeys;\n this.#denseCapacity = options.denseCapacity;\n this.#visibleSlots = options.visibleSlots;\n this.#measurements = options.measurements;\n this.#tombstones = options.tombstones;\n this.#tombstoneOrder = options.tombstoneOrder;\n this.#nextTicket = options.nextTicket;\n this.#maxRetainedMeasurements = options.maxRetainedMeasurements;\n this.diagnostics = Object.freeze({\n nodesCreated: options.work.nodesCreated,\n entriesVisited: options.work.entriesVisited,\n treeDepth: nodeHeight(options.root),\n identityLookups: options.work.identityLookups,\n identityComparisons: options.work.identityComparisons,\n measurementEntriesScanned: options.work.measurementEntriesScanned,\n previousEntriesScanned: options.work.previousEntriesScanned,\n sortComparisons: options.work.sortComparisons,\n reorderEntriesReused: options.work.reorderEntriesReused,\n refilterEntriesReused: options.work.refilterEntriesReused,\n refilterEntriesInserted: options.work.refilterEntriesInserted,\n refilterEntriesRetired: options.work.refilterEntriesRetired,\n reorderEntriesRemeasured: options.work.reorderEntriesRemeasured,\n visibleMeasurementCount: hashCount(options.measurements) - hashCount(options.tombstones),\n tombstoneCount: hashCount(options.tombstones),\n measurementCacheCount: hashCount(options.measurements),\n });\n }\n get rowCount() {\n return nodeCount(this.#root);\n }\n /**\n * Derivation — what must be empty for a bulk replacement to be\n * byte-equivalent to the cooperative one. The cooperative builder consults\n * prior state in exactly three places:\n *\n * 1. The ingest's measured-height lookup reads `#measurements` — a hit makes\n * a produced entry `measured` with the cached height.\n * 2. The `scan-retained` walk reads `#tombstoneOrder` (whose entries mirror\n * `#tombstones`) to carry removed-row measurements forward.\n * 3. The `scan-visible` walk retains a prior VISIBLE entry's measurement\n * only when `value.measured` — and a visible entry is `measured` only\n * while its identity is in `#measurements` (`measure` sets both,\n * `apply`'s re-estimate clears both), so `#measurements` empty makes this\n * branch unreachable.\n * 4. Both paths also walk the prior visible sequence to let a SURVIVING\n * row's height ride (`#rideSurvivorHeight`, #516) — the one read of\n * sequence entry VALUES — and they do it identically, so it does not\n * enter this predicate.\n *\n * `#visibleKeys`, `#nextTicket`, and the sequence entries themselves are\n * otherwise never read for values — the builder rebuilds the key set and\n * sequence from the source — so a populated but never-measured index (e.g.\n * 50k rows at true mount) has NO retained state: every lookup above would\n * miss, and a bulk build over the source produces the identical index.\n * The predicate is therefore exactly \"measurements, tombstones, and\n * retention order are all empty\".\n */\n get hasRetainedState() {\n return (hashCount(this.#measurements) > 0 ||\n hashCount(this.#tombstones) > 0 ||\n this.#tombstoneOrder !== null);\n }\n getHeight(index) {\n if (!Number.isSafeInteger(index))\n return 0;\n return sequenceAt(this.#root, index)?.height ?? 0;\n }\n getOffsetForIndex(index) {\n if (Number.isNaN(index) || index <= 0 || this.#root === null)\n return 0;\n if (index === Number.POSITIVE_INFINITY || index >= this.rowCount) {\n return this.getTotalHeight();\n }\n let target = Math.floor(index);\n let current = this.#root;\n let offset = 0;\n while (current !== null) {\n const leftCount = nodeCount(current.left);\n if (target <= leftCount)\n current = current.left;\n else {\n offset += nodePixels(current.left);\n if (target === leftCount + 1)\n return offset + current.value.height;\n offset += current.value.height;\n target -= leftCount + 1;\n current = current.right;\n }\n }\n return offset;\n }\n getIndexForOffset(offset) {\n if (Number.isNaN(offset) || offset <= 0 || this.#root === null)\n return 0;\n if (offset >= this.getTotalHeight())\n return this.rowCount;\n let current = this.#root;\n let remaining = offset;\n let rank = 0;\n while (current !== null) {\n const leftPixels = nodePixels(current.left);\n if (remaining < leftPixels) {\n current = current.left;\n continue;\n }\n remaining -= leftPixels;\n const leftCount = nodeCount(current.left);\n if (remaining < current.value.height)\n return rank + leftCount;\n remaining -= current.value.height;\n rank += leftCount + 1;\n current = current.right;\n }\n return rank;\n }\n getTotalHeight() {\n return nodePixels(this.#root);\n }\n keyAt(index) {\n if (!Number.isSafeInteger(index))\n return undefined;\n return sequenceAt(this.#root, index)?.ref;\n }\n hasMeasurement(ref) {\n return hashGet(this.#measurements, this.#identity(ref)) !== undefined;\n }\n getMeasuredHeightMean() {\n const count = hashCount(this.#measurements);\n return count === 0 ? undefined : hashSum(this.#measurements) / count;\n }\n measure(index, ref, height) {\n assertExistingIndex(index, this.rowCount, \"Row measurement index\");\n const normalized = normalizeHeight(height, \"Measured row height\");\n const identity = this.#identity(ref);\n const current = sequenceAt(this.#root, index);\n this.#assertIdentity(current, identity);\n if (current.measured && current.height === normalized)\n return this;\n const work = createWork(1);\n const measurements = hashSet(this.#measurements, identity, normalized, work);\n const root = updateSequence(this.#root, index, { ...current, height: normalized, measured: true }, work);\n return this.#next(root, this.#visibleKeys, this.#denseCapacity, this.#visibleSlots, measurements, this.#tombstones, this.#tombstoneOrder, this.#nextTicket, work);\n }\n retainMeasurement(ref, height, denseKey) {\n const normalized = normalizeHeight(height, \"Measured row height\");\n const identity = this.#identity(ref);\n const work = createWork(1);\n if (this.#visibleSlots !== undefined) {\n // Dense generation: `#visibleKeys` is null, so the string-lane guard\n // below would be vacuous — visibility is answered by the slot bitset.\n if (denseKey === undefined) {\n throw new RowHeightReplacementLifecycleError(\"failed\", \"A dense row-height index requires dense-keyed operations; \" +\n \"fall back to a full replacement.\");\n }\n if (!Number.isSafeInteger(denseKey) || denseKey < 0) {\n // Mirror the insert arm: a negative or fractional key would silently\n // mis-read here (1.5's `&31` truncation reads a DIFFERENT row's bit).\n throw new RangeError(`Dense row-height key ${denseKey} must be a non-negative ` +\n \"safe integer.\");\n }\n if (testDenseBit(this.#visibleSlots, denseKey)) {\n throw new RangeError(\"Cannot retain an absent measurement for a visible row.\");\n }\n }\n else if (hashGet(this.#visibleKeys, identity, work) !== undefined) {\n throw new RangeError(\"Cannot retain an absent measurement for a visible row.\");\n }\n if (this.#maxRetainedMeasurements === 0)\n return this;\n let measurements = hashSet(this.#measurements, identity, normalized, work);\n let tombstones = this.#tombstones;\n let tombstoneOrder = this.#tombstoneOrder;\n const previousTicket = hashGet(tombstones, identity, work);\n if (previousTicket !== undefined) {\n tombstoneOrder = mapDelete(tombstoneOrder, ticketKey(previousTicket), work);\n }\n const ticket = this.#nextTicket;\n const nextTicket = takeNextTicket(ticket);\n tombstones = hashSet(tombstones, identity, ticket, work);\n tombstoneOrder = mapSet(tombstoneOrder, ticketKey(ticket), identity, work);\n while (hashCount(tombstones) > this.#maxRetainedMeasurements) {\n const oldest = minimumMapEntry(tombstoneOrder);\n if (oldest === undefined) {\n throw new Error(\"Removed-measurement retention is inconsistent.\");\n }\n tombstoneOrder = mapDelete(tombstoneOrder, oldest.key, work);\n tombstones = hashDelete(tombstones, oldest.value, work);\n measurements = hashDelete(measurements, oldest.value, work);\n }\n return this.#next(this.#root, this.#visibleKeys, this.#denseCapacity, this.#visibleSlots, measurements, tombstones, tombstoneOrder, nextTicket, work);\n }\n apply(operations) {\n if (operations.length === 0)\n return this;\n let root = this.#root;\n let visibleKeys = this.#visibleKeys;\n let denseCapacity = this.#denseCapacity;\n let visibleSlots = this.#visibleSlots;\n // The slot bitset is MUTABLE, so the persistent contract demands a clone\n // before the first membership write of this call; reference equality with\n // `this.#visibleSlots` doubles as the no-op signal below.\n let slotsShared = true;\n let measurements = this.#measurements;\n let tombstones = this.#tombstones;\n let tombstoneOrder = this.#tombstoneOrder;\n const work = createWork();\n let nextTicket = this.#nextTicket;\n for (const operation of operations) {\n work.entriesVisited += 1;\n if (visibleSlots !== undefined && operation.denseKey === undefined) {\n throw new RowHeightReplacementLifecycleError(\"failed\", \"A dense row-height index requires dense-keyed operations; \" +\n \"fall back to a full replacement.\");\n }\n if (operation.kind === \"insert\") {\n assertInsertIndex(operation.index, nodeCount(root));\n const identity = this.#identity(operation.ref);\n if (visibleSlots !== undefined) {\n const denseKey = operation.denseKey;\n if (!Number.isSafeInteger(denseKey) || denseKey < 0) {\n throw new RangeError(`Dense row-height key ${denseKey} must be a non-negative ` +\n \"safe integer.\");\n }\n if (testDenseBit(visibleSlots, denseKey)) {\n throw new Error(`Duplicate dense row-height slot ${denseKey}: ${identity}`);\n }\n }\n else if (hashGet(visibleKeys, identity, work) !== undefined) {\n throw new Error(`Duplicate stable row-height key: ${identity}`);\n }\n const estimatedHeight = this.#estimated(operation.estimatedHeight);\n const measuredHeight = hashGet(measurements, identity, work);\n const retainedTicket = hashGet(tombstones, identity, work);\n root = insertSequence(root, operation.index, {\n ref: operation.ref,\n identity,\n estimatedHeight: operation.estimatedHeight,\n height: measuredHeight ?? estimatedHeight,\n measured: measuredHeight !== undefined,\n denseKey: operation.denseKey,\n }, work);\n if (visibleSlots !== undefined) {\n const denseKey = operation.denseKey;\n const neededCapacity = Math.max(denseCapacity, denseKey + 1);\n if (slotsShared) {\n visibleSlots = cloneDenseMembership(visibleSlots, neededCapacity);\n slotsShared = false;\n }\n else if (denseKey >>> 5 >= visibleSlots.length) {\n visibleSlots = cloneDenseMembership(visibleSlots, neededCapacity);\n }\n setDenseBit(visibleSlots, denseKey);\n denseCapacity = neededCapacity;\n }\n else {\n visibleKeys = hashSet(visibleKeys, identity, true, work);\n }\n if (retainedTicket !== undefined) {\n tombstones = hashDelete(tombstones, identity, work);\n tombstoneOrder = mapDelete(tombstoneOrder, ticketKey(retainedTicket), work);\n }\n continue;\n }\n const sourceIndex = operation.kind === \"remove\" || operation.kind === \"move\"\n ? operation.previousIndex\n : operation.index;\n assertExistingIndex(sourceIndex, nodeCount(root), \"Row operation index\");\n const identity = this.#identity(operation.ref);\n const current = sequenceAt(root, sourceIndex);\n this.#assertIdentity(current, identity);\n // Dense slot-drift guard for every variant that resolves a current\n // entry (remove, move, update — insert has no current entry; its slot\n // is range-validated and duplicate-checked in its own arm instead): a\n // caller whose slot view drifted from the entry's stamped slot must\n // fail loud rather than silently clearing or riding the wrong bit.\n if (visibleSlots !== undefined &&\n operation.denseKey !== current.denseKey) {\n throw new RowHeightReplacementLifecycleError(\"failed\", `Dense slot drift: operation denseKey ${operation.denseKey} does ` +\n `not match the entry's stamped slot ${current.denseKey} for ` +\n `${identity}; fall back to a full replacement.`);\n }\n if (operation.kind === \"remove\") {\n root = removeSequence(root, sourceIndex, work).root;\n if (visibleSlots !== undefined) {\n // Clear by the ENTRY's stamped slot — the one that set the bit —\n // which the identity assertion above ties to the caller's ref.\n if (slotsShared) {\n visibleSlots = cloneDenseMembership(visibleSlots, denseCapacity);\n slotsShared = false;\n }\n clearDenseBit(visibleSlots, current.denseKey);\n }\n else {\n visibleKeys = hashDelete(visibleKeys, identity, work);\n }\n if (current.measured) {\n if (this.#maxRetainedMeasurements === 0) {\n measurements = hashDelete(measurements, identity, work);\n }\n else {\n const ticket = nextTicket;\n nextTicket = takeNextTicket(nextTicket);\n tombstones = hashSet(tombstones, identity, ticket, work);\n tombstoneOrder = mapSet(tombstoneOrder, ticketKey(ticket), identity, work);\n while (hashCount(tombstones) > this.#maxRetainedMeasurements) {\n const oldest = minimumMapEntry(tombstoneOrder);\n if (oldest === undefined) {\n throw new Error(\"Removed-measurement retention is inconsistent.\");\n }\n tombstoneOrder = mapDelete(tombstoneOrder, oldest.key, work);\n tombstones = hashDelete(tombstones, oldest.value, work);\n measurements = hashDelete(measurements, oldest.value, work);\n }\n }\n }\n }\n else if (operation.kind === \"move\") {\n assertExistingIndex(operation.index, nodeCount(root), \"Row move destination index\");\n if (operation.index === operation.previousIndex)\n continue;\n const removed = removeSequence(root, operation.previousIndex, work);\n root = insertSequence(removed.root, operation.index, removed.value, work);\n }\n else {\n const estimatedHeight = this.#estimated(operation.estimatedHeight);\n if (!current.measured &&\n current.estimatedHeight === operation.estimatedHeight) {\n continue;\n }\n measurements = hashDelete(measurements, identity, work);\n root = updateSequence(root, operation.index, {\n ...current,\n estimatedHeight: operation.estimatedHeight,\n height: estimatedHeight,\n measured: false,\n }, work);\n }\n }\n if (root === this.#root &&\n visibleKeys === this.#visibleKeys &&\n visibleSlots === this.#visibleSlots &&\n denseCapacity === this.#denseCapacity &&\n measurements === this.#measurements &&\n tombstones === this.#tombstones &&\n tombstoneOrder === this.#tombstoneOrder &&\n nextTicket === this.#nextTicket) {\n return this;\n }\n return this.#next(root, visibleKeys, denseCapacity, visibleSlots, measurements, tombstones, tombstoneOrder, nextTicket, work);\n }\n /**\n * Builds a source with NO `denseCapacity`, so on a dense generation this\n * is a deliberate LANE EXIT: the result is a string-lane generation (the\n * full-replacement path is where the lane is legally re-decided).\n */\n replace(rows) {\n const builder = this.beginReplacement({\n rowCount: rows.length,\n entryAt: (index) => rows[index],\n });\n while (!builder.done)\n builder.advance({ maxUnits: 256 });\n return builder.finish();\n }\n /**\n * Synchronous BY DESIGN, like `reorder`/`refilter`: the row set stands\n * still, only the estimator's inputs changed, so one in-order pass over\n * the existing entries plus a balanced rebuild answers it — no source, no\n * identity re-hash, no HAMT work. Measurements, tombstones, retention\n * order, and the lane (dense bitset included) are carried through\n * verbatim; only entries with an `estimatedHeight` are rewritten. See the\n * interface docblock for the semantics.\n */\n clearEstimates() {\n if (this.#root === null)\n return this;\n const work = createWork();\n const values = [];\n let changed = false;\n const stack = [];\n let cursor = this.#root;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n const value = node.value;\n work.previousEntriesScanned += 1;\n if (value.estimatedHeight === undefined) {\n values.push(value);\n }\n else {\n changed = true;\n values.push({\n ...value,\n estimatedHeight: undefined,\n // A measurement is a fact the DOM reported and survives; an\n // estimate is arithmetic over the inputs that just changed.\n height: value.measured ? value.height : this.#defaultHeight,\n });\n }\n cursor = node.right;\n }\n if (!changed)\n return this;\n const root = buildBalancedSequence(values, 0, values.length, work);\n return this.#next(root, this.#visibleKeys, this.#denseCapacity, this.#visibleSlots, this.#measurements, this.#tombstones, this.#tombstoneOrder, this.#nextTicket, work);\n }\n /**\n * Synchronous BY DESIGN: a sort-only commit reorders EXISTING rows whose\n * heights are already known, so only the ordered structure and its prefix\n * sums change — no re-measure, no re-estimate, no identity re-hash beyond\n * the per-row key encoding. Measured ~10–20ms at 50k rows versus ~215ms of\n * cooperative `beginReplacement` re-ingest (identity hash + HAMT insert +\n * frozen rowRef per row, in 8ms slices), which is the whole point of the\n * method. The caller (renderer-dom's row-layout controller) falls back to a\n * full replacement on ANY throw, so violations of the permutation contract\n * fail loud here rather than fabricating entries.\n */\n reorder(source) {\n const rowCount = source.rowCount;\n if (!Number.isSafeInteger(rowCount) || rowCount < 0) {\n throw new RangeError(\"Reorder source rowCount must be a non-negative safe integer.\");\n }\n const entryAt = source.entryAt;\n if (typeof entryAt !== \"function\") {\n throw new TypeError(\"Reorder source entryAt must be a function.\");\n }\n if (rowCount !== this.rowCount) {\n throw new RangeError(`Reorder source rowCount (${rowCount}) must equal the current row ` +\n `count (${this.rowCount}); reorder permutes the existing rows only.`);\n }\n if (rowCount === 0)\n return this;\n const boundEntryAt = entryAt.bind(source);\n if (this.#visibleSlots !== undefined) {\n // Dense generation (Amendment I): resolve the permutation by slot.\n // The string-lane body below stays INLINE and byte-identical to its\n // pre-dense form deliberately (the Task 3 pin: the string lane must be\n // provably untouched by diff alone): do not unify the lanes or hoist\n // the shared walks into helpers.\n return this.#reorderDense(boundEntryAt, rowCount);\n }\n const work = createWork();\n // One in-order pass over the current sequence: the by-identity lookup\n // table for the walk below, and the old order for no-op detection.\n const previousValues = [];\n const unconsumed = new Map();\n {\n const stack = [];\n let cursor = this.#root;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n previousValues.push(node.value);\n unconsumed.set(node.value.identity, node.value);\n work.previousEntriesScanned += 1;\n cursor = node.right;\n }\n }\n // Walk the new order, relinking each EXISTING entry verbatim. Estimates\n // and measurements ride along untouched inside the reused entry objects,\n // so the source's `estimatedHeight`s are deliberately ignored.\n const values = new Array(rowCount);\n let unchanged = true;\n for (let index = 0; index < rowCount; index += 1) {\n const row = boundEntryAt(index);\n const identity = this.#identity(row.key);\n work.entriesVisited += 1;\n work.identityLookups += 1;\n const value = unconsumed.get(identity);\n if (value === undefined) {\n throw new Error(`Reorder key does not match an existing row (missing, or ` +\n `duplicated in the new order): ${identity}`);\n }\n unconsumed.delete(identity);\n values[index] = value;\n work.reorderEntriesReused += 1;\n if (value !== previousValues[index])\n unchanged = false;\n }\n if (unchanged)\n return this;\n const root = buildBalancedSequence(values, 0, rowCount, work);\n return this.#next(root, this.#visibleKeys, this.#denseCapacity, this.#visibleSlots, this.#measurements, this.#tombstones, this.#tombstoneOrder, this.#nextTicket, work);\n }\n /**\n * Dense-lane reorder (Amendment I): the permutation resolves each source\n * row by its `denseKey` (model slot) against a slot-indexed array — ZERO\n * identity strings on the hot path; identities are computed only to name\n * a row in an error. Key validation mirrors the builder's\n * `#ingestDenseKey` cases (missing / malformed / out-of-range → lifecycle\n * error), which the controller's fallback-on-throw contract routes to a\n * full replacement that re-decides the lane. Membership is unchanged by\n * construction — reorder permutes the existing rows — so the generation\n * carries `#visibleSlots` and `#denseCapacity` forward untouched.\n *\n * TRUST BOUNDARY: a resolved row's `row.key` is trusted to match the\n * slot's stored identity and deliberately never re-verified — that\n * verification IS the per-row string cost this lane exists to delete.\n * `apply` guards slot drift instead, because its operations are k-sized.\n */\n #reorderDense(boundEntryAt, rowCount) {\n const capacity = this.#denseCapacity;\n const work = createWork();\n // One in-order pass over the current sequence: the by-slot lookup table\n // for the walk below, and the old order for no-op detection.\n const previousValues = [];\n const unconsumedBySlot = new Array(capacity);\n {\n const stack = [];\n let cursor = this.#root;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n previousValues.push(node.value);\n unconsumedBySlot[node.value.denseKey] = node.value;\n work.previousEntriesScanned += 1;\n cursor = node.right;\n }\n }\n // Walk the new order, relinking each EXISTING entry verbatim. Estimates\n // and measurements ride along untouched inside the reused entry objects,\n // so the source's `estimatedHeight`s are deliberately ignored.\n const values = new Array(rowCount);\n let unchanged = true;\n for (let index = 0; index < rowCount; index += 1) {\n const row = boundEntryAt(index);\n work.entriesVisited += 1;\n const denseKey = row.denseKey;\n if (denseKey === undefined) {\n throw new RowHeightReplacementLifecycleError(\"failed\", \"A dense row-height index requires a denseKey on every source \" +\n `row (${this.#identity(row.key)} carries none); fall back to ` +\n \"a full replacement.\");\n }\n if (!Number.isSafeInteger(denseKey) ||\n denseKey < 0 ||\n denseKey >= capacity) {\n throw new RowHeightReplacementLifecycleError(\"failed\", `Dense key ${denseKey} for row ${this.#identity(row.key)} is ` +\n `outside the dense generation's capacity ${capacity}.`);\n }\n const value = unconsumedBySlot[denseKey];\n if (value === undefined) {\n throw new Error(`Reorder slot does not match an existing row (missing, or ` +\n `duplicated in the new order): ${denseKey}`);\n }\n unconsumedBySlot[denseKey] = undefined;\n values[index] = value;\n work.reorderEntriesReused += 1;\n if (value !== previousValues[index])\n unchanged = false;\n }\n if (unchanged)\n return this;\n const root = buildBalancedSequence(values, 0, rowCount, work);\n return this.#next(root, this.#visibleKeys, this.#denseCapacity, this.#visibleSlots, this.#measurements, this.#tombstones, this.#tombstoneOrder, this.#nextTicket, work);\n }\n /**\n * Synchronous BY DESIGN (Amendment G, G3b): a filter-only commit changes\n * MEMBERSHIP while surviving rows keep their relative order and their\n * already-measured heights, so the cooperative replacement's per-row\n * re-ingest and its sliced interval — the window the blank-viewport defect\n * lived in — are pure overhead here. Measured in Node against dist:\n * a 50k→12.5k narrowing runs 15–26ms (the amendment's 20–25ms ceiling);\n * a 12.5k→50k widening runs ~57–80ms, dominated by the fresh ingest of\n * 37.5k entrants — above the cost model's 30–35ms projection but still one\n * synchronous pass with no replacement interval, versus the 45–63ms sliced\n * cooperative flush (`reingest-composition.md`). Retention semantics deliberately mirror the\n * cooperative path observable-for-observable: entrants reuse a retained\n * (tombstoned) measurement when one exists, measured leavers tombstone in\n * old-sequence ticket order (or drop outright at cap 0), unmeasured\n * leavers vanish, and cap pressure evicts oldest-first. The caller\n * (renderer-dom's row-layout controller) falls back to a full replacement\n * on ANY throw.\n */\n refilter(source) {\n const rowCount = source.rowCount;\n if (!Number.isSafeInteger(rowCount) || rowCount < 0) {\n throw new RangeError(\"Refilter source rowCount must be a non-negative safe integer.\");\n }\n const entryAt = source.entryAt;\n if (typeof entryAt !== \"function\") {\n throw new TypeError(\"Refilter source entryAt must be a function.\");\n }\n const boundEntryAt = entryAt.bind(source);\n if (this.#visibleSlots !== undefined) {\n // Dense generation (Amendment I): resolve survivors by slot.\n // The string-lane body below stays INLINE and byte-identical to its\n // pre-dense form deliberately (the Task 3 pin: the string lane must be\n // provably untouched by diff alone): do not unify the lanes or hoist\n // the shared walks into helpers.\n return this.#refilterDense(boundEntryAt, rowCount);\n }\n const work = createWork();\n // One in-order pass over the current sequence: the by-identity lookup\n // table for the walk below, and the old order for no-op detection.\n const previousValues = [];\n const unconsumed = new Map();\n {\n const stack = [];\n let cursor = this.#root;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n previousValues.push(node.value);\n unconsumed.set(node.value.identity, node.value);\n work.previousEntriesScanned += 1;\n cursor = node.right;\n }\n }\n // Walk the new order: survivors relink verbatim (their measurements and\n // estimates ride, exactly as in `reorder`), entrants ingest fresh under\n // the cooperative path's rule — measured-lookup against the FULL cache,\n // so a returning tombstoned key gets its retained measurement back and\n // sheds its tombstone.\n const values = new Array(rowCount);\n const seen = new Set();\n let visibleKeys = null;\n let measurements = this.#measurements;\n let tombstones = this.#tombstones;\n let tombstoneOrder = this.#tombstoneOrder;\n let nextTicket = this.#nextTicket;\n let unchanged = rowCount === previousValues.length;\n for (let index = 0; index < rowCount; index += 1) {\n const row = boundEntryAt(index);\n const identity = this.#identity(row.key);\n work.entriesVisited += 1;\n work.identityLookups += 1;\n if (seen.has(identity)) {\n throw new Error(`Duplicate stable row-height key: ${identity}`);\n }\n seen.add(identity);\n visibleKeys = hashSet(visibleKeys, identity, true, work);\n const existing = unconsumed.get(identity);\n if (existing !== undefined) {\n unconsumed.delete(identity);\n values[index] = existing;\n work.refilterEntriesReused += 1;\n if (existing !== previousValues[index])\n unchanged = false;\n continue;\n }\n unchanged = false;\n const estimatedHeight = this.#estimated(row.estimatedHeight);\n const measuredHeight = hashGet(measurements, identity, work);\n if (measuredHeight !== undefined) {\n work.measurementEntriesScanned += 1;\n // A tombstone can only exist where a retained measurement does, so\n // the lookup is skipped for the (common) genuinely-new entrant.\n const retainedTicket = hashGet(tombstones, identity, work);\n if (retainedTicket !== undefined) {\n tombstones = hashDelete(tombstones, identity, work);\n tombstoneOrder = mapDelete(tombstoneOrder, ticketKey(retainedTicket), work);\n }\n }\n values[index] = {\n ref: row.key,\n identity,\n estimatedHeight: row.estimatedHeight,\n height: measuredHeight ?? estimatedHeight,\n measured: measuredHeight !== undefined,\n denseKey: row.denseKey,\n };\n work.refilterEntriesInserted += 1;\n }\n // Whatever the walk left unconsumed has LEFT the visible set. The Map\n // preserves old-sequence order, so measured leavers take new tickets in\n // exactly the order the cooperative scan-visible phase would assign them.\n for (const value of unconsumed.values()) {\n unchanged = false;\n work.refilterEntriesRetired += 1;\n if (!value.measured)\n continue;\n if (this.#maxRetainedMeasurements === 0) {\n measurements = hashDelete(measurements, value.identity, work);\n continue;\n }\n const ticket = nextTicket;\n nextTicket = takeNextTicket(nextTicket);\n tombstones = hashSet(tombstones, value.identity, ticket, work);\n tombstoneOrder = mapSet(tombstoneOrder, ticketKey(ticket), value.identity, work);\n }\n while (hashCount(tombstones) > this.#maxRetainedMeasurements) {\n const oldest = minimumMapEntry(tombstoneOrder);\n if (oldest === undefined) {\n throw new Error(\"Removed-measurement retention is inconsistent.\");\n }\n tombstoneOrder = mapDelete(tombstoneOrder, oldest.key, work);\n tombstones = hashDelete(tombstones, oldest.value, work);\n measurements = hashDelete(measurements, oldest.value, work);\n }\n if (unchanged)\n return this;\n const root = buildBalancedSequence(values, 0, rowCount, work);\n return this.#next(root, visibleKeys, this.#denseCapacity, this.#visibleSlots, measurements, tombstones, tombstoneOrder, nextTicket, work);\n }\n /**\n * Dense-lane refilter (Amendment I): survivors resolve by `denseKey`\n * (model slot) against a slot-indexed array — ZERO identity strings for\n * the (dominant) survivor population. Only ENTRANTS compute an identity,\n * because measurements and tombstones stay string-identity-keyed in both\n * lanes: a slot is lifetime-bound and reused after permanent removal, so\n * slot reuse must never touch retention (the amendment's §3 trap). Key\n * validation mirrors the builder's `#ingestDenseKey` cases (missing /\n * malformed / out-of-range → lifecycle error → the controller's\n * fallback-on-throw contract), and the duplicate check shares one bitset\n * with the next generation's membership, exactly as the builder does.\n *\n * TRUST BOUNDARY: a survivor's `row.key` is trusted to match the slot's\n * stored identity and deliberately never re-verified — that verification\n * IS the per-row string cost this lane exists to delete. `apply` guards\n * slot drift instead, because its operations are k-sized.\n *\n * LEAVER ORDER IS LOAD-BEARING: measured leavers take tombstone tickets\n * in OLD-SEQUENCE order (the string lane inherits this from its Map's\n * insertion order), and ticket order is observable through cap eviction.\n * The leaver pass therefore walks `previousValues` in order and consumes\n * the slot cells — NEVER the slot array by index, whose order is\n * unrelated to the sequence.\n */\n #refilterDense(boundEntryAt, rowCount) {\n const capacity = this.#denseCapacity;\n const work = createWork();\n // One in-order pass over the current sequence: the by-slot lookup table\n // for the walk below, and the old order for no-op detection and the\n // leaver pass.\n const previousValues = [];\n const unconsumedBySlot = new Array(capacity);\n {\n const stack = [];\n let cursor = this.#root;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n previousValues.push(node.value);\n unconsumedBySlot[node.value.denseKey] = node.value;\n work.previousEntriesScanned += 1;\n cursor = node.right;\n }\n }\n // Walk the new order: survivors relink verbatim by slot (measurements\n // and estimates ride, exactly as in `reorder`), entrants ingest fresh\n // under the cooperative path's rule — measured-lookup against the FULL\n // cache BY IDENTITY, so a returning tombstoned key gets its retained\n // measurement back and sheds its tombstone. `nextVisibleSlots` doubles\n // as the duplicate check and the next generation's membership.\n const values = new Array(rowCount);\n const nextVisibleSlots = createDenseMembership(capacity);\n let measurements = this.#measurements;\n let tombstones = this.#tombstones;\n let tombstoneOrder = this.#tombstoneOrder;\n let nextTicket = this.#nextTicket;\n let unchanged = rowCount === previousValues.length;\n for (let index = 0; index < rowCount; index += 1) {\n const row = boundEntryAt(index);\n work.entriesVisited += 1;\n const denseKey = row.denseKey;\n if (denseKey === undefined) {\n throw new RowHeightReplacementLifecycleError(\"failed\", \"A dense row-height index requires a denseKey on every source \" +\n `row (${this.#identity(row.key)} carries none); fall back to ` +\n \"a full replacement.\");\n }\n if (!Number.isSafeInteger(denseKey) ||\n denseKey < 0 ||\n denseKey >= capacity) {\n throw new RowHeightReplacementLifecycleError(\"failed\", `Dense key ${denseKey} for row ${this.#identity(row.key)} is ` +\n `outside the dense generation's capacity ${capacity}.`);\n }\n if (testDenseBit(nextVisibleSlots, denseKey)) {\n throw new Error(`Duplicate dense row-height slot ${denseKey}: ` +\n this.#identity(row.key));\n }\n setDenseBit(nextVisibleSlots, denseKey);\n const existing = unconsumedBySlot[denseKey];\n if (existing !== undefined) {\n unconsumedBySlot[denseKey] = undefined;\n values[index] = existing;\n work.refilterEntriesReused += 1;\n if (existing !== previousValues[index])\n unchanged = false;\n continue;\n }\n unchanged = false;\n const identity = this.#identity(row.key);\n work.identityLookups += 1;\n const estimatedHeight = this.#estimated(row.estimatedHeight);\n const measuredHeight = hashGet(measurements, identity, work);\n if (measuredHeight !== undefined) {\n work.measurementEntriesScanned += 1;\n // A tombstone can only exist where a retained measurement does, so\n // the lookup is skipped for the (common) genuinely-new entrant.\n const retainedTicket = hashGet(tombstones, identity, work);\n if (retainedTicket !== undefined) {\n tombstones = hashDelete(tombstones, identity, work);\n tombstoneOrder = mapDelete(tombstoneOrder, ticketKey(retainedTicket), work);\n }\n }\n values[index] = {\n ref: row.key,\n identity,\n estimatedHeight: row.estimatedHeight,\n height: measuredHeight ?? estimatedHeight,\n measured: measuredHeight !== undefined,\n denseKey,\n };\n work.refilterEntriesInserted += 1;\n }\n // Whatever the walk left unconsumed has LEFT the visible set. Iterate\n // the OLD SEQUENCE (see the doc comment above — ticket order is\n // observable via cap eviction) and consume each leaver's slot cell.\n for (const value of previousValues) {\n const slot = value.denseKey;\n if (unconsumedBySlot[slot] === undefined)\n continue;\n unconsumedBySlot[slot] = undefined;\n unchanged = false;\n work.refilterEntriesRetired += 1;\n if (!value.measured)\n continue;\n if (this.#maxRetainedMeasurements === 0) {\n measurements = hashDelete(measurements, value.identity, work);\n continue;\n }\n const ticket = nextTicket;\n nextTicket = takeNextTicket(nextTicket);\n tombstones = hashSet(tombstones, value.identity, ticket, work);\n tombstoneOrder = mapSet(tombstoneOrder, ticketKey(ticket), value.identity, work);\n }\n while (hashCount(tombstones) > this.#maxRetainedMeasurements) {\n const oldest = minimumMapEntry(tombstoneOrder);\n if (oldest === undefined) {\n throw new Error(\"Removed-measurement retention is inconsistent.\");\n }\n tombstoneOrder = mapDelete(tombstoneOrder, oldest.key, work);\n tombstones = hashDelete(tombstones, oldest.value, work);\n measurements = hashDelete(measurements, oldest.value, work);\n }\n if (unchanged)\n return this;\n const root = buildBalancedSequence(values, 0, rowCount, work);\n return this.#next(root, null, this.#denseCapacity, nextVisibleSlots, measurements, tombstones, tombstoneOrder, nextTicket, work);\n }\n beginReplacement(source) {\n const rowCount = source.rowCount;\n if (!Number.isSafeInteger(rowCount) || rowCount < 0) {\n throw new RangeError(\"Replacement source rowCount must be a non-negative safe integer.\");\n }\n const entryAt = source.entryAt;\n if (typeof entryAt !== \"function\") {\n throw new TypeError(\"Replacement source entryAt must be a function.\");\n }\n const denseCapacity = source.denseCapacity;\n if (denseCapacity !== undefined &&\n (!Number.isSafeInteger(denseCapacity) || denseCapacity < 0)) {\n throw new RangeError(\"Replacement source denseCapacity must be a non-negative safe integer.\");\n }\n return new PersistentRowHeightReplacementBuilder({\n denseCapacity,\n // With no retained state every ingest lookup would miss (see\n // `hasRetainedState`'s derivation), so the builder may build everything\n // in one synchronous O(n) pass instead of cooperative phases.\n bulk: !this.hasRetainedState,\n base: {\n index: this,\n defaultHeight: this.#defaultHeight,\n getKey: this.#getKey,\n root: this.#root,\n visibleKeys: this.#visibleKeys,\n denseCapacity: this.#denseCapacity,\n measurements: this.#measurements,\n tombstones: this.#tombstones,\n tombstoneOrder: this.#tombstoneOrder,\n nextTicket: this.#nextTicket,\n maxRetainedMeasurements: this.#maxRetainedMeasurements,\n },\n rowCount,\n entryAt: entryAt.bind(source),\n });\n }\n captureAnchor(index, scrollTop) {\n if (!Number.isSafeInteger(index))\n return undefined;\n const value = sequenceAt(this.#root, index);\n if (value === undefined)\n return undefined;\n if (!Number.isFinite(scrollTop)) {\n throw new RangeError(\"Anchor scrollTop must be finite.\");\n }\n return Object.freeze({\n ref: value.ref,\n offset: scrollTop - this.getOffsetForIndex(index),\n });\n }\n restoreAnchor(anchor, index) {\n assertExistingIndex(index, this.rowCount, \"Anchor row index\");\n if (!Number.isFinite(anchor.offset)) {\n throw new RangeError(\"Anchor offset must be finite.\");\n }\n const value = sequenceAt(this.#root, index);\n if (value.identity !== this.#identity(anchor.ref)) {\n throw new Error(\"The anchor key does not match the row at the new index.\");\n }\n return this.getOffsetForIndex(index) + anchor.offset;\n }\n #identity(ref) {\n return encodeStableKey(this.#getKey(ref));\n }\n #estimated(height) {\n return height === undefined\n ? this.#defaultHeight\n : normalizeHeight(height, \"Estimated row height\");\n }\n #assertIdentity(current, identity) {\n if (current.identity !== identity) {\n throw new Error(\"The row-height operation key does not match the row at its index.\");\n }\n }\n #next(root, visibleKeys, denseCapacity, visibleSlots, measurements, tombstones, tombstoneOrder, nextTicket, work) {\n return new _a({\n defaultHeight: this.#defaultHeight,\n getKey: this.#getKey,\n root,\n visibleKeys,\n denseCapacity,\n visibleSlots,\n measurements,\n tombstones,\n tombstoneOrder,\n nextTicket,\n maxRetainedMeasurements: this.#maxRetainedMeasurements,\n work,\n });\n }\n}\n_a = PersistentRowHeightIndex;\nclass PersistentRowHeightReplacementBuilder {\n #status = \"pending\";\n #phase = \"ingest\";\n #base;\n #entryAt;\n #sourceRowCount;\n #values = [];\n /** Ingested identity → its position in `#values`. Doubles as the duplicate\n * check the ingest has always run and as the survivor lookup the scan\n * phases use to let a surviving row's height RIDE\n * (see `#rideSurvivorHeight`). */\n #identities = new Map();\n #retainedMeasurements = [];\n #retainedTraversal = [];\n #visibleTraversal = [];\n #sequenceBuildStack = [];\n #retentionBuildStack = [];\n #visibleKeys = null;\n /** Dense lane (Amendment I §1): declared by the source at `begin`. */\n #denseCapacity;\n #visibleSlots;\n #measurements;\n #tombstones = null;\n #tombstoneOrder = null;\n #root = null;\n #nextTicket;\n #ingestIndex = 0;\n #retainedStart = 0;\n #evictionIndex = 0;\n #tombstoneBuildIndex = 0;\n #completedUnits = 0;\n #lastSliceUnits = 0;\n #sliceCount = 0;\n #maxSliceUnits = 0;\n #maxSliceDuration = 0;\n #noOp = false;\n #equalVisible = true;\n #phaseUnits = {\n ingest: 0,\n \"scan-retained\": 0,\n \"scan-visible\": 0,\n evict: 0,\n \"build-tombstones\": 0,\n \"build-sequence\": 0,\n \"build-retention-order\": 0,\n done: 0,\n };\n #totalUnits;\n #bulk;\n #work = createWork();\n constructor(options) {\n this.#base = options.base;\n this.#entryAt = options.entryAt;\n this.#sourceRowCount = options.rowCount;\n this.#denseCapacity = options.denseCapacity;\n this.#visibleSlots =\n options.denseCapacity === undefined\n ? null\n : createDenseMembership(options.denseCapacity);\n this.#measurements = options.base.measurements;\n this.#nextTicket = options.base.nextTicket;\n this.#bulk = options.bulk;\n // The bulk pass is one unit of work by construction; the cooperative\n // estimate below deliberately over-counts so progress never regresses.\n this.#totalUnits = options.bulk\n ? 1\n : Math.min(Number.MAX_SAFE_INTEGER, options.rowCount * 4 +\n nodeCount(options.base.root) * 8 +\n hashCount(options.base.tombstones) * 8 +\n 8);\n }\n get done() {\n return this.#status === \"done\" || this.#status === \"finished\";\n }\n get progress() {\n return Object.freeze({\n phase: this.#phase,\n completedUnits: this.#completedUnits,\n totalUnits: Math.max(this.#totalUnits, this.#completedUnits),\n unitsThisSlice: this.#lastSliceUnits,\n sourceRowsIngested: this.#ingestIndex,\n previousRowsScanned: this.#work.previousEntriesScanned,\n done: this.done,\n });\n }\n get diagnostics() {\n const candidateRoots = [\n this.#root,\n this.#visibleKeys,\n this.#measurements,\n this.#tombstones,\n this.#tombstoneOrder,\n ].filter((root) => root !== null).length;\n return Object.freeze({\n status: this.#status,\n phase: this.#phase,\n retainedBaseRootCount: this.#base === null ? 0 : 1,\n retainedSourceCount: this.#entryAt === null ? 0 : 1,\n candidateArrayEntryCount: (this.#values?.length ?? 0) + (this.#retainedMeasurements?.length ?? 0),\n candidateStackEntryCount: (this.#retainedTraversal?.length ?? 0) +\n (this.#visibleTraversal?.length ?? 0) +\n (this.#sequenceBuildStack?.length ?? 0) +\n (this.#retentionBuildStack?.length ?? 0),\n candidateRootCount: candidateRoots,\n identitySetEntryCount: this.#identities?.size ?? 0,\n maxSliceUnits: this.#maxSliceUnits,\n maxSliceDuration: this.#maxSliceDuration,\n sliceCount: this.#sliceCount,\n completedUnits: this.#completedUnits,\n totalUnits: Math.max(this.#totalUnits, this.#completedUnits),\n phaseUnits: Object.freeze({ ...this.#phaseUnits }),\n nodesCreated: this.#work.nodesCreated,\n identityLookups: this.#work.identityLookups,\n identityComparisons: this.#work.identityComparisons,\n });\n }\n advance(options) {\n this.#assertPending();\n if (!Number.isSafeInteger(options.maxUnits) || options.maxUnits <= 0) {\n throw new RangeError(\"Replacement maxUnits must be a positive safe integer.\");\n }\n if (options.now !== undefined && typeof options.now !== \"function\") {\n throw new TypeError(\"Replacement now must be a function.\");\n }\n if (options.deadline !== undefined) {\n if (!Number.isFinite(options.deadline)) {\n throw new RangeError(\"Replacement deadline must be finite.\");\n }\n if (options.now === undefined) {\n throw new TypeError(\"Replacement now is required when deadline is supplied.\");\n }\n }\n const maxUnits = Math.min(256, Math.floor(options.maxUnits));\n let units = 0;\n let startedAt;\n let observedAt;\n try {\n if (options.now !== undefined) {\n startedAt = options.now();\n if (!Number.isFinite(startedAt)) {\n throw new RangeError(\"Replacement clock must return a finite number.\");\n }\n observedAt = startedAt;\n }\n if (this.#bulk && this.#status === \"pending\") {\n // Synchronous BY DESIGN (spec C2a): with no retained state the\n // cooperative phases degenerate — every measured-height lookup misses,\n // scan-retained walks nothing, and eviction/tombstone/retention builds\n // are all empty — so the entire replacement is one O(n) pass:\n // duplicate-checked ingest + `buildBalancedSequence`. Measured\n // ~15-20ms at 50k rows (B3's balanced build) versus ~450ms of sliced\n // cooperative re-ingest during which a mounting grid paints nothing.\n // `maxUnits`/`deadline` are deliberately not consulted: the pass is a\n // single unit, and slicing it would recreate the blank mount.\n this.#stepBulk();\n this.#phaseUnits.ingest += 1;\n units = 1;\n this.#completedUnits += 1;\n if (options.now !== undefined) {\n observedAt = options.now();\n if (!Number.isFinite(observedAt)) {\n throw new RangeError(\"Replacement clock must return a finite number.\");\n }\n }\n }\n while (units < maxUnits && this.#status === \"pending\") {\n const phase = this.#phase;\n this.#step();\n this.#phaseUnits[phase] += 1;\n units += 1;\n this.#completedUnits += 1;\n if (options.now !== undefined) {\n observedAt = options.now();\n if (!Number.isFinite(observedAt)) {\n throw new RangeError(\"Replacement clock must return a finite number.\");\n }\n if (options.deadline !== undefined &&\n observedAt >= options.deadline) {\n break;\n }\n }\n }\n }\n catch (error) {\n this.#status = \"failed\";\n this.#release();\n throw error;\n }\n this.#lastSliceUnits = units;\n this.#sliceCount += 1;\n this.#maxSliceUnits = Math.max(this.#maxSliceUnits, units);\n if (startedAt !== undefined && observedAt !== undefined) {\n this.#maxSliceDuration = Math.max(this.#maxSliceDuration, Math.max(0, observedAt - startedAt));\n }\n return this.progress;\n }\n finish() {\n if (this.#status !== \"done\") {\n if (this.#status === \"pending\") {\n throw new RowHeightReplacementLifecycleError(\"not-ready\", \"Replacement is not complete.\");\n }\n throw this.#lifecycleError(this.#status);\n }\n const base = this.#base;\n const result = this.#noOp\n ? base.index\n : new PersistentRowHeightIndex({\n defaultHeight: base.defaultHeight,\n getKey: base.getKey,\n root: this.#root,\n visibleKeys: this.#visibleKeys,\n denseCapacity: this.#denseCapacity,\n visibleSlots: this.#visibleSlots ?? undefined,\n measurements: this.#measurements,\n tombstones: this.#tombstones,\n tombstoneOrder: this.#tombstoneOrder,\n nextTicket: this.#nextTicket,\n maxRetainedMeasurements: base.maxRetainedMeasurements,\n work: this.#work,\n });\n this.#status = \"finished\";\n this.#release();\n return result;\n }\n cancel() {\n if (this.#status === \"cancelled\")\n return;\n if (this.#status === \"pending\" || this.#status === \"done\") {\n this.#status = \"cancelled\";\n this.#release();\n }\n }\n #assertPending() {\n if (this.#status === \"pending\")\n return;\n throw this.#lifecycleError(this.#status);\n }\n #lifecycleError(status) {\n const code = status === \"pending\" ? \"not-ready\" : status;\n return new RowHeightReplacementLifecycleError(code, `Replacement builder is ${status}.`);\n }\n #step() {\n switch (this.#phase) {\n case \"ingest\":\n this.#stepIngest();\n return;\n case \"scan-retained\":\n this.#stepRetainedTraversal();\n return;\n case \"scan-visible\":\n this.#stepVisibleTraversal();\n return;\n case \"evict\":\n this.#stepEviction();\n return;\n case \"build-tombstones\":\n this.#stepTombstoneBuild();\n return;\n case \"build-sequence\":\n this.#stepSequenceBuild();\n return;\n case \"build-retention-order\":\n this.#stepRetentionBuild();\n return;\n case \"done\":\n throw new RowHeightReplacementLifecycleError(\"done\", \"Replacement builder is done.\");\n }\n }\n /**\n * The dense lane's per-row ingest (Amendment I §1). With no declared\n * capacity the input's `denseKey` is stamped verbatim and stays inert\n * (string lane). Under a declared capacity every row MUST carry an\n * in-range `denseKey` — the source promised dense coverage, so a missing\n * or out-of-range key is a CALLER BUG and throws rather than silently\n * falling back (the controller only declares `denseCapacity` when the\n * snapshot guarantees slots). The visible-slot bitset is built here, in\n * place of the `#visibleKeys` HAMT the dense lane skips entirely; the\n * string-identity `#identities` duplicate check still runs first at both\n * call sites, because retention stays identity-keyed in both lanes.\n */\n #ingestDenseKey(row, identity) {\n const capacity = this.#denseCapacity;\n if (capacity === undefined)\n return row.denseKey;\n const denseKey = row.denseKey;\n if (denseKey === undefined) {\n throw new RowHeightReplacementLifecycleError(\"failed\", `Replacement source declared denseCapacity ${capacity} but a row ` +\n `(${identity}) carries no denseKey; the source broke its dense ` +\n \"promise.\");\n }\n if (!Number.isSafeInteger(denseKey) ||\n denseKey < 0 ||\n denseKey >= capacity) {\n throw new RowHeightReplacementLifecycleError(\"failed\", `Dense key ${denseKey} for row ${identity} is outside the declared ` +\n `denseCapacity ${capacity}.`);\n }\n if (testDenseBit(this.#visibleSlots, denseKey)) {\n throw new Error(`Duplicate dense row-height slot ${denseKey}: ${identity}`);\n }\n setDenseBit(this.#visibleSlots, denseKey);\n return denseKey;\n }\n /**\n * The whole replacement in one pass, valid only when the base has no\n * retained state (`hasRetainedState === false`, checked by\n * `beginReplacement`). Reproduces the cooperative ingest exactly, with the\n * measured-height lookup resolved by the gate itself: `#measurements` is\n * empty, so every lookup would miss and height starts as\n * `estimatedHeight ?? defaultHeight` with `measured: false` — after which\n * the base walk below lets a SURVIVING row's height ride, exactly as the\n * cooperative scan-visible phase does. The duplicate identity check and\n * its error are the cooperative ingest's, verbatim. Semantic no-op\n * detection is preserved too: an identical visible sequence (same\n * identities and estimates, in order) finishes to the base index.\n */\n #stepBulk() {\n const base = this.#base;\n const values = this.#values;\n const identities = this.#identities;\n const entryAt = this.#entryAt;\n while (this.#ingestIndex < this.#sourceRowCount) {\n const row = entryAt(this.#ingestIndex);\n const identity = encodeStableKey(base.getKey(row.key));\n this.#work.entriesVisited += 1;\n this.#work.identityLookups += 1;\n if (identities.has(identity)) {\n throw new Error(`Duplicate stable row-height key: ${identity}`);\n }\n identities.set(identity, values.length);\n const estimatedHeight = row.estimatedHeight === undefined\n ? base.defaultHeight\n : normalizeHeight(row.estimatedHeight, \"Estimated row height\");\n const denseKey = this.#ingestDenseKey(row, identity);\n if (this.#denseCapacity === undefined) {\n this.#visibleKeys = hashSet(this.#visibleKeys, identity, true, this.#work);\n }\n values.push({\n ref: row.key,\n identity,\n estimatedHeight: row.estimatedHeight,\n height: estimatedHeight,\n measured: false,\n denseKey,\n });\n this.#ingestIndex += 1;\n }\n this.#entryAt = null;\n // One walk over the prior visible sequence, doing the cooperative path's\n // two scan-visible jobs in the bulk pass's single unit (a true mount has\n // an empty base and pays nothing here):\n //\n // 1. The no-op predicate: every prior visible entry matches its\n // candidate's identity, estimate, AND dense stamp, and the counts and\n // lanes agree. A no-op finishes to the BASE generation, so lane\n // disagreement (or a reassigned slot) must rebuild even when the\n // identities match — otherwise a stale bitset would answer for new\n // slots.\n // 2. Survivor heights RIDE (`#rideSurvivorHeight`): the bulk gate proves\n // no MEASUREMENT exists, but a never-measured base still carries the\n // estimate-laden heights its rows are drawn at, and byte-equivalence\n // with the cooperative path requires carrying them identically.\n if (base.root !== null) {\n let equal = nodeCount(base.root) === values.length &&\n this.#denseCapacity === base.denseCapacity;\n const stack = [];\n let cursor = base.root;\n let position = 0;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n this.#work.previousEntriesScanned += 1;\n if (equal) {\n const candidate = values[position];\n if (candidate.identity !== node.value.identity ||\n candidate.estimatedHeight !== node.value.estimatedHeight ||\n candidate.denseKey !== node.value.denseKey) {\n equal = false;\n }\n }\n this.#work.identityLookups += 1;\n const survivorPosition = identities.get(node.value.identity);\n if (survivorPosition !== undefined) {\n this.#rideSurvivorHeight(survivorPosition, node.value);\n }\n position += 1;\n cursor = node.right;\n }\n if (equal) {\n this.#noOp = true;\n this.#phase = \"done\";\n this.#status = \"done\";\n return;\n }\n }\n this.#root = buildBalancedSequence(values, 0, values.length, this.#work);\n this.#phase = \"done\";\n this.#status = \"done\";\n }\n #stepIngest() {\n const base = this.#base;\n const values = this.#values;\n const identities = this.#identities;\n if (this.#ingestIndex < this.#sourceRowCount) {\n const row = this.#entryAt(this.#ingestIndex);\n const identity = encodeStableKey(base.getKey(row.key));\n this.#work.entriesVisited += 1;\n this.#work.identityLookups += 1;\n if (identities.has(identity)) {\n throw new Error(`Duplicate stable row-height key: ${identity}`);\n }\n identities.set(identity, values.length);\n const estimatedHeight = row.estimatedHeight === undefined\n ? base.defaultHeight\n : normalizeHeight(row.estimatedHeight, \"Estimated row height\");\n const measuredHeight = hashGet(this.#measurements, identity, this.#work);\n if (measuredHeight !== undefined) {\n this.#work.measurementEntriesScanned += 1;\n }\n const denseKey = this.#ingestDenseKey(row, identity);\n if (this.#denseCapacity === undefined) {\n this.#visibleKeys = hashSet(this.#visibleKeys, identity, true, this.#work);\n }\n values.push({\n ref: row.key,\n identity,\n estimatedHeight: row.estimatedHeight,\n height: measuredHeight ?? estimatedHeight,\n measured: measuredHeight !== undefined,\n denseKey,\n });\n this.#ingestIndex += 1;\n return;\n }\n this.#entryAt = null;\n this.#phase = \"scan-retained\";\n if (base.tombstoneOrder !== null) {\n this.#retainedTraversal.push({\n node: base.tombstoneOrder,\n state: 0,\n });\n }\n }\n #stepRetainedTraversal() {\n const stack = this.#retainedTraversal;\n const frame = stack.at(-1);\n if (frame === undefined) {\n this.#phase = \"scan-visible\";\n const root = this.#base.root;\n if (root !== null)\n this.#visibleTraversal.push({ node: root, state: 0 });\n return;\n }\n if (frame.state === 0) {\n frame.state = 1;\n if (frame.node.left !== null) {\n stack.push({ node: frame.node.left, state: 0 });\n }\n return;\n }\n if (frame.state === 1) {\n frame.state = 2;\n this.#work.identityLookups += 1;\n if (!this.#identities.has(frame.node.value)) {\n this.#retainedMeasurements.push({\n identity: frame.node.value,\n ticket: Number(frame.node.key),\n });\n }\n return;\n }\n stack.pop();\n if (frame.node.right !== null) {\n stack.push({ node: frame.node.right, state: 0 });\n }\n }\n #stepVisibleTraversal() {\n const stack = this.#visibleTraversal;\n const frame = stack.at(-1);\n if (frame === undefined) {\n if (this.#equalVisible &&\n this.#work.previousEntriesScanned === this.#values.length &&\n this.#denseCapacity === this.#base.denseCapacity) {\n this.#noOp = true;\n this.#phase = \"done\";\n this.#status = \"done\";\n return;\n }\n this.#phase = \"evict\";\n this.#retainedStart = Math.max(0, this.#retainedMeasurements.length -\n this.#base.maxRetainedMeasurements);\n return;\n }\n if (frame.state === 0) {\n frame.state = 1;\n if (frame.node.left !== null) {\n stack.push({ node: frame.node.left, state: 0 });\n }\n return;\n }\n if (frame.state === 1) {\n frame.state = 2;\n const value = frame.node.value;\n const candidate = this.#values[this.#work.previousEntriesScanned];\n if (candidate === undefined ||\n candidate.identity !== value.identity ||\n candidate.estimatedHeight !== value.estimatedHeight ||\n candidate.denseKey !== value.denseKey) {\n this.#equalVisible = false;\n }\n this.#work.previousEntriesScanned += 1;\n this.#work.identityLookups += 1;\n const survivorPosition = this.#identities.get(value.identity);\n if (value.measured) {\n if (survivorPosition === undefined) {\n if (this.#base.maxRetainedMeasurements === 0) {\n this.#measurements = hashDelete(this.#measurements, value.identity, this.#work);\n }\n else {\n const ticket = this.#nextTicket;\n this.#nextTicket = takeNextTicket(this.#nextTicket);\n this.#retainedMeasurements.push({\n identity: value.identity,\n ticket,\n });\n }\n }\n }\n else if (survivorPosition !== undefined) {\n this.#rideSurvivorHeight(survivorPosition, value);\n }\n return;\n }\n stack.pop();\n if (frame.node.right !== null) {\n stack.push({ node: frame.node.right, state: 0 });\n }\n }\n /**\n * A SURVIVING row's height rides through the replacement (#516): the base\n * entry's height — measured or estimated — is what the row is drawn at\n * right now, and re-ingesting the same identity at the default (or at a\n * fresh estimate) moves every row top below it while the scroller's own\n * offset stays put, sliding the visible window down the dataset. The same\n * principle `reorder`/`refilter` already state for their survivors\n * (\"estimates ride\") applies to a full replacement's survivors.\n *\n * Measured candidates are skipped — the measurement lookup already gave\n * them the exact height — and so are measured base entries (their height\n * reached the candidate through `#measurements`; a candidate that missed\n * that lookup while its base entry is measured cannot occur, because\n * `measured` is set if and only if the identity is in `#measurements`).\n */\n #rideSurvivorHeight(position, value) {\n if (value.measured)\n return;\n const survivor = this.#values[position];\n if (survivor.measured || survivor.height === value.height)\n return;\n this.#values[position] = { ...survivor, height: value.height };\n }\n #stepEviction() {\n if (this.#evictionIndex < this.#retainedStart) {\n const evicted = this.#retainedMeasurements[this.#evictionIndex];\n this.#measurements = hashDelete(this.#measurements, evicted.identity, this.#work);\n this.#evictionIndex += 1;\n return;\n }\n this.#phase = \"build-tombstones\";\n this.#tombstoneBuildIndex = this.#retainedStart;\n }\n #stepTombstoneBuild() {\n const retained = this.#retainedMeasurements;\n if (this.#tombstoneBuildIndex < retained.length) {\n const value = retained[this.#tombstoneBuildIndex];\n this.#tombstones = hashSet(this.#tombstones, value.identity, value.ticket, this.#work);\n this.#tombstoneBuildIndex += 1;\n return;\n }\n this.#phase = \"build-sequence\";\n if (this.#values.length > 0) {\n this.#sequenceBuildStack.push(this.#newSequenceBuildFrame(0, this.#values.length));\n }\n }\n #stepSequenceBuild() {\n const stack = this.#sequenceBuildStack;\n const frame = stack.at(-1);\n if (frame === undefined) {\n this.#phase = \"build-retention-order\";\n if (this.#retainedStart < this.#retainedMeasurements.length) {\n this.#retentionBuildStack.push(this.#newRetentionBuildFrame(this.#retainedStart, this.#retainedMeasurements.length));\n }\n return;\n }\n if (frame.state === 0) {\n frame.state = 1;\n if (frame.start < frame.middle) {\n stack.push(this.#newSequenceBuildFrame(frame.start, frame.middle));\n }\n return;\n }\n if (frame.state === 1) {\n frame.state = 2;\n if (frame.middle + 1 < frame.end) {\n stack.push(this.#newSequenceBuildFrame(frame.middle + 1, frame.end));\n }\n return;\n }\n const node = sequenceNode(this.#values[frame.middle], frame.left, frame.right, this.#work);\n stack.pop();\n const parent = stack.at(-1);\n if (parent === undefined)\n this.#root = node;\n else if (parent.state === 1)\n parent.left = node;\n else\n parent.right = node;\n }\n #stepRetentionBuild() {\n const stack = this.#retentionBuildStack;\n const frame = stack.at(-1);\n if (frame === undefined) {\n this.#phase = \"done\";\n this.#status = \"done\";\n return;\n }\n if (frame.state === 0) {\n frame.state = 1;\n if (frame.start < frame.middle) {\n stack.push(this.#newRetentionBuildFrame(frame.start, frame.middle));\n }\n return;\n }\n if (frame.state === 1) {\n frame.state = 2;\n if (frame.middle + 1 < frame.end) {\n stack.push(this.#newRetentionBuildFrame(frame.middle + 1, frame.end));\n }\n return;\n }\n const retained = this.#retainedMeasurements[frame.middle];\n const node = mapNode(ticketKey(retained.ticket), retained.identity, frame.left, frame.right, this.#work);\n stack.pop();\n const parent = stack.at(-1);\n if (parent === undefined)\n this.#tombstoneOrder = node;\n else if (parent.state === 1)\n parent.left = node;\n else\n parent.right = node;\n }\n #newSequenceBuildFrame(start, end) {\n return {\n start,\n end,\n middle: Math.floor((start + end) / 2),\n state: 0,\n left: null,\n right: null,\n };\n }\n #newRetentionBuildFrame(start, end) {\n return {\n start,\n end,\n middle: Math.floor((start + end) / 2),\n state: 0,\n left: null,\n right: null,\n };\n }\n #release() {\n this.#base = null;\n this.#entryAt = null;\n this.#values = null;\n this.#identities = null;\n this.#retainedMeasurements = null;\n this.#retainedTraversal = null;\n this.#visibleTraversal = null;\n this.#sequenceBuildStack = null;\n this.#retentionBuildStack = null;\n this.#visibleKeys = null;\n this.#visibleSlots = null;\n this.#measurements = null;\n this.#tombstones = null;\n this.#tombstoneOrder = null;\n this.#root = null;\n }\n}\nexport function createRowHeightIndex(options) {\n const defaultHeight = normalizeHeight(options.defaultHeight, \"Default row height\");\n const maxRetainedMeasurements = options.maxRetainedMeasurements ?? DEFAULT_MAX_RETAINED_MEASUREMENTS;\n if (!Number.isSafeInteger(maxRetainedMeasurements) ||\n maxRetainedMeasurements < 0) {\n throw new RangeError(\"maxRetainedMeasurements must be a non-negative safe integer.\");\n }\n const empty = new PersistentRowHeightIndex({\n defaultHeight,\n getKey: options.getKey,\n root: null,\n visibleKeys: null,\n denseCapacity: undefined,\n visibleSlots: undefined,\n measurements: null,\n tombstones: null,\n tombstoneOrder: null,\n nextTicket: 0,\n maxRetainedMeasurements,\n work: createWork(),\n });\n return options.rows === undefined || options.rows.length === 0\n ? empty\n : empty.replace(options.rows);\n}\n/** Direct test seam; intentionally not exported from the layout-core barrel. */\nexport function getRowHeightIndexDiagnosticsForTesting(index) {\n if (!(index instanceof PersistentRowHeightIndex)) {\n throw new TypeError(\"Diagnostics require a persistent row-height index.\");\n }\n return index.diagnostics;\n}\n/** Direct test seam; intentionally not exported from the layout-core barrel. */\nexport function getRowHeightReplacementBuilderDiagnosticsForTesting(builder) {\n if (!(builder instanceof PersistentRowHeightReplacementBuilder)) {\n throw new TypeError(\"Diagnostics require a persistent row-height replacement builder.\");\n }\n return builder.diagnostics;\n}\n","function dataRef(rowId) {\n return { kind: \"data\", rowId };\n}\nclass ImmutableSet {\n #values;\n constructor(values) {\n this.#values = new Set(values);\n }\n get size() {\n return this.#values.size;\n }\n has(value) {\n return this.#values.has(value);\n }\n forEach(callbackfn, thisArg) {\n for (const value of this.#values) {\n callbackfn.call(thisArg, value, value, this);\n }\n }\n entries() {\n return this.#values.entries();\n }\n keys() {\n return this.#values.keys();\n }\n values() {\n return this.#values.values();\n }\n [Symbol.iterator]() {\n return this.#values[Symbol.iterator]();\n }\n get [Symbol.toStringTag]() {\n return \"ImmutableSet\";\n }\n}\n/** @internal Clones mutable caller input behind a read-only collection surface. */\nexport function toImmutableIndexedSet(values) {\n return Object.freeze(new ImmutableSet(values));\n}\nfunction isVisibleData(snapshot, rowId) {\n return snapshot.indexOf(dataRef(rowId)) >= 0;\n}\nexport function createEmptyIndexedSelection() {\n const rows = attachRowSelectionProgram(Object.freeze({\n kind: \"explicit\",\n rowIds: toImmutableIndexedSet(),\n }), Object.freeze({\n baseSelected: false,\n sequence: 0,\n points: null,\n layers: Object.freeze([]),\n }));\n return Object.freeze({\n rows,\n ranges: Object.freeze([]),\n anchor: null,\n });\n}\nexport function selectAllVisibleRows(selection, snapshot) {\n if (snapshot.visibleDataRowCount === 0)\n return selection;\n if (selection.rows.kind === \"all\" &&\n (selection.rows.excludedRanges?.size ?? 0) === 0 &&\n selection.ranges.length === 0 &&\n selection.anchor === null)\n return selection;\n const program = Object.freeze({\n baseSelected: true,\n sequence: 0,\n points: null,\n layers: Object.freeze([]),\n projection: Object.freeze({\n snapshot: snapshot,\n runs: singletonRun(true, snapshot.visibleDataRowCount),\n }),\n });\n const rows = attachRowSelectionProgram(Object.freeze({ kind: \"all\" }), program);\n return Object.freeze({\n ...selection,\n rows,\n ranges: Object.freeze([]),\n anchor: null,\n });\n}\nexport function toggleIndexedRowSelection(selection, rowId, snapshot) {\n if (!isVisibleData(snapshot, rowId))\n return selection;\n const program = rowSelectionProgram(selection, snapshot);\n const selected = semanticRowSelected(program, rowId);\n const sequence = program.sequence + 1;\n const projection = projectionFor(program, snapshot);\n const rank = snapshot.dataIndexOf(dataRef(rowId));\n const nextProgram = Object.freeze({\n ...program,\n sequence,\n points: setPointRule(program.points, {\n rowId,\n sequence,\n selected: !selected,\n }),\n projection: Object.freeze({\n snapshot: snapshot,\n runs: assignRunRange(projection.runs, rank, rank + 1, !selected),\n }),\n });\n if (selection.rows.kind === \"explicit\") {\n const rowIds = new Set(selection.rows.rowIds);\n const rangeIndex = currentRangeIndex(selection.rows.ranges, snapshot);\n let excludedRanges = currentExclusionIndex(selection.rows.excludedRanges, snapshot);\n const point = resolvedRowRange({ startRowId: rowId, endRowId: rowId }, snapshot);\n const selectedByRange = rangeTreeContains(rangeIndex.root, point.lo);\n if (selected) {\n rowIds.delete(rowId);\n if (selectedByRange)\n excludedRanges = insertExcludedPoint(excludedRanges, point);\n else\n excludedRanges = removeExcludedSpan(excludedRanges, point);\n }\n else {\n excludedRanges = removeExcludedSpan(excludedRanges, point);\n rowIds.add(rowId);\n }\n const rows = attachRowSelectionProgram(Object.freeze({\n kind: \"explicit\",\n rowIds: toImmutableIndexedSet(rowIds),\n ...(rangeIndex.size === 0 ? {} : { ranges: rangeIndex }),\n ...(excludedRanges.size === 0 ? {} : { excludedRanges }),\n }), nextProgram);\n return Object.freeze({\n ...selection,\n rows,\n });\n }\n let excludedRanges = currentExclusionIndex(selection.rows.excludedRanges, snapshot);\n const point = resolvedRowRange({ startRowId: rowId, endRowId: rowId }, snapshot);\n excludedRanges = rangeTreeContains(excludedRanges.root, point.lo)\n ? removeExcludedSpan(excludedRanges, point)\n : insertExcludedPoint(excludedRanges, point);\n const rows = attachRowSelectionProgram(Object.freeze({\n kind: \"all\",\n ...(excludedRanges.size === 0 ? {} : { excludedRanges }),\n }), nextProgram);\n return Object.freeze({\n ...selection,\n rows,\n });\n}\nfunction nodeHeight(node) {\n return node?.height ?? 0;\n}\nfunction makeRangeNode(range, left = null, right = null) {\n return Object.freeze({\n ...range,\n left,\n right,\n height: Math.max(nodeHeight(left), nodeHeight(right)) + 1,\n maxHi: Math.max(range.hi, left?.maxHi ?? -1, right?.maxHi ?? -1),\n selectedCount: range.hi -\n range.lo +\n 1 +\n (left?.selectedCount ?? 0) +\n (right?.selectedCount ?? 0),\n size: 1 + (left?.size ?? 0) + (right?.size ?? 0),\n });\n}\nfunction balanceRangeNode(node) {\n const balance = nodeHeight(node.left) - nodeHeight(node.right);\n if (balance > 1 && node.left !== null) {\n let left = node.left;\n if (nodeHeight(left.left) < nodeHeight(left.right) && left.right !== null) {\n const pivot = left.right;\n left = makeRangeNode(pivot, makeRangeNode(left, left.left, pivot.left), pivot.right);\n }\n return makeRangeNode(left, left.left, makeRangeNode(node, left.right, node.right));\n }\n if (balance < -1 && node.right !== null) {\n let right = node.right;\n if (nodeHeight(right.right) < nodeHeight(right.left) &&\n right.left !== null) {\n const pivot = right.left;\n right = makeRangeNode(pivot, pivot.left, makeRangeNode(right, pivot.right, right.right));\n }\n return makeRangeNode(right, makeRangeNode(node, node.left, right.left), right.right);\n }\n return node;\n}\nfunction insertRangeNode(root, range) {\n if (root === null)\n return makeRangeNode(range);\n return range.lo < root.lo\n ? balanceRangeNode(makeRangeNode(root, insertRangeNode(root.left, range), root.right))\n : balanceRangeNode(makeRangeNode(root, root.left, insertRangeNode(root.right, range)));\n}\nfunction minimumRangeNode(root) {\n let current = root;\n while (current.left !== null)\n current = current.left;\n return current;\n}\nfunction removeRangeNode(root, lo) {\n if (root === null)\n return null;\n if (lo < root.lo)\n return balanceRangeNode(makeRangeNode(root, removeRangeNode(root.left, lo), root.right));\n if (lo > root.lo)\n return balanceRangeNode(makeRangeNode(root, root.left, removeRangeNode(root.right, lo)));\n if (root.left === null)\n return root.right;\n if (root.right === null)\n return root.left;\n const successor = minimumRangeNode(root.right);\n return balanceRangeNode(makeRangeNode(successor, root.left, removeRangeNode(root.right, successor.lo)));\n}\nfunction splitRangeTree(root, lo) {\n if (root === null)\n return [null, null];\n if (root.lo < lo) {\n const [leftOfSplit, rightOfSplit] = splitRangeTree(root.right, lo);\n return [\n balanceRangeNode(makeRangeNode(root, root.left, leftOfSplit)),\n rightOfSplit,\n ];\n }\n const [leftOfSplit, rightOfSplit] = splitRangeTree(root.left, lo);\n return [\n leftOfSplit,\n balanceRangeNode(makeRangeNode(root, rightOfSplit, root.right)),\n ];\n}\nfunction concatenateRangeTrees(left, right) {\n if (left === null)\n return right;\n if (right === null)\n return left;\n if (nodeHeight(left) > nodeHeight(right) + 1)\n return balanceRangeNode(makeRangeNode(left, left.left, concatenateRangeTrees(left.right, right)));\n if (nodeHeight(right) > nodeHeight(left) + 1)\n return balanceRangeNode(makeRangeNode(right, concatenateRangeTrees(left, right.left), right.right));\n const successor = minimumRangeNode(right);\n return balanceRangeNode(makeRangeNode(successor, left, removeRangeNode(right, successor.lo)));\n}\nfunction findOverlappingRange(root, lo, hi) {\n if (root === null)\n return undefined;\n if (root.left !== null && root.left.maxHi >= lo - 1) {\n const left = findOverlappingRange(root.left, lo, hi);\n if (left !== undefined)\n return left;\n }\n if (root.lo <= hi + 1 && root.hi >= lo - 1)\n return root;\n return root.lo > hi + 1\n ? undefined\n : findOverlappingRange(root.right, lo, hi);\n}\nfunction findIntersectingRange(root, lo, hi) {\n if (root === null)\n return undefined;\n if (root.left !== null && root.left.maxHi >= lo) {\n const left = findIntersectingRange(root.left, lo, hi);\n if (left !== undefined)\n return left;\n }\n if (root.lo <= hi && root.hi >= lo)\n return root;\n return root.lo > hi ? undefined : findIntersectingRange(root.right, lo, hi);\n}\nfunction rangeTreeContains(root, rank) {\n let current = root;\n while (current !== null) {\n if (rank < current.lo)\n current = current.left;\n else if (rank > current.hi)\n current = current.right;\n else\n return true;\n }\n return false;\n}\nclass IndexedRowRangeIndex {\n revision;\n root;\n size;\n constructor(revision, root) {\n this.revision = revision;\n this.root = root;\n this.size = root?.size ?? 0;\n Object.freeze(this);\n }\n *[Symbol.iterator]() {\n const stack = [];\n let current = this.root;\n while (current !== null || stack.length > 0) {\n while (current !== null) {\n stack.push(current);\n current = current.left;\n }\n const next = stack.pop();\n yield Object.freeze({ startRowId: next.loId, endRowId: next.hiId });\n current = next.right;\n }\n }\n}\nfunction compareRowIds(left, right) {\n if (sameRowId(left, right))\n return 0;\n if (typeof left !== typeof right)\n return typeof left === \"number\" ? -1 : 1;\n if (typeof left === \"number\" && typeof right === \"number\") {\n if (Number.isNaN(left))\n return 1;\n if (Number.isNaN(right))\n return -1;\n return left < right ? -1 : 1;\n }\n return left < right ? -1 : 1;\n}\nfunction pointHeight(node) {\n return node?.height ?? 0;\n}\nfunction makePointNode(rule, left = null, right = null) {\n return Object.freeze({\n ...rule,\n left,\n right,\n height: Math.max(pointHeight(left), pointHeight(right)) + 1,\n });\n}\nfunction balancePointNode(node) {\n const balance = pointHeight(node.left) - pointHeight(node.right);\n if (balance > 1 && node.left !== null) {\n let left = node.left;\n if (pointHeight(left.left) < pointHeight(left.right) &&\n left.right !== null) {\n const pivot = left.right;\n left = makePointNode(pivot, makePointNode(left, left.left, pivot.left), pivot.right);\n }\n return makePointNode(left, left.left, makePointNode(node, left.right, node.right));\n }\n if (balance < -1 && node.right !== null) {\n let right = node.right;\n if (pointHeight(right.right) < pointHeight(right.left) &&\n right.left !== null) {\n const pivot = right.left;\n right = makePointNode(pivot, pivot.left, makePointNode(right, pivot.right, right.right));\n }\n return makePointNode(right, makePointNode(node, node.left, right.left), right.right);\n }\n return node;\n}\nfunction setPointRule(root, rule) {\n if (root === null)\n return makePointNode(rule);\n const comparison = compareRowIds(rule.rowId, root.rowId);\n if (comparison === 0)\n return makePointNode(rule, root.left, root.right);\n return comparison < 0\n ? balancePointNode(makePointNode(root, setPointRule(root.left, rule), root.right))\n : balancePointNode(makePointNode(root, root.left, setPointRule(root.right, rule)));\n}\nfunction getPointRule(root, rowId) {\n let current = root;\n while (current !== null) {\n const comparison = compareRowIds(rowId, current.rowId);\n if (comparison === 0)\n return current;\n current = comparison < 0 ? current.left : current.right;\n }\n return undefined;\n}\nfunction ruleHeight(node) {\n return node?.height ?? 0;\n}\nfunction makeRuleNode(rule, left = null, right = null) {\n return Object.freeze({\n lo: rule.lo,\n hi: rule.hi,\n sequence: rule.sequence,\n left,\n right,\n height: Math.max(ruleHeight(left), ruleHeight(right)) + 1,\n maxHi: Math.max(rule.hi, left?.maxHi ?? -1, right?.maxHi ?? -1),\n maxSequence: Math.max(rule.sequence, left?.maxSequence ?? -1, right?.maxSequence ?? -1),\n });\n}\nfunction balanceRuleNode(node) {\n const balance = ruleHeight(node.left) - ruleHeight(node.right);\n if (balance > 1 && node.left !== null) {\n let left = node.left;\n if (ruleHeight(left.left) < ruleHeight(left.right) && left.right !== null) {\n const pivot = left.right;\n left = makeRuleNode(pivot, makeRuleNode(left, left.left, pivot.left), pivot.right);\n }\n return makeRuleNode(left, left.left, makeRuleNode(node, left.right, node.right));\n }\n if (balance < -1 && node.right !== null) {\n let right = node.right;\n if (ruleHeight(right.right) < ruleHeight(right.left) &&\n right.left !== null) {\n const pivot = right.left;\n right = makeRuleNode(pivot, pivot.left, makeRuleNode(right, pivot.right, right.right));\n }\n return makeRuleNode(right, makeRuleNode(node, node.left, right.left), right.right);\n }\n return node;\n}\nfunction insertRuleNode(root, rule) {\n if (root === null)\n return makeRuleNode(rule);\n return rule.lo < root.lo\n ? balanceRuleNode(makeRuleNode(root, insertRuleNode(root.left, rule), root.right))\n : balanceRuleNode(makeRuleNode(root, root.left, insertRuleNode(root.right, rule)));\n}\nfunction findIntersectingRule(root, lo, hi) {\n if (root === null)\n return undefined;\n if (root.left !== null && root.left.maxHi >= lo) {\n const left = findIntersectingRule(root.left, lo, hi);\n if (left !== undefined)\n return left;\n }\n if (root.lo <= hi && root.hi >= lo)\n return root;\n return root.lo > hi ? undefined : findIntersectingRule(root.right, lo, hi);\n}\nfunction minimumRuleNode(root) {\n let current = root;\n while (current.left !== null)\n current = current.left;\n return current;\n}\nfunction removeRuleNode(root, lo) {\n if (root === null)\n return null;\n if (lo < root.lo)\n return balanceRuleNode(makeRuleNode(root, removeRuleNode(root.left, lo), root.right));\n if (lo > root.lo)\n return balanceRuleNode(makeRuleNode(root, root.left, removeRuleNode(root.right, lo)));\n if (root.left === null)\n return root.right;\n if (root.right === null)\n return root.left;\n const successor = minimumRuleNode(root.right);\n return balanceRuleNode(makeRuleNode(successor, root.left, removeRuleNode(root.right, successor.lo)));\n}\nfunction concatenateRuleTrees(left, right) {\n if (left === null)\n return right;\n if (right === null)\n return left;\n if (ruleHeight(left) > ruleHeight(right) + 1)\n return balanceRuleNode(makeRuleNode(left, left.left, concatenateRuleTrees(left.right, right)));\n if (ruleHeight(right) > ruleHeight(left) + 1)\n return balanceRuleNode(makeRuleNode(right, concatenateRuleTrees(left, right.left), right.right));\n const successor = minimumRuleNode(right);\n return balanceRuleNode(makeRuleNode(successor, left, removeRuleNode(right, successor.lo)));\n}\nfunction splitRuleTree(root, rank) {\n if (root === null)\n return [null, null];\n if (rank <= root.lo) {\n const [left, right] = splitRuleTree(root.left, rank);\n return [\n left,\n concatenateRuleTrees(right, makeRuleNode(root, null, root.right)),\n ];\n }\n if (rank > root.hi) {\n const [left, right] = splitRuleTree(root.right, rank);\n return [\n concatenateRuleTrees(makeRuleNode(root, root.left, null), left),\n right,\n ];\n }\n return [\n concatenateRuleTrees(root.left, makeRuleNode({ lo: root.lo, hi: rank - 1, sequence: root.sequence })),\n concatenateRuleTrees(makeRuleNode({ lo: rank, hi: root.hi, sequence: root.sequence }), root.right),\n ];\n}\nfunction assignRuleRange(root, lo, hi, sequence) {\n if (findIntersectingRule(root, lo, hi) === undefined)\n return insertRuleNode(root, { lo, hi, sequence });\n const [left, fromLo] = splitRuleTree(root, lo);\n const [, right] = splitRuleTree(fromLo, hi + 1);\n return concatenateRuleTrees(left, concatenateRuleTrees(makeRuleNode({ lo, hi, sequence }), right));\n}\nfunction newestRuleAt(root, rank, best = -1) {\n if (root === null || root.maxHi < rank || root.maxSequence <= best)\n return best;\n let next = best;\n if (root.left !== null)\n next = newestRuleAt(root.left, rank, next);\n if (root.lo <= rank && rank <= root.hi && root.sequence > next)\n next = root.sequence;\n if (root.lo <= rank && root.right !== null)\n next = newestRuleAt(root.right, rank, next);\n return next;\n}\nfunction runHeight(node) {\n return node?.height ?? 0;\n}\nfunction makeRunNode(selected, length, left = null, right = null) {\n return Object.freeze({\n selected,\n length,\n left,\n right,\n height: Math.max(runHeight(left), runHeight(right)) + 1,\n totalLength: length + (left?.totalLength ?? 0) + (right?.totalLength ?? 0),\n selectedCount: (selected ? length : 0) +\n (left?.selectedCount ?? 0) +\n (right?.selectedCount ?? 0),\n });\n}\nfunction singletonRun(selected, length) {\n return length === 0 ? null : makeRunNode(selected, length);\n}\nfunction joinRunTrees(left, middle, right) {\n if (runHeight(left) > runHeight(right) + 1 && left !== null) {\n return makeRunNode(left.selected, left.length, left.left, joinRunTrees(left.right, middle, right));\n }\n if (runHeight(right) > runHeight(left) + 1 && right !== null) {\n return makeRunNode(right.selected, right.length, joinRunTrees(left, middle, right.left), right.right);\n }\n return makeRunNode(middle.selected, middle.length, left, right);\n}\nfunction extractMinimumRun(root) {\n if (root.left === null)\n return [root, root.right];\n const [minimum, left] = extractMinimumRun(root.left);\n return [minimum, makeRunNode(root.selected, root.length, left, root.right)];\n}\nfunction concatRunTreesRaw(left, right) {\n if (left === null)\n return right;\n if (right === null)\n return left;\n const [minimum, remaining] = extractMinimumRun(right);\n return joinRunTrees(left, minimum, remaining);\n}\nfunction splitRunTree(root, index) {\n if (root === null)\n return [null, null];\n const leftLength = root.left?.totalLength ?? 0;\n if (index < leftLength) {\n const [left, right] = splitRunTree(root.left, index);\n return [\n left,\n joinRunTrees(right, makeRunNode(root.selected, root.length), root.right),\n ];\n }\n if (index > leftLength + root.length) {\n const [left, right] = splitRunTree(root.right, index - leftLength - root.length);\n return [\n joinRunTrees(root.left, makeRunNode(root.selected, root.length), left),\n right,\n ];\n }\n const ownOffset = index - leftLength;\n const leftOwn = singletonRun(root.selected, ownOffset);\n const rightOwn = singletonRun(root.selected, root.length - ownOffset);\n return [\n concatRunTreesRaw(root.left, leftOwn),\n concatRunTreesRaw(rightOwn, root.right),\n ];\n}\nfunction assignRunRange(root, start, end, selected) {\n const [left, rest] = splitRunTree(root, start);\n const [, right] = splitRunTree(rest, Math.max(0, end - start));\n return concatRunTreesRaw(concatRunTreesRaw(left, singletonRun(selected, Math.max(0, end - start))), right);\n}\nfunction removeRunAt(root, index) {\n const [left, rest] = splitRunTree(root, index);\n const [, right] = splitRunTree(rest, 1);\n return concatRunTreesRaw(left, right);\n}\nfunction insertRunAt(root, index, selected) {\n const [left, right] = splitRunTree(root, index);\n return concatRunTreesRaw(concatRunTreesRaw(left, singletonRun(selected, 1)), right);\n}\nconst rowSelectionPrograms = new WeakMap();\nfunction attachRowSelectionProgram(rows, program) {\n rowSelectionPrograms.set(rows, program);\n return rows;\n}\nfunction semanticRowSelected(program, rowId) {\n let sequence = 0;\n let selected = program.baseSelected;\n const point = getPointRule(program.points, rowId);\n if (point !== undefined) {\n sequence = point.sequence;\n selected = point.selected;\n }\n for (const layer of program.layers) {\n const rank = layer.snapshot.dataIndexOf(dataRef(rowId));\n if (rank < 0)\n continue;\n const rangeSequence = newestRuleAt(layer.rules, rank, sequence);\n if (rangeSequence > sequence) {\n sequence = rangeSequence;\n selected = true;\n }\n }\n return selected;\n}\nfunction buildProjection(program, snapshot) {\n // This is the explicit reset path: arbitrary replacement/permutation has no\n // sublinear intersection answer in the public snapshot contract. Stream the\n // target once into compressed runs; never allocate the selected ID set.\n if (program.sequence === 0) {\n return Object.freeze({\n snapshot,\n runs: singletonRun(program.baseSelected, snapshot.visibleDataRowCount),\n });\n }\n let runs = null;\n let currentValue;\n let currentLength = 0;\n const flush = () => {\n if (currentValue !== undefined && currentLength > 0)\n runs = concatRunTreesRaw(runs, singletonRun(currentValue, currentLength));\n };\n for (let index = 0; index < snapshot.visibleDataRowCount; index += 1) {\n const row = snapshot.dataRowAt(index);\n if (row === undefined)\n continue;\n const selected = semanticRowSelected(program, row.rowId);\n if (selected === currentValue)\n currentLength += 1;\n else {\n flush();\n currentValue = selected;\n currentLength = 1;\n }\n }\n flush();\n return Object.freeze({ snapshot, runs });\n}\nfunction projectionFor(program, snapshot) {\n return program.projection?.snapshot === snapshot\n ? program.projection\n : buildProjection(program, snapshot);\n}\nfunction addSemanticRange(program, snapshot, lo, hi, sequence) {\n const layerIndex = program.layers.findIndex((layer) => layer.snapshot === snapshot);\n const layers = Array.from(program.layers);\n if (layerIndex < 0) {\n layers.push(Object.freeze({\n snapshot,\n rules: assignRuleRange(null, lo, hi, sequence),\n }));\n }\n else {\n const layer = layers[layerIndex];\n layers[layerIndex] = Object.freeze({\n snapshot,\n rules: assignRuleRange(layer.rules, lo, hi, sequence),\n });\n }\n return Object.freeze({\n ...program,\n sequence,\n layers: Object.freeze(layers),\n });\n}\nfunction rowSelectionProgram(selection, snapshot) {\n const existing = rowSelectionPrograms.get(selection.rows);\n if (existing !== undefined)\n return existing;\n let program = Object.freeze({\n baseSelected: selection.rows.kind === \"all\",\n sequence: 0,\n points: null,\n layers: Object.freeze([]),\n });\n if (selection.rows.kind === \"explicit\") {\n for (const rowId of selection.rows.rowIds) {\n const sequence = program.sequence + 1;\n program = Object.freeze({\n ...program,\n sequence,\n points: setPointRule(program.points, {\n rowId,\n sequence,\n selected: true,\n }),\n });\n }\n for (const range of selection.rows.ranges ?? []) {\n const resolved = resolvedRowRange(range, snapshot);\n if (resolved === undefined)\n continue;\n program = addSemanticRange(program, snapshot, resolved.lo, resolved.hi, program.sequence + 1);\n }\n }\n for (const range of selection.rows.excludedRanges ?? []) {\n for (const rowId of [range.startRowId, range.endRowId]) {\n const sequence = program.sequence + 1;\n program = Object.freeze({\n ...program,\n sequence,\n points: setPointRule(program.points, {\n rowId,\n sequence,\n selected: false,\n }),\n });\n }\n }\n rowSelectionPrograms.set(selection.rows, program);\n return program;\n}\nfunction cloneRowsWithProgram(rows, program) {\n const clone = rows.kind === \"explicit\"\n ? Object.freeze({\n kind: \"explicit\",\n rowIds: rows.rowIds,\n ...(rows.ranges === undefined ? {} : { ranges: rows.ranges }),\n ...(rows.excludedRanges === undefined\n ? {}\n : { excludedRanges: rows.excludedRanges }),\n })\n : Object.freeze({\n kind: \"all\",\n ...(rows.excludedRanges === undefined\n ? {}\n : { excludedRanges: rows.excludedRanges }),\n });\n return attachRowSelectionProgram(clone, program);\n}\n/** @internal Preserves the semantic row-selection program across defensive copies. */\nexport function preserveIndexedRowSelectionProgram(source, target) {\n const program = rowSelectionPrograms.get(source);\n if (program !== undefined)\n rowSelectionPrograms.set(target, program);\n}\n/** @internal Releases snapshot bases retained only by a disposed grid state. */\nexport function releaseIndexedRowSelectionProgram(rows) {\n rowSelectionPrograms.delete(rows);\n}\n/** @internal Distinguishes identical public projections with different semantic histories. */\nexport function sameIndexedRowSelectionProgram(left, right) {\n const leftProgram = rowSelectionPrograms.get(left);\n const rightProgram = rowSelectionPrograms.get(right);\n if (leftProgram === rightProgram)\n return true;\n const canonical = (rows, program) => {\n if (program === undefined)\n return true;\n const kind = rows.kind;\n return (program.sequence === 0 &&\n program.points === null &&\n program.layers.length === 0 &&\n program.baseSelected === (kind === \"all\"));\n };\n return canonical(left, leftProgram) && canonical(right, rightProgram);\n}\nfunction countPointRules(root) {\n return root === null\n ? 0\n : 1 + countPointRules(root.left) + countPointRules(root.right);\n}\nfunction countRangeRules(root) {\n return root === null\n ? 0\n : 1 + countRangeRules(root.left) + countRangeRules(root.right);\n}\nfunction countRuns(root) {\n return root === null ? 0 : 1 + countRuns(root.left) + countRuns(root.right);\n}\n/** @internal Retention diagnostics for semantic-selection regression tests. */\nexport function getIndexedRowSelectionProgramDiagnostics(rows) {\n const program = rowSelectionPrograms.get(rows);\n return Object.freeze({\n pointRuleCount: countPointRules(program?.points ?? null),\n rangeRuleCount: (program?.layers ?? []).reduce((count, layer) => count + countRangeRules(layer.rules), 0),\n snapshotBasisCount: program?.layers.length ?? 0,\n projectionRunCount: countRuns(program?.projection?.runs ?? null),\n });\n}\nconst exclusionIndexes = new WeakSet();\nfunction makeExclusionIndex(revision, root) {\n const index = new IndexedRowRangeIndex(revision, root);\n exclusionIndexes.add(index);\n return index;\n}\nfunction resolvedRowRange(range, snapshot) {\n const startRank = snapshot.dataIndexOf(dataRef(range.startRowId));\n const endRank = snapshot.dataIndexOf(dataRef(range.endRowId));\n if (startRank < 0 || endRank < 0)\n return undefined;\n return startRank <= endRank\n ? {\n lo: startRank,\n hi: endRank,\n loId: range.startRowId,\n hiId: range.endRowId,\n }\n : {\n lo: endRank,\n hi: startRank,\n loId: range.endRowId,\n hiId: range.startRowId,\n };\n}\nfunction insertResolvedRange(index, next) {\n let root = index.root;\n let merged = next;\n for (;;) {\n const overlap = findOverlappingRange(root, merged.lo, merged.hi);\n if (overlap === undefined)\n break;\n root = removeRangeNode(root, overlap.lo);\n merged = {\n lo: Math.min(merged.lo, overlap.lo),\n hi: Math.max(merged.hi, overlap.hi),\n loId: overlap.lo < merged.lo ? overlap.loId : merged.loId,\n hiId: overlap.hi > merged.hi ? overlap.hiId : merged.hiId,\n };\n }\n return new IndexedRowRangeIndex(index.revision, insertRangeNode(root, merged));\n}\nfunction createRangeIndex(ranges, snapshot) {\n let index = new IndexedRowRangeIndex(snapshot.revision, null);\n for (const range of ranges ?? []) {\n const resolved = resolvedRowRange(range, snapshot);\n if (resolved !== undefined)\n index = insertResolvedRange(index, resolved);\n }\n return index;\n}\nfunction currentRangeIndex(ranges, snapshot) {\n return ranges instanceof IndexedRowRangeIndex &&\n !exclusionIndexes.has(ranges) &&\n ranges.revision === snapshot.revision\n ? ranges\n : createRangeIndex(ranges, snapshot);\n}\nfunction createExclusionIndex(ranges, snapshot) {\n let index = makeExclusionIndex(snapshot.revision, null);\n for (const range of ranges ?? []) {\n for (const rowId of [range.startRowId, range.endRowId]) {\n const point = resolvedRowRange({ startRowId: rowId, endRowId: rowId }, snapshot);\n if (point !== undefined && !rangeTreeContains(index.root, point.lo))\n index = makeExclusionIndex(snapshot.revision, insertRangeNode(index.root, point));\n }\n }\n return index;\n}\nfunction currentExclusionIndex(ranges, snapshot) {\n return ranges instanceof IndexedRowRangeIndex &&\n exclusionIndexes.has(ranges) &&\n ranges.revision === snapshot.revision\n ? ranges\n : createExclusionIndex(ranges, snapshot);\n}\nfunction insertExcludedPoint(index, point) {\n if (rangeTreeContains(index.root, point.lo))\n return index;\n return makeExclusionIndex(index.revision, insertRangeNode(index.root, point));\n}\nfunction removeExcludedSpan(index, removed) {\n if (findIntersectingRange(index.root, removed.lo, removed.hi) === undefined)\n return index;\n const [left, fromLo] = splitRangeTree(index.root, removed.lo);\n const [, right] = splitRangeTree(fromLo, removed.hi + 1);\n return makeExclusionIndex(index.revision, concatenateRangeTrees(left, right));\n}\nexport function selectIndexedRowRange(selection, startRowId, endRowId, snapshot) {\n const nextRange = { startRowId, endRowId };\n const resolvedNext = resolvedRowRange(nextRange, snapshot);\n if (resolvedNext === undefined)\n return selection;\n const program = rowSelectionProgram(selection, snapshot);\n const sequence = program.sequence + 1;\n const projection = projectionFor(program, snapshot);\n const nextProgram = Object.freeze({\n ...addSemanticRange(program, snapshot, resolvedNext.lo, resolvedNext.hi, sequence),\n projection: Object.freeze({\n snapshot: snapshot,\n runs: assignRunRange(projection.runs, resolvedNext.lo, resolvedNext.hi + 1, true),\n }),\n });\n if (selection.rows.kind === \"all\") {\n const excludedRanges = removeExcludedSpan(currentExclusionIndex(selection.rows.excludedRanges, snapshot), resolvedNext);\n const rows = attachRowSelectionProgram(Object.freeze({\n kind: \"all\",\n ...(excludedRanges.size === 0 ? {} : { excludedRanges }),\n }), nextProgram);\n return Object.freeze({\n ...selection,\n rows,\n });\n }\n const ranges = insertResolvedRange(currentRangeIndex(selection.rows.ranges, snapshot), resolvedNext);\n const excludedRanges = removeExcludedSpan(currentExclusionIndex(selection.rows.excludedRanges, snapshot), resolvedNext);\n const rows = attachRowSelectionProgram(Object.freeze({\n kind: \"explicit\",\n rowIds: selection.rows.rowIds,\n ranges,\n ...(excludedRanges.size === 0 ? {} : { excludedRanges }),\n }), nextProgram);\n return Object.freeze({\n ...selection,\n rows,\n });\n}\nexport function isIndexedRowSelected(selection, ref, snapshot) {\n if (ref.kind !== \"data\" || snapshot.indexOf(ref) < 0)\n return false;\n return semanticRowSelected(rowSelectionProgram(selection, snapshot), ref.rowId);\n}\n/**\n * Build the engine's row-checkbox slice from the shape a consumer can write.\n *\n * Deliberately assembled out of the same primitives a USER's gestures go\n * through — `selectAllVisibleRows`, `toggleIndexedRowSelection`,\n * `selectIndexedRowRange` — rather than by hand-rolling a second constructor\n * for the semantic program. A hand-rolled one would be a second definition of\n * what a selection means, free to drift from the gesture path it is supposed to\n * be interchangeable with, and it would have to reproduce the incremental\n * projection maintenance that keeps each of these sublinear.\n *\n * Cost is therefore O(k log n) in the SIZE OF THE REQUEST, never in the row\n * count: `{ kind: \"all\" }` alone runs one `selectAllVisibleRows`, which records\n * \"everything\" as a single run and visits no rows at all.\n *\n * Ids the current snapshot does not show are dropped, because that is what\n * ticking them by hand would do — the same rule `state.focus` and the cell\n * ranges already follow.\n */\nexport function createIndexedRowSelection(requested, snapshot) {\n let selection = createEmptyIndexedSelection();\n if (requested.kind === \"all\") {\n selection = selectAllVisibleRows(selection, snapshot);\n }\n else {\n // A Set because `toggleIndexedRowSelection` toggles: a repeated id would\n // tick the row and then untick it again.\n for (const rowId of new Set(requested.rowIds)) {\n selection = toggleIndexedRowSelection(selection, rowId, snapshot);\n }\n for (const range of requested.ranges ?? []) {\n selection = selectIndexedRowRange(selection, range.startRowId, range.endRowId, snapshot);\n }\n }\n for (const rowId of new Set(requested.excludedRowIds)) {\n // Only rows the request actually selected can be excluded from it. Without\n // this guard the toggle would SELECT an unselected id, turning \"everything\n // except row 7\" into \"everything, plus row 7\" the moment row 7 was not\n // covered in the first place.\n if (!isIndexedRowSelected(selection, dataRef(rowId), snapshot))\n continue;\n selection = toggleIndexedRowSelection(selection, rowId, snapshot);\n }\n return selection.rows;\n}\n/**\n * Render the engine's row-checkbox slice as the shape a consumer can write\n * back — the inverse of {@link createIndexedRowSelection}.\n *\n * Sparse in, sparse out. A symbolic \"all\" stays two words, and a shift-checked\n * 100k-row span stays its two endpoint ids; nothing here walks a population.\n *\n * @public\n */\nexport function describeRowSelection(rows) {\n // Exclusions are stored as degenerate ranges — `insertExcludedPoint` is the\n // only thing that ever adds one — so reading both endpoints costs nothing and\n // survives any future widening rather than silently halving it.\n const excluded = new Set();\n for (const range of rows.excludedRanges ?? []) {\n excluded.add(range.startRowId);\n excluded.add(range.endRowId);\n }\n const excludedRowIds = excluded.size === 0 ? {} : { excludedRowIds: Object.freeze([...excluded]) };\n if (rows.kind === \"all\") {\n return Object.freeze({ kind: \"all\", ...excludedRowIds });\n }\n const ranges = [...(rows.ranges ?? [])].map((range) => Object.freeze({ startRowId: range.startRowId, endRowId: range.endRowId }));\n return Object.freeze({\n kind: \"explicit\",\n rowIds: Object.freeze([...rows.rowIds]),\n ...(ranges.length === 0 ? {} : { ranges: Object.freeze(ranges) }),\n ...excludedRowIds,\n });\n}\n/**\n * @internal Structural equality for the row-checkbox slice, ignoring the\n * semantic program attached to it.\n *\n * `sameSelection` cannot answer this question: it short-circuits on\n * `sameIndexedRowSelectionProgram`, which compares HISTORIES and so calls two\n * independently-built selections different even when they tick the same rows.\n * That is the right answer for a gesture (an \"all\"-derived selection and an\n * identical explicit one behave differently as rows arrive) and the wrong one\n * for an idempotence check, where the question is only whether applying this\n * value would change anything a reader can see.\n */\nexport function sameIndexedRowSelectionValue(left, right) {\n if (left === right)\n return true;\n if (left.kind !== right.kind)\n return false;\n if (!sameRowRangeIndex(left.excludedRanges, right.excludedRanges))\n return false;\n if (left.kind !== \"explicit\" || right.kind !== \"explicit\")\n return true;\n if (left.rowIds.size !== right.rowIds.size)\n return false;\n for (const rowId of left.rowIds) {\n if (!right.rowIds.has(rowId))\n return false;\n }\n return sameRowRangeIndex(left.ranges, right.ranges);\n}\nfunction sameRowRangeIndex(left, right) {\n if (left === right)\n return true;\n if ((left?.size ?? 0) !== (right?.size ?? 0))\n return false;\n const leftRanges = [...(left ?? [])];\n const rightRanges = [...(right ?? [])];\n return leftRanges.every((range, index) => {\n const other = rightRanges[index];\n return (other !== undefined &&\n sameRowId(range.startRowId, other.startRowId) &&\n sameRowId(range.endRowId, other.endRowId));\n });\n}\nexport function getIndexedSelectionSummary(selection, snapshot) {\n const visibleCount = snapshot.visibleDataRowCount;\n const selectedCount = projectionFor(rowSelectionProgram(selection, snapshot), snapshot).runs?.selectedCount ?? 0;\n return Object.freeze({\n state: selectedCount === 0\n ? \"none\"\n : selectedCount === visibleCount\n ? \"all\"\n : \"some\",\n selectedCount,\n visibleCount,\n });\n}\nfunction columnIndex(columns, columnId) {\n for (let index = 0; index < columns.length; index += 1) {\n if (columns[index] === columnId)\n return index;\n }\n return -1;\n}\n/**\n * `rowId`'s absolute DATASET position, or `-1` when the row is not loaded.\n *\n * With `loadedWindow` null this is the plain data-only rank every\n * pre-eviction caller already compared against, so a local-mode grid keeps\n * arithmetic that is byte-for-byte what it was. With a window it is the rank\n * shifted into dataset coordinates, which is the only space in which a span\n * still means something once its rows are gone.\n *\n * Data-only rank, not `indexOf`: group headers occupy visible indices but no\n * dataset position, and the window is a dataset span. The two orderings agree\n * on data rows — both are monotonic in visible order — so containment answers\n * identically for the cells this function is ever asked about.\n */\nfunction datasetPosition(snapshot, rowId, loadedWindow) {\n const rank = snapshot.dataIndexOf(dataRef(rowId));\n if (rank < 0)\n return -1;\n return (loadedWindow?.start ?? 0) + rank;\n}\n/**\n * Whether `span`'s remembered positions may be read against `window`.\n *\n * FAIL-CLOSED, and deliberately so. Matching keys mean the same population,\n * so the positions still name the same rows. A different key means a re-sort\n * or a filter change has re-filled those positions with other rows entirely.\n * And an ABSENT key on either side is not a match — it is the absence of any\n * evidence about the population, which is the same situation as a mismatch\n * and must be refused for the same reason.\n *\n * Treating \"no key on both sides\" as agreement fails OPEN, and the failure is\n * not a downgraded number, it is wrong paint: a windowed consumer who simply\n * never heard of `datasetKey` (it is optional, and nothing in the type says it\n * is load-bearing) re-sorts, one endpoint survives at a new position, and\n * `indexedRangeContainsCell` — which returns a bare boolean and has no\n * `verified` channel to downgrade through — reports `true` for rows the user\n * never selected. Measured: selection `row-10..row-40` under window\n * `[0, 100)`, re-sorted to `[30, 130)`, painted a row that had never been in\n * the selection.\n *\n * The cost of closing it is that a windowed consumer publishing no\n * `datasetKey` loses span survival across eviction and degrades to\n * loaded-rows-only — visibly, in the `verified` flag and the count, rather\n * than invisibly, in the wrong cells. `warnMissingDatasetKey` tells them.\n *\n * Local mode is untouched: with no window there is no span to read in the\n * first place (see `endpointPositions`).\n *\n * ## The population is a second question, and the key does not answer it\n *\n * `datasetKey` identifies the QUERY. `lifecycle.mdx` tells consumers to keep\n * it stable while they page within one result, so an insert or a delete made\n * upstream of an evicted selection leaves the key matching while re-filling\n * the remembered positions with entirely different rows. Measured:\n * `row-1..row-8` selected and evicted, five rows prepended to the same\n * result, and the returning window painted four rows that did not exist when\n * the user selected — while the eight they did select painted nothing.\n *\n * So the size of the population is compared too, and it fails closed the same\n * way. `provenDeletions` is the one allowance: rows this very call has\n * PROVEN gone are a population change the engine observed, so a total short\n * by exactly that many is fully accounted for rather than unexplained. Only\n * {@link narrowDeletedEndpoints} passes a non-zero value; every reader that\n * merely wants to trust a remembered position uses the strict form.\n */\nfunction spanReadableInWindow(span, window, provenDeletions = 0) {\n return (window.datasetKey !== undefined &&\n span.datasetKey === window.datasetKey &&\n span.datasetTotal !== undefined &&\n window.datasetTotal === span.datasetTotal - provenDeletions);\n}\n/**\n * Whether `window` can carry dataset spans at all. A window with no\n * `datasetKey` cannot: anything stamped under it could never be read back\n * (see {@link spanReadableInWindow}), so stamping one would only emit a\n * number through `onSelectionChange` that the engine itself refuses.\n */\nfunction windowCarriesSpans(window) {\n return window !== null && window.datasetKey !== undefined;\n}\n/**\n * Where `range`'s endpoints sit in the dataset, per endpoint, preferring what\n * the snapshot can confirm right now over what the range remembers.\n *\n * `undefined` for an endpoint means neither source could answer.\n */\nfunction endpointPositions(range, snapshot, loadedWindow) {\n const liveStart = datasetPosition(snapshot, range.start.rowId, loadedWindow);\n const liveEnd = datasetPosition(snapshot, range.end.rowId, loadedWindow);\n const bothLive = liveStart >= 0 && liveEnd >= 0;\n if (bothLive)\n return { start: liveStart, end: liveEnd, bothLive };\n // Pre-eviction callers never carry a span and never supply a window. With\n // no window there is no dataset coordinate system to remember positions in,\n // so a half-resolved range answers nothing at all — byte-for-byte what it\n // did before eviction existed.\n if (loadedWindow === null)\n return { start: undefined, end: undefined, bothLive };\n const remembered = range.datasetRowSpan !== undefined &&\n spanReadableInWindow(range.datasetRowSpan, loadedWindow)\n ? range.datasetRowSpan\n : undefined;\n return {\n start: liveStart >= 0 ? liveStart : remembered?.start,\n end: liveEnd >= 0 ? liveEnd : remembered?.end,\n bothLive,\n };\n}\n/**\n * The dataset positions `range` covers, ordered.\n *\n * The remembered half is the whole point of eviction: an endpoint that is\n * merely evicted still has a dataset position recorded on the range, and\n * `hi - lo + 1` over it is answerable with zero rows loaded. It is flagged\n * unverified because a row deleted server-side WHILE evicted leaves no trace\n * anywhere the engine can read.\n *\n * A range with ONE endpoint resolvable resolves to the union of what it does\n * know — the live survivor plus the absentee's remembered position, or just\n * the survivor when nothing is remembered. This is the sliding-window case:\n * an ordinary incremental scroll retires one endpoint many revisions before\n * the other, and treating that as \"unanswerable\" would under-report every\n * scrolled selection by the whole span but one row.\n *\n * `undefined` — neither endpoint resolvable and nothing usable remembered —\n * is genuinely unanswerable, which is different from zero.\n */\nfunction rangeDatasetSpan(range, snapshot, loadedWindow) {\n const { start, end, bothLive } = endpointPositions(range, snapshot, loadedWindow);\n const low = start ?? end;\n const high = end ?? start;\n if (low === undefined || high === undefined)\n return undefined;\n return {\n lo: Math.min(low, high),\n hi: Math.max(low, high),\n // Both endpoints present is not on its own enough to call the extent\n // proven. Under a window that CAN carry spans, a range without one has no\n // positional identity: reconciliation stripped it, which it only does\n // when it could not locate the range in the current population. The rows\n // it still names really are selected — so it paints — but the extent it\n // reports is a remnant, not what the user chose, and saying otherwise is\n // the same \"silent under-count wearing a verified flag\" this whole\n // design exists to remove.\n verified: bothLive &&\n (!windowCarriesSpans(loadedWindow) || range.datasetRowSpan !== undefined),\n };\n}\n/**\n * Data rows covered by the CELL-RANGE slice (`selection.ranges`), by\n * arithmetic over spans rather than by visiting rows — so a 4,901-row\n * selection with 30 rows loaded still counts 4,901.\n *\n * Not to be confused with {@link getIndexedSelectionSummary}, which counts\n * the separate sparse row-selection program the checkbox column drives.\n *\n * `loadedWindow` is the same honesty-gated span `reconcileIndexedSelection`\n * takes; omitting it (local mode) restricts the count to what the snapshot\n * can resolve, exactly as before eviction existed.\n *\n * @internal Re-exported by `@pretable/core` as\n * `ɵgetIndexedCellSelectionSummary`.\n */\nexport function getIndexedCellSelectionSummary(selection, snapshot, loadedWindow) {\n const window = loadedWindow ?? null;\n const spans = [];\n let verified = true;\n for (const range of selection.ranges) {\n const span = rangeDatasetSpan(range, snapshot, window);\n if (span === undefined) {\n // Selects at least one row, at a position nothing can supply. Adding a\n // guess would be the lie; contributing nothing and saying the total is\n // unverified is the most this can honestly do.\n verified = false;\n continue;\n }\n if (!span.verified)\n verified = false;\n spans.push(span);\n }\n // Union, so two ranges over the same rows report those rows once. Sorting a\n // handful of spans is still O(ranges) in the sense that matters: nothing\n // here scales with how many rows are selected.\n spans.sort((left, right) => left.lo - right.lo);\n let rowCount = 0;\n let covered = null;\n for (const span of spans) {\n const lo = covered === null || span.lo > covered ? span.lo : covered + 1;\n if (span.hi >= lo)\n rowCount += span.hi - lo + 1;\n if (covered === null || span.hi > covered)\n covered = span.hi;\n }\n return Object.freeze({ rowCount, verified });\n}\n/**\n * Whether a cell range covers `ref` / `columnId`, resolved against the drawn\n * column order.\n *\n * @internal Re-exported by `@pretable/core` as `ɵindexedRangeContainsCell`.\n */\nexport function indexedRangeContainsCell(range, ref, columnId, snapshot, columns, \n/**\n * The loaded span, when the honesty gate is passing. Supplying it is what\n * lets a rendered row in the MIDDLE of a range paint while the range's own\n * endpoints are evicted — the case that previously painted nothing at all,\n * because resolving both endpoints was a precondition.\n */\nloadedWindow) {\n if (ref.kind !== \"data\")\n return false;\n const currentColumnIndex = columnIndex(columns, columnId);\n const startColumnIndex = columnIndex(columns, range.start.columnId);\n const endColumnIndex = columnIndex(columns, range.end.columnId);\n if (currentColumnIndex < 0 ||\n startColumnIndex < 0 ||\n endColumnIndex < 0 ||\n currentColumnIndex < Math.min(startColumnIndex, endColumnIndex) ||\n currentColumnIndex > Math.max(startColumnIndex, endColumnIndex)) {\n return false;\n }\n const window = loadedWindow ?? null;\n const rowPosition = datasetPosition(snapshot, ref.rowId, window);\n if (rowPosition < 0)\n return false;\n const span = rangeDatasetSpan(range, snapshot, window);\n if (span === undefined)\n return false;\n return rowPosition >= span.lo && rowPosition <= span.hi;\n}\nfunction visibleAddress(address, snapshot) {\n return isVisibleData(snapshot, address.rowId);\n}\nfunction sameRowId(left, right) {\n return left === right || (left !== left && right !== right);\n}\n/** @internal Projects the visible rank cache from exact row-model deltas. */\nexport function projectIndexedSelection(selection, previousSnapshot, snapshot, sequence) {\n const program = rowSelectionProgram(selection, previousSnapshot);\n let projection;\n if (sequence.kind === \"reset\" ||\n sequence.fromRevision !== previousSnapshot.revision ||\n sequence.toRevision !== snapshot.revision) {\n projection = buildProjection(program, snapshot);\n }\n else {\n // Routine revisions touch only structural data refs. Removing their old\n // ranks then inserting their final ranks preserves every untouched run and\n // makes work proportional to the journal delta, not ranges or exclusions.\n let runs = projectionFor(program, previousSnapshot).runs;\n const touched = new Map();\n for (const change of sequence.changes) {\n for (const operation of change.operations) {\n if (operation.ref.kind === \"data\" && operation.kind !== \"update\")\n touched.set(operation.ref.rowId, true);\n }\n }\n const removals = [];\n const insertions = [];\n for (const rowId of touched.keys()) {\n const previousRank = previousSnapshot.dataIndexOf(dataRef(rowId));\n if (previousRank >= 0)\n removals.push({ rank: previousRank, rowId });\n const rank = snapshot.dataIndexOf(dataRef(rowId));\n if (rank >= 0)\n insertions.push({ rank, rowId });\n }\n removals.sort((left, right) => right.rank - left.rank);\n for (const removal of removals)\n runs = removeRunAt(runs, removal.rank);\n insertions.sort((left, right) => left.rank - right.rank);\n for (const insertion of insertions)\n runs = insertRunAt(runs, insertion.rank, semanticRowSelected(program, insertion.rowId));\n if ((runs?.totalLength ?? 0) !== snapshot.visibleDataRowCount) {\n projection = buildProjection(program, snapshot);\n }\n else {\n projection = Object.freeze({\n snapshot: snapshot,\n runs,\n });\n }\n }\n const nextProgram = Object.freeze({ ...program, projection });\n const rows = cloneRowsWithProgram(selection.rows, nextProgram);\n return Object.freeze({ ...selection, rows });\n}\n/**\n * Whether `rowId`'s disappearance from `snapshot` is provably a deletion\n * rather than an eviction. Proof requires knowing where the row sat in\n * dataset terms the last time it *was* loaded — `previous.snapshot`'s\n * data-only rank, converted to an absolute position via `previous.window`,\n * the window that was active for that snapshot. Falling inside\n * `loadedWindow` (the window active NOW) means the current window covers\n * where the row used to be, yet the row is gone — nothing but deletion\n * explains that. Falling outside — or the position simply being unknown,\n * because `previous` was not supplied or never resolved the row — is NOT\n * proof of deletion, so the row is presumed evicted: it may simply be\n * sitting in the unloaded remainder the window admits exists.\n *\n * @internal Exported for `reconcileIndexedFocus`, which must reach the same\n * verdict about a row as the selection does — never re-implemented there.\n */\nexport function provenDeletedRow(rowId, loadedWindow, previous) {\n if (previous === undefined || previous.window == null)\n return false;\n const previousRank = previous.snapshot.dataIndexOf(dataRef(rowId));\n if (previousRank < 0)\n return false;\n const previousAbsolute = previous.window.start + previousRank;\n return (previousAbsolute >= loadedWindow.start &&\n previousAbsolute < loadedWindow.start + loadedWindow.length);\n}\n/**\n * The row that now holds dataset position `position`, addressed in `column`.\n *\n * `undefined` when the position is outside the loaded window, which is the\n * only honest answer: naming a row is naming an identity, and the engine\n * cannot name one it has not loaded.\n */\nfunction addressAtDatasetPosition(snapshot, position, column, loadedWindow) {\n const rank = position - loadedWindow.start;\n if (rank < 0 || rank >= loadedWindow.length)\n return undefined;\n const row = snapshot.dataRowAt(rank);\n if (row === undefined)\n return undefined;\n return Object.freeze({ rowId: row.rowId, columnId: column });\n}\n/**\n * Narrows `range` by the endpoints that are PROVEN deleted, instead of\n * discarding it.\n *\n * The spec states the eviction rule per ROW: an absent row inside the loaded\n * span is deleted and prunes, one outside it is evicted and survives. Applied\n * per RANGE — drop the whole range if either endpoint is proven deleted — one\n * genuinely removed row took every merely-evicted row between the endpoints\n * with it, which is the silent under-selection this design exists to remove.\n *\n * The arithmetic is one rule for every shape. A deletion removes a row from\n * the dataset, so everything after it shifts down one; whether the deleted\n * endpoint is the low one or the high one, the surviving rows end up at\n * `lo … hi - 1`:\n *\n * | Deleted endpoint | Survivors, old positions | …after the shift |\n * | ---------------- | ------------------------ | ---------------- |\n * | the LOW end | `lo + 1 … hi` | `lo … hi - 1` |\n * | the HIGH end | `lo … hi - 1` | `lo … hi - 1` |\n *\n * So the HIGH field loses one position per proven deletion and the low field\n * does not move — and a surviving endpoint that is loaded reports its live\n * position instead, which already carries the shift and also absorbs any\n * deletion the engine could not prove.\n *\n * Returns `undefined` — meaning \"drop the range\", the pre-narrowing answer —\n * when there is no readable span to narrow, when nothing is left of the span,\n * or when the narrowed boundary lands on a row that is not loaded and so\n * cannot be named. Fail-closed in every case: the range is discarded rather\n * than left holding a position it cannot justify.\n */\nfunction narrowDeletedEndpoints(range, snapshot, loadedWindow, deleted) {\n const span = range.datasetRowSpan;\n const count = (deleted.start ? 1 : 0) + (deleted.end ? 1 : 0);\n // No positional identity, so there is nothing to narrow BY. A windowed grid\n // that publishes no `datasetKey` lands here on every range, deliberately:\n // its spans are refused everywhere else too (see `spanReadableInWindow`).\n //\n // `count` is passed as the proven-deletion allowance: a deletion IS a\n // population change, so the strict read would refuse every span the moment\n // it had something to narrow. Requiring the total to be short by exactly\n // the rows this call proved gone keeps the check meaningful — a revision\n // that also inserted, or that deleted a third row elsewhere, does not add\n // up and is refused, which drops the range rather than moving it to a\n // position the engine cannot justify.\n if (span === undefined || !spanReadableInWindow(span, loadedWindow, count))\n return undefined;\n const startIsHigh = span.start >= span.end;\n let nextStart = startIsHigh ? span.start - count : span.start;\n let nextEnd = startIsHigh ? span.end : span.end - count;\n if (!deleted.start) {\n const live = datasetPosition(snapshot, range.start.rowId, loadedWindow);\n if (live >= 0)\n nextStart = live;\n }\n if (!deleted.end) {\n const live = datasetPosition(snapshot, range.end.rowId, loadedWindow);\n if (live >= 0)\n nextEnd = live;\n }\n // Empty: the deletions consumed the whole span. `nextStart`/`nextEnd` can\n // cross only when `count` exceeded the span's width, which is exactly that.\n if (startIsHigh ? nextStart < nextEnd : nextEnd < nextStart)\n return undefined;\n const start = deleted.start\n ? addressAtDatasetPosition(snapshot, nextStart, range.start.columnId, loadedWindow)\n : range.start;\n const end = deleted.end\n ? addressAtDatasetPosition(snapshot, nextEnd, range.end.columnId, loadedWindow)\n : range.end;\n if (start === undefined || end === undefined)\n return undefined;\n return Object.freeze({\n start,\n end,\n datasetRowSpan: Object.freeze({\n start: nextStart,\n end: nextEnd,\n datasetKey: span.datasetKey,\n // The CURRENT total, not the span's. These positions have just been\n // rewritten to describe the post-deletion population, so stamping the\n // pre-deletion size would leave the range permanently unreadable the\n // instant after it was successfully narrowed.\n datasetTotal: loadedWindow.datasetTotal,\n }),\n });\n}\nfunction sameSpan(left, right) {\n if (left === right)\n return true;\n if (left === undefined || right === undefined)\n return false;\n // Plain value equality, NOT `spanReadableInWindow`: this asks whether two\n // spans say the same thing, not whether either may be trusted.\n return (left.start === right.start &&\n left.end === right.end &&\n left.datasetKey === right.datasetKey &&\n left.datasetTotal === right.datasetTotal);\n}\nfunction withoutDatasetRowSpan(range) {\n if (range.datasetRowSpan === undefined)\n return range;\n return Object.freeze({ start: range.start, end: range.end });\n}\n/**\n * Records where `range`'s endpoints sit in the dataset, so the span outlives\n * the rows.\n *\n * Positions come from the snapshot where it can answer and from the range's\n * own memory where it cannot, which is what lets a gesture extending from an\n * already-EVICTED anchor still produce a countable range. A stamp is written\n * only when BOTH endpoints resolve that way: a half-known range keeps\n * whatever it had, so a moment of partial knowledge cannot overwrite a\n * complete span with a narrower one.\n *\n * Returns `range` itself when there is nothing to record — no window, or a\n * span identical to the one already on it — so reconciliation stays a no-op\n * in local mode and does not republish the selection on every revision.\n *\n * A window with no `datasetKey` records nothing and clears whatever was\n * there: such a span could never be read back (see\n * {@link spanReadableInWindow}), so keeping one would put a number the engine\n * itself refuses in front of a consumer, who might well persist it.\n */\nfunction stampDatasetRowSpan(range, snapshot, loadedWindow) {\n // No window: nothing to record, and nothing to correct. A span already on\n // the range is left alone rather than dropped — it is inert here (with no\n // window, `endpointPositions` never reads a remembered position), and the\n // window is routinely absent for a moment BEFORE the first revision is\n // observed. Dropping it there would destroy a selection restored through\n // the controlled `state` prop on the very render that restores it.\n if (loadedWindow === null)\n return range;\n if (!windowCarriesSpans(loadedWindow))\n return withoutDatasetRowSpan(range);\n const { start, end } = endpointPositions(range, snapshot, loadedWindow);\n if (start === undefined || end === undefined) {\n return range.datasetRowSpan === undefined ||\n spanReadableInWindow(range.datasetRowSpan, loadedWindow)\n ? range\n : withoutDatasetRowSpan(range);\n }\n const next = Object.freeze({\n start,\n end,\n datasetKey: loadedWindow.datasetKey,\n datasetTotal: loadedWindow.datasetTotal,\n });\n if (sameSpan(range.datasetRowSpan, next))\n return range;\n return Object.freeze({ ...range, datasetRowSpan: next });\n}\n/**\n * Fills in `datasetRowSpan` for ranges a GESTURE just built.\n *\n * Every selection gesture — shift-click, keyboard extension, marquee,\n * select-all, an echo through the controlled `state` prop — hands the engine\n * brand-new range objects carrying nothing but row ids. Left alone those\n * ranges are born spanless, so the count collapses to whatever happens to be\n * loaded the moment the window next moves. Stamping them here, on the single\n * public write path, is what makes the span the range's identity rather than\n * a memo reconciliation occasionally attaches.\n *\n * `replaced` is the selection being written over. It is read as a\n * rowId → dataset-position map, which is how an extension anchored on an\n * evicted row still knows where its anchor is: the range that anchor came\n * from is right there, and it remembers.\n */\nexport function adoptIndexedCellRangeSpans(ranges, replaced, snapshot, loadedWindow) {\n // No window, or one that cannot carry spans: `stampDatasetRowSpan` is the\n // whole of the behaviour, and there is nothing to recall from.\n if (!windowCarriesSpans(loadedWindow))\n return ranges.map((range) => stampDatasetRowSpan(range, snapshot, loadedWindow));\n const remembered = new Map();\n for (const range of replaced) {\n const span = range.datasetRowSpan;\n if (span === undefined)\n continue;\n if (!spanReadableInWindow(span, loadedWindow))\n continue;\n if (!remembered.has(range.start.rowId))\n remembered.set(range.start.rowId, span.start);\n if (!remembered.has(range.end.rowId))\n remembered.set(range.end.rowId, span.end);\n }\n return ranges.map((range) => {\n // Per endpoint, best source first: what the snapshot can see now, then\n // what this range already carries, then what the selection it replaces\n // remembers about that same row id.\n const own = endpointPositions(range, snapshot, loadedWindow);\n const start = own.start ?? remembered.get(range.start.rowId);\n const end = own.end ?? remembered.get(range.end.rowId);\n if (start === undefined || end === undefined)\n return stampDatasetRowSpan(range, snapshot, loadedWindow);\n const next = Object.freeze({\n start,\n end,\n datasetKey: loadedWindow.datasetKey,\n datasetTotal: loadedWindow.datasetTotal,\n });\n if (sameSpan(range.datasetRowSpan, next))\n return range;\n return Object.freeze({ ...range, datasetRowSpan: next });\n });\n}\n/**\n * The window absence may be judged AGAINST, which is not always the window\n * that was supplied.\n *\n * A new `datasetKey` is a new population: the dataset positions every span\n * remembers now hold different rows, and no row id can be presumed merely\n * evicted rather than gone. Retention is switched off for that revision — the\n * pre-eviction rules apply, which is what the spec means by \"a new datasetKey\n * resets everything, as today\".\n *\n * @internal Shared with `reconcileIndexedFocus`: the cursor and the selection\n * must switch retention off on the same revisions, or a population change\n * drops the selection while the cursor sits on a row from the old one.\n */\nexport function evictionRetentionWindow(eviction) {\n const suppliedWindow = eviction?.window ?? null;\n const previousWindow = eviction?.previous?.window;\n const populationChanged = suppliedWindow !== null &&\n previousWindow != null &&\n // Value comparison, not `spanReadableInWindow`: two keyless windows are\n // not evidence of a change. A keyless consumer gets no span trust at all\n // (see `windowCarriesSpans`), so there is nothing here to invalidate.\n previousWindow.datasetKey !== suppliedWindow.datasetKey;\n return populationChanged ? null : suppliedWindow;\n}\n/**\n * Whether this revision's window is UNKNOWN rather than absent.\n *\n * A null window is two entirely different situations and they want opposite\n * answers. In LOCAL mode the consumer hands over the whole result on every\n * `setRows`, so an absent row really has been deleted and pruning is correct.\n * In a WINDOWED grid whose honesty gate did not pass this revision — an\n * in-flight count query, a backend that estimates past 10k, one revision of\n * engine-side sort — the engine has been told nothing at all about which rows\n * exist. Dropping a selection there is the engine ASSERTING a deletion it\n * cannot have observed, from inputs that are every one of them transient\n * properties of a single render. Measured: one such revision destroyed an\n * eight-row selection AND the cursor permanently, and restoring the exact\n * total afterwards brought neither back, because the span was already gone.\n *\n * So: absent proof of deletion, retain. The same rule the rest of this file\n * already follows, applied to the case where the proof is not merely missing\n * but unobtainable.\n *\n * NOT the same question as {@link evictionRetentionWindow}, which also\n * returns null on a POPULATION CHANGE — a new `datasetKey`, where the engine\n * has been told plenty and what it was told is \"everything you remember is\n * about a different table\". That still resets, as the spec says it must.\n *\n * @internal Shared with `reconcileIndexedFocus`: the cursor and the selection\n * must reach the same verdict on the same revisions, or a grid retains a\n * selection under a cursor that moved.\n */\nexport function evictionWindowUnknown(eviction) {\n return (eviction?.windowed ?? false) && (eviction?.window ?? null) === null;\n}\nexport function reconcileIndexedSelection(selection, snapshot, eviction) {\n const suppliedWindow = eviction?.window ?? null;\n const previous = eviction?.previous;\n // STAMPING still runs against `suppliedWindow` on a population change, which\n // is the difference between this and simply passing `null` everywhere: a\n // range whose two endpoints are both present in the NEW population is fully\n // locatable there, so it is re-stamped in the new population's coordinates.\n // Passing `null` for that too would leave the old key sitting on the range,\n // refused by every reader but still emitted through `onSelectionChange`\n // and liable to be persisted by a consumer.\n const retentionWindow = evictionRetentionWindow(eviction);\n let changed = false;\n rowSelectionProgram(selection, snapshot);\n // The window is unknown this revision, so nothing below has anything to\n // reason FROM: absence is not evidence of deletion, and a position stamped\n // against no window would be a position in no coordinate system. A\n // reconciliation that learned nothing changes nothing. Returned after the\n // `rowSelectionProgram` call above, which rebuilds the visible-rank cache\n // and is required on every revision regardless of what this decides.\n //\n // Local mode never reaches this line — see `evictionWindowUnknown`.\n if (evictionWindowUnknown(eviction))\n return selection;\n const ranges = [];\n for (const range of selection.ranges) {\n const startVisible = visibleAddress(range.start, snapshot);\n const endVisible = visibleAddress(range.end, snapshot);\n if (startVisible && endVisible) {\n // Both endpoints are here, so this is the moment the span is knowable\n // first-hand. Record it; every later revision that cannot see them\n // reads it back.\n const stamped = stampDatasetRowSpan(range, snapshot, suppliedWindow);\n if (stamped !== range)\n changed = true;\n ranges.push(stamped);\n }\n else if (startVisible || endVisible) {\n const survivor = startVisible ? range.start : range.end;\n const absentee = startVisible ? range.end : range.start;\n // ONE endpoint gone is what an ordinary incremental scroll looks like:\n // the window slides past the range's start many revisions before it\n // reaches the end. Collapsing to the survivor there rewrites the\n // selection — and, because the collapsed range is stamped in turn,\n // overwrites the span that recorded how big it really was, so the\n // truth does not come back when the row does. Only a PROVEN deletion\n // earns the collapse; mere absence keeps the range whole, with the\n // survivor's position refreshed live and the absentee's read back\n // from the span.\n const absenteeDeleted = retentionWindow !== null &&\n provenDeletedRow(absentee.rowId, retentionWindow, previous);\n // A proven deletion prunes ONE ROW, not the range around it. The rows\n // between the endpoints are still selected — most of them loaded and\n // painted, in this branch — so the range narrows past the deleted\n // endpoint rather than collapsing onto the survivor and reporting a\n // selection of one.\n const narrowed = absenteeDeleted && retentionWindow !== null\n ? narrowDeletedEndpoints(range, snapshot, retentionWindow, {\n start: !startVisible,\n end: !endVisible,\n })\n : undefined;\n if (narrowed !== undefined) {\n ranges.push(narrowed);\n changed = true;\n }\n else if (retentionWindow === null || absenteeDeleted) {\n ranges.push(stampDatasetRowSpan(Object.freeze({ start: survivor, end: survivor }), snapshot, \n // `retentionWindow`, not `suppliedWindow`. On a population change\n // this is null, so the collapsed range gets NO span — which is\n // the whole point: it is a remnant of a selection the engine\n // could not locate in the new population, and a span would let\n // the summary call its one surviving row a proven extent. See\n // `rangeDatasetSpan`, which reads a missing span under a\n // span-carrying window as exactly that doubt.\n retentionWindow));\n changed = true;\n }\n else {\n const retained = stampDatasetRowSpan(range, snapshot, retentionWindow);\n if (retained !== range)\n changed = true;\n ranges.push(retained);\n }\n }\n else if (retentionWindow != null) {\n // Pruning requires POSITIVE proof of deletion for at least one\n // endpoint. Neither being provable does not retain \"half\" the row the\n // way partial visibility above does — the row is a single identity\n // that is either loaded or not, so an unprovable pair keeps the whole\n // range verbatim, letting a returning row come back selected.\n const startDeleted = provenDeletedRow(range.start.rowId, retentionWindow, previous);\n const endDeleted = provenDeletedRow(range.end.rowId, retentionWindow, previous);\n if (startDeleted || endDeleted) {\n changed = true;\n // Same rule as the branch above: the proven-deleted ROWS go, the span\n // around them stays. Dropping the range here is what took an evicted\n // 80-row selection down with a single deleted endpoint.\n const narrowed = narrowDeletedEndpoints(range, snapshot, retentionWindow, { start: startDeleted, end: endDeleted });\n if (narrowed !== undefined)\n ranges.push(narrowed);\n }\n else {\n ranges.push(range);\n }\n }\n else {\n changed = true;\n }\n }\n let anchor = selection.anchor;\n if (anchor !== null &&\n !visibleAddress(anchor, snapshot) &&\n // The anchor is the fixed end of the NEXT gesture —\n // `extendRangeFromAnchor` builds its range straight from this address —\n // so it is an identity, not a cursor into the loaded rows. Reassigning it\n // on visibility alone flips which end of an upward selection is fixed\n // (and, with several ranges, jumps it into a range the user never\n // anchored on): the next shift-click then extends from the wrong end and\n // deselects what they had. Only a PROVEN deletion earns the reassignment,\n // for the same reason it is what earns collapsing a range.\n (retentionWindow === null ||\n provenDeletedRow(anchor.rowId, retentionWindow, previous))) {\n anchor = ranges[0]?.start ?? null;\n changed = true;\n }\n if (!changed)\n return selection;\n return Object.freeze({\n ...selection,\n ranges: Object.freeze(ranges),\n anchor,\n });\n}\n","import { scrollTopToReveal, } from \"@pretable-internal/layout-core\";\nimport { evictionRetentionWindow, evictionWindowUnknown, provenDeletedRow, } from \"./indexed-selection\";\n/**\n * The one header address there is.\n *\n * Frozen and shared so identity comparison short-circuits — `sameRef` in\n * `create-grid-ui-core` still compares structurally, because a consumer may\n * hand in its own `{kind: \"header\"}` literal through `setFocus`.\n *\n * @internal Re-exported by `@pretable/core` as `ɵHEADER_FOCUS_REF`.\n */\nexport const HEADER_FOCUS_REF = Object.freeze({\n kind: \"header\",\n});\nfunction refOf(row) {\n return row.kind === \"data\"\n ? { kind: \"data\", rowId: row.rowId }\n : { kind: \"group\", groupId: row.groupId };\n}\nfunction emptyFocus() {\n return Object.freeze({\n ref: null,\n columnId: null,\n });\n}\nfunction focusAt(snapshot, index, columnId) {\n const row = snapshot.rowAt(index);\n return row === undefined\n ? undefined\n : Object.freeze({ ref: refOf(row), columnId });\n}\n/**\n * Where the cursor sits once `snapshot` has replaced the one it was placed\n * against.\n *\n * An absent focused row is TWO different situations, and the window is what\n * tells them apart — the same discriminator `reconcileIndexedSelection` uses,\n * reached through the same `provenDeletedRow`:\n *\n * - **Evicted** (absent, outside the loaded window): the row is coming back,\n * so the cursor is RETAINED. Re-seating here is what made a scroll away and\n * back move the user's cursor silently; Excel and AG Grid both keep it where\n * it was left and scroll it back into view. The spec's §5 rule — \"re-seat to\n * the nearest surviving row\" — was written before this distinction existed,\n * when an absent row could only mean a deleted one.\n * - **Deleted, hidden or unprovable-under-no-window** (absent from a span that\n * IS loaded): re-seat to the nearest survivor, exactly as before.\n *\n * With no window — local mode — this is byte-for-byte the pre-eviction\n * function: `retentionWindow` is null, so every absent row re-seats.\n */\nexport function reconcileIndexedFocus(focus, snapshot, eviction) {\n if (focus.ref === null || focus.columnId === null)\n return emptyFocus();\n // The header strip is not a row. The row model cannot evict it, delete it or\n // re-seat it, so a header cursor survives every snapshot byte-identical.\n // Falling through would be actively wrong rather than merely wasteful:\n // `indexOf` would report -1 for an address that is perfectly valid, and the\n // re-seat below would silently move the cursor onto a data row on the first\n // streaming patch.\n if (focus.ref.kind === \"header\")\n return focus;\n if (snapshot.indexOf(focus.ref) >= 0)\n return focus;\n // The window is unknown this revision, so this absence proves nothing — the\n // same verdict `reconcileIndexedSelection` reaches through the same\n // predicate, on the same revisions, which is the point of sharing it. A\n // group ref is excluded for the reason it is excluded below: it has no\n // dataset position, so no window could ever have said anything about it.\n if (focus.ref.kind === \"data\" && evictionWindowUnknown(eviction))\n return focus;\n const retentionWindow = evictionRetentionWindow(eviction);\n if (retentionWindow !== null &&\n // Group refs are not dataset rows: they have no data-only rank to convert\n // into a dataset position, so eviction can never be proven or disproven\n // for one. A collapsed or regrouped header re-seats to its ancestor as it\n // always did.\n focus.ref.kind === \"data\" &&\n !provenDeletedRow(focus.ref.rowId, retentionWindow, eviction?.previous)) {\n return focus;\n }\n const nearest = snapshot.nearestVisibleRef(focus.ref);\n if (nearest === undefined || snapshot.indexOf(nearest) < 0)\n return emptyFocus();\n return Object.freeze({ ref: nearest, columnId: focus.columnId });\n}\nexport function moveIndexedFocus(input) {\n const { snapshot, columns, movement } = input;\n if (columns.length === 0)\n return emptyFocus();\n // Reconciled FIRST, and WITH the eviction context, so every branch below\n // reasons about where the cursor actually is rather than where the caller\n // last saw it. In local mode this is the pre-eviction call verbatim: with no\n // window nothing is ever retained, so `current` is always either a loaded\n // row, the header, or nothing.\n const current = reconcileIndexedFocus(input.focus, snapshot, input.eviction);\n const headerColumnId = current.ref !== null &&\n current.ref.kind === \"header\" &&\n current.columnId !== null\n ? current.columnId\n : null;\n // Resolved ONCE and reused all the way down: this function is held to a\n // bounded number of row-model calls per keystroke, and a second `indexOf`\n // for the same address would break that budget.\n //\n // A negative answer for a ROW cursor means the row is not loaded and\n // reconciliation kept it anyway — it was EVICTED, and the row model is going\n // to get it back.\n const rowIndex = current.ref === null ||\n current.columnId === null ||\n current.ref.kind === \"header\"\n ? -1\n : snapshot.indexOf(current.ref);\n const unloadedCursor = current.ref !== null && current.ref.kind !== \"header\" && rowIndex < 0;\n // A grid with no rows still has a header, and a cursor already parked on it\n // stays there. Only the row-addressed cursors collapse — and not one held\n // over an evicted row, or releasing the whole window at once would drop the\n // cursor the moment the user pressed a key.\n if (snapshot.visibleRowCount === 0 &&\n headerColumnId === null &&\n !unloadedCursor)\n return emptyFocus();\n const lastColumnIndex = columns.length - 1;\n if (headerColumnId !== null) {\n const columnIndex = Math.max(0, columns.indexOf(headerColumnId));\n const onHeader = (index) => Object.freeze({\n ref: HEADER_FOCUS_REF,\n columnId: columns[Math.max(0, Math.min(lastColumnIndex, index))],\n });\n const intoBody = () => focusAt(snapshot, 0, headerColumnId) ?? onHeader(columnIndex);\n // Exhaustive on purpose, with no `default:`. Every movement in\n // `PretableIndexedFocusMovement` states what it does on a header cell here,\n // so adding a movement later is a compile error rather than a silent\n // fall-through onto a row-addressed code path that would call `indexOf`\n // with a header ref.\n switch (movement) {\n case \"left\":\n return onHeader(columnIndex - 1);\n case \"right\":\n return onHeader(columnIndex + 1);\n // The header is one row, so a vertical edge jump has nowhere to go and\n // the only edge it can mean is a column edge. `home` / `end` and the\n // explicitly horizontal pair therefore coincide here, and only here.\n case \"home\":\n case \"first-column\":\n return onHeader(0);\n case \"end\":\n case \"last-column\":\n return onHeader(lastColumnIndex);\n // The header is the top. `up` and `page-up` have nowhere further to go,\n // and consuming them is what stops an ArrowUp streak from popping focus\n // out of the grid entirely.\n case \"up\":\n case \"page-up\":\n return onHeader(columnIndex);\n // A header cell has no parent group — `parentGroupOf` would need a row.\n case \"parent\":\n return onHeader(columnIndex);\n case \"down\":\n case \"page-down\":\n return intoBody();\n // The header reads as the row above row 0 for a wrap walk: forward off\n // the last header column lands on the first body cell. Backward off the\n // first column returns unchanged, which is the same top-left corner\n // `shift-tab` already reports for row 0 — the surface releases there\n // rather than clamping, so this cannot become a keyboard trap.\n case \"tab\":\n return columnIndex === lastColumnIndex\n ? (focusAt(snapshot, 0, columns[0]) ?? onHeader(columnIndex))\n : onHeader(columnIndex + 1);\n case \"shift-tab\":\n return onHeader(columnIndex - 1);\n }\n }\n // Keyed off the CALLER's focus, not the reconciled one. \"No cursor at all\"\n // seeds a cursor at one corner of the grid; \"a cursor whose row is gone\"\n // clears it. Reconciliation turns the second into the first, so reading\n // `current` here would silently promote every absent cursor into a seed at\n // row 0 — the pre-eviction local-mode answer is `emptyFocus`, and it stays\n // that way.\n if (input.focus.ref === null || input.focus.columnId === null) {\n const reverseRow = movement === \"up\" || movement === \"end\" || movement === \"shift-tab\";\n const reverseColumn = movement === \"left\" ||\n movement === \"shift-tab\" ||\n movement === \"last-column\";\n return (focusAt(snapshot, reverseRow ? snapshot.visibleRowCount - 1 : 0, columns[reverseColumn ? lastColumnIndex : 0]) ?? emptyFocus());\n }\n // Reconciliation cleared a cursor the caller did supply: the row is gone and\n // there was no survivor to re-seat onto.\n if (current.ref === null || current.columnId === null)\n return current;\n // Unreachable in practice — the header block above returned for every header\n // cursor, and `reconcileIndexedFocus` cannot manufacture one. It is written\n // as a real branch rather than a cast so that the compiler narrows `ref` to a\n // ROW ref for the whole rest of this function: everything below indexes into\n // the row model, and an address the row model has never heard of must not be\n // able to reach it even if a future edit reorders these blocks.\n if (current.ref.kind === \"header\")\n return current;\n let columnIndex = columns.indexOf(current.columnId);\n if (columnIndex < 0)\n columnIndex = 0;\n // The two COLUMN-axis moves are answered before the row is required: they\n // read the column list and the cursor's own column, and neither needs to\n // know where the row sits — or whether it is loaded at all.\n if (movement === \"left\" || movement === \"right\") {\n const delta = movement === \"left\" ? -1 : 1;\n const nextColumn = columns[Math.max(0, Math.min(lastColumnIndex, columnIndex + delta))];\n return nextColumn === current.columnId\n ? current\n : Object.freeze({ ref: current.ref, columnId: nextColumn });\n }\n // The horizontal edges. Same row, opposite ends of it — the counterpart of\n // `home` / `end` below, which move along the other axis.\n if (movement === \"first-column\" || movement === \"last-column\") {\n const nextColumn = columns[movement === \"first-column\" ? 0 : lastColumnIndex];\n return nextColumn === current.columnId\n ? current\n : Object.freeze({ ref: current.ref, columnId: nextColumn });\n }\n // Everything past here reads the cursor's position AMONG THE LOADED ROWS,\n // and an evicted cursor has none.\n //\n // The move is REFUSED rather than redirected. The alternatives were: jump to\n // the nearest loaded row — which teleports the cursor across however many\n // rows were released, silently relocating a selection anchor the user set\n // deliberately; or move to the adjacent DATASET position and let the\n // consumer fetch it — which this state cannot even express, because\n // `PretableIndexedFocusRef` addresses a cursor by row identity and the\n // engine cannot name a row it has never loaded. Holding still keeps the\n // spec's guarantee that focus never falls to `<body>`, keeps the cursor\n // where the user left it, and leaves the positional-cursor question open\n // rather than answering it with a guess.\n //\n // In local mode this line is unreachable: with no window nothing is\n // retained, so `reconcileIndexedFocus` has already re-seated or cleared any\n // absent cursor and `rowIndex` cannot be negative here.\n if (rowIndex < 0)\n return current;\n if (movement === \"parent\") {\n const parent = snapshot.parentGroupOf(current.ref);\n return parent === undefined\n ? current\n : Object.freeze({\n ref: { kind: \"group\", groupId: parent.groupId },\n columnId: current.columnId,\n });\n }\n if (movement === \"tab\" || movement === \"shift-tab\") {\n const delta = movement === \"tab\" ? 1 : -1;\n if ((delta > 0 &&\n rowIndex === snapshot.visibleRowCount - 1 &&\n columnIndex === lastColumnIndex) ||\n (delta < 0 && rowIndex === 0 && columnIndex === 0)) {\n return current;\n }\n let nextRow = rowIndex;\n let nextColumn = columnIndex + delta;\n if (nextColumn > lastColumnIndex) {\n nextColumn = 0;\n nextRow += 1;\n }\n else if (nextColumn < 0) {\n nextColumn = lastColumnIndex;\n nextRow -= 1;\n }\n nextRow = Math.max(0, Math.min(snapshot.visibleRowCount - 1, nextRow));\n return focusAt(snapshot, nextRow, columns[nextColumn]) ?? current;\n }\n // Up off the first row lands on that column's HEADER cell, which is the only\n // way into the header now that its controls are out of the tab order. Before\n // this, ArrowUp on row 0 was a silent no-op.\n //\n // Deliberately `up` only. `page-up` still clamps at row 0: a page step is a\n // scroll-sized jump through rows, and having it fall off the top into a\n // single header cell would make \"page up twice\" mean two different things.\n if (movement === \"up\" && rowIndex === 0) {\n return Object.freeze({\n ref: HEADER_FOCUS_REF,\n columnId: current.columnId,\n });\n }\n const pageRows = Number.isSafeInteger(input.pageRows) && (input.pageRows ?? 0) > 0\n ? input.pageRows\n : 10;\n const nextRow = movement === \"home\"\n ? 0\n : movement === \"end\"\n ? snapshot.visibleRowCount - 1\n : Math.max(0, Math.min(snapshot.visibleRowCount - 1, rowIndex +\n (movement === \"up\"\n ? -1\n : movement === \"down\"\n ? 1\n : movement === \"page-up\"\n ? -pageRows\n : pageRows)));\n return nextRow === rowIndex\n ? current\n : (focusAt(snapshot, nextRow, current.columnId) ?? current);\n}\nexport function getScrollTopForIndexedFocus(input) {\n // The header is sticky: it is on screen at every scroll offset, so there is\n // nothing to reveal. `null` is this function's existing \"already resolved,\n // do not write a scrollTop\" answer — the same one an in-view row gets — and\n // is what stops a move onto the header from yanking the body to row 0.\n if (input.ref.kind === \"header\")\n return null;\n const targetIndex = input.snapshot.indexOf(input.ref);\n if (targetIndex < 0)\n return null;\n return scrollTopToReveal({\n rowMetrics: input.rowMetrics,\n targetIndex,\n scrollTop: input.scrollTop,\n viewportHeight: input.viewportHeight,\n });\n}\n","// The engine's stored default for a column that declares no `widthPx` —\n// layout-core's single source of truth, shared with renderer-dom's drawing\n// fallback so the stored width and the drawn width agree for a never-resized\n// column (see column-defaults.ts for the decision note).\nimport { DEFAULT_COLUMN_WIDTH_PX } from \"@pretable-internal/layout-core\";\nimport { moveIndexedFocus, reconcileIndexedFocus } from \"./indexed-focus\";\nimport { adoptIndexedCellRangeSpans, createEmptyIndexedSelection, createIndexedRowSelection, getIndexedCellSelectionSummary, getIndexedSelectionSummary, isIndexedRowSelected, preserveIndexedRowSelectionProgram, projectIndexedSelection, reconcileIndexedSelection, releaseIndexedRowSelectionProgram, sameIndexedRowSelectionProgram, sameIndexedRowSelectionValue, selectAllVisibleRows, selectIndexedRowRange, toImmutableIndexedSet, toggleIndexedRowSelection, } from \"./indexed-selection\";\nexport class PretableGridUiError extends Error {\n code;\n cause;\n constructor(code, message, cause) {\n super(message);\n this.name = \"PretableGridUiError\";\n this.code = code;\n this.cause = cause;\n }\n}\nconst EMPTY_VIEWPORT = Object.freeze({\n scrollTop: 0,\n scrollLeft: 0,\n height: 0,\n width: 0,\n});\nfunction sameValueZero(left, right) {\n return left === right || (left !== left && right !== right);\n}\nfunction sameRef(left, right) {\n if (left === right)\n return true;\n if (left === null || right === null || left.kind !== right.kind)\n return false;\n // Two header refs are the same address: the kind IS the whole address, since\n // the column lives on the focus state beside the ref. The compiler could not\n // have caught this one — the chain below is a boolean expression, not an\n // exhaustive switch, so a widened union just makes it silently return\n // `false` for every header/header pair. That would publish a \"changed\" focus\n // on every no-op `setFocus`, and re-render the surface on every arrow key\n // that did not actually move.\n if (left.kind === \"header\" && right.kind === \"header\")\n return true;\n return left.kind === \"data\" && right.kind === \"data\"\n ? sameValueZero(left.rowId, right.rowId)\n : left.kind === \"group\" &&\n right.kind === \"group\" &&\n left.groupId === right.groupId;\n}\nfunction sameViewport(left, right) {\n return (left.scrollTop === right.scrollTop &&\n left.scrollLeft === right.scrollLeft &&\n left.height === right.height &&\n left.width === right.width);\n}\nfunction normalizeViewport(viewport) {\n if (!Number.isFinite(viewport.scrollTop) ||\n !Number.isFinite(viewport.scrollLeft) ||\n !Number.isFinite(viewport.height) ||\n !Number.isFinite(viewport.width) ||\n viewport.height < 0 ||\n viewport.width < 0) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"Grid UI viewport values must be finite with non-negative dimensions.\");\n }\n return Object.freeze({ ...viewport });\n}\nfunction normalizeColumns(columns) {\n const ids = new Set();\n const normalized = columns.map((column) => {\n if (ids.has(column.id)) {\n throw new PretableGridUiError(\"invalid-ui-state\", `Duplicate visual column id: ${column.id}`);\n }\n const widthPx = column.widthPx ?? DEFAULT_COLUMN_WIDTH_PX;\n if (!Number.isFinite(widthPx) || widthPx <= 0) {\n throw new PretableGridUiError(\"invalid-ui-state\", `Visual column width must be positive for: ${column.id}`);\n }\n ids.add(column.id);\n return Object.freeze({\n id: column.id,\n widthPx,\n ...(column.pinned === undefined ? {} : { pinned: column.pinned }),\n // Strip-when-false, matching `setColumnVisible`: a visible entry never\n // carries the key, so the two ways of arriving at \"visible\" are\n // byte-identical.\n ...(column.hidden === true ? { hidden: true } : {}),\n });\n });\n return Object.freeze(orderPinnedColumns(normalized));\n}\nfunction orderPinnedColumns(columns) {\n return [\n ...columns.filter((column) => column.pinned === \"left\"),\n ...columns.filter((column) => column.pinned === undefined),\n ...columns.filter((column) => column.pinned === \"right\"),\n ];\n}\n/**\n * The still-visible column nearest to `hiddenIndex` in layout order: every\n * column to its left is tried first, nearest outward, then every column to\n * its right — `null` when every other column is hidden too.\n */\nfunction nearestVisibleColumnId(layout, hiddenIndex) {\n for (let index = hiddenIndex - 1; index >= 0; index -= 1) {\n if (layout[index].hidden !== true)\n return layout[index].id;\n }\n for (let index = hiddenIndex + 1; index < layout.length; index += 1) {\n if (layout[index].hidden !== true)\n return layout[index].id;\n }\n return null;\n}\nfunction copySelection(selection, \n/**\n * What this write replaces, plus the coordinates to express the result in.\n * A gesture hands over ranges built from row ids alone, so this is where\n * their dataset spans come from — see `adoptIndexedCellRangeSpans`. Absent\n * `loadedWindow` (local mode, the honesty gate not passing, or simply no\n * revision observed yet) is the pre-eviction path: no span is derived, and\n * one already present is carried through untouched rather than dropped,\n * because it is inert without a window and the window is legitimately\n * absent on the render that restores a persisted selection.\n */\ncontext) {\n const rows = selection.rows.kind === \"explicit\"\n ? Object.freeze({\n kind: \"explicit\",\n rowIds: toImmutableIndexedSet(selection.rows.rowIds),\n ...(selection.rows.ranges === undefined\n ? {}\n : { ranges: selection.rows.ranges }),\n ...(selection.rows.excludedRanges === undefined\n ? {}\n : { excludedRanges: selection.rows.excludedRanges }),\n })\n : Object.freeze({\n kind: \"all\",\n ...(selection.rows.excludedRanges === undefined\n ? {}\n : { excludedRanges: selection.rows.excludedRanges }),\n });\n preserveIndexedRowSelectionProgram(selection.rows, rows);\n return Object.freeze({\n rows,\n ranges: Object.freeze(adoptIndexedCellRangeSpans(selection.ranges.map((range) => Object.freeze({\n start: Object.freeze({ ...range.start }),\n end: Object.freeze({ ...range.end }),\n // Copied, not rebuilt from ids: this is the only public write\n // path, so dropping the span here un-counts every retained range\n // in the selection — including the ones the gesture never\n // touched.\n ...(range.datasetRowSpan === undefined\n ? {}\n : { datasetRowSpan: Object.freeze({ ...range.datasetRowSpan }) }),\n })), context.replaced, context.snapshot, context.loadedWindow)),\n anchor: selection.anchor === null ? null : Object.freeze({ ...selection.anchor }),\n });\n}\nfunction sameFocus(left, right) {\n return sameRef(left.ref, right.ref) && left.columnId === right.columnId;\n}\nfunction sameSet(left, right) {\n if (left.size !== right.size)\n return false;\n for (const value of left) {\n if (!right.has(value))\n return false;\n }\n return true;\n}\nfunction sameRowRanges(left, right) {\n if (left === right)\n return true;\n if (left?.size !== right?.size)\n return false;\n const leftIterator = left?.[Symbol.iterator]();\n const rightIterator = right?.[Symbol.iterator]();\n if (leftIterator === undefined || rightIterator === undefined)\n return false;\n for (;;) {\n const leftNext = leftIterator.next();\n const rightNext = rightIterator.next();\n if (leftNext.done || rightNext.done)\n return leftNext.done === rightNext.done;\n if (!sameValueZero(leftNext.value.startRowId, rightNext.value.startRowId) ||\n !sameValueZero(leftNext.value.endRowId, rightNext.value.endRowId))\n return false;\n }\n}\nfunction sameDatasetRowSpan(left, right) {\n if (left === right)\n return true;\n if (left === undefined || right === undefined)\n return false;\n return (left.start === right.start &&\n left.end === right.end &&\n left.datasetKey === right.datasetKey &&\n left.datasetTotal === right.datasetTotal);\n}\nfunction sameSelection(left, right) {\n if (left.rows.kind !== right.rows.kind)\n return false;\n if (!sameIndexedRowSelectionProgram(left.rows, right.rows))\n return false;\n let sameRows = false;\n if (left.rows.kind === \"explicit\" && right.rows.kind === \"explicit\") {\n const leftRows = left.rows;\n const rightRows = right.rows;\n sameRows =\n sameSet(leftRows.rowIds, rightRows.rowIds) &&\n sameRowRanges(leftRows.excludedRanges, rightRows.excludedRanges) &&\n sameRowRanges(leftRows.ranges, rightRows.ranges);\n }\n else if (left.rows.kind === \"all\" && right.rows.kind === \"all\") {\n sameRows = sameRowRanges(left.rows.excludedRanges, right.rows.excludedRanges);\n }\n if (!sameRows || left.ranges.length !== right.ranges.length)\n return false;\n for (let index = 0; index < left.ranges.length; index += 1) {\n const leftRange = left.ranges[index];\n const rightRange = right.ranges[index];\n if (!sameValueZero(leftRange.start.rowId, rightRange.start.rowId) ||\n leftRange.start.columnId !== rightRange.start.columnId ||\n !sameValueZero(leftRange.end.rowId, rightRange.end.rowId) ||\n leftRange.end.columnId !== rightRange.end.columnId ||\n // The span is part of a range's identity, not decoration on it: while\n // the rows are evicted it is the ONLY thing that says how large the\n // selection is, and two ranges over the same ids with different spans\n // select different numbers of rows. Comparing it is safe precisely\n // because `copySelection` recovers a missing span from the selection\n // being replaced — so a controlled `state` echo that drops the field\n // still compares equal, and the effect stays the no-op it has to be.\n !sameDatasetRowSpan(leftRange.datasetRowSpan, rightRange.datasetRowSpan)) {\n return false;\n }\n }\n if (left.anchor === null || right.anchor === null) {\n return left.anchor === right.anchor;\n }\n return (sameValueZero(left.anchor.rowId, right.anchor.rowId) &&\n left.anchor.columnId === right.anchor.columnId);\n}\n/**\n * Creates the framework-independent indexed UI store.\n *\n * @internal Re-exported by `@pretable/core` as `ɵcreateGridUiCore` for\n * `@pretable/react`, which must reach the engine through the same declaration\n * emission `@pretable/core` publishes rather than through this package\n * directly. See the note on that re-export in `packages/core/src/public_api.ts`.\n */\nexport function createGridUiCore(options) {\n const listeners = new Set();\n const queuedActions = [];\n const columnLayout = normalizeColumns(options.columns);\n const initialColumnIds = Object.freeze(columnLayout.map((column) => column.id));\n let cachedNavigationLayout = columnLayout;\n let cachedNavigationColumnIds = initialColumnIds;\n let disposed = false;\n let notifying = false;\n let draining = false;\n let projecting = false;\n let activeProjectionToken;\n // The snapshot as of the last successful reconciliation, paired with the\n // window that was active for it — a single binding rather than two `let`s\n // updated adjacently, so the pairing a later reconciliation converts\n // data-only ranks through (see `provenDeletedRow` in\n // `indexed-selection.ts`) cannot desynchronize.\n let observed;\n let state = Object.freeze({\n viewport: options.viewport\n ? normalizeViewport(options.viewport)\n : EMPTY_VIEWPORT,\n focus: Object.freeze({ ref: null, columnId: null }),\n selection: createEmptyIndexedSelection(),\n editing: null,\n columnLayout,\n // Absent, not `false`, when unsupplied — see the field's doc comment.\n ...(options.hideGroupedColumns === undefined\n ? {}\n : { hideGroupedColumns: options.hideGroupedColumns }),\n // Always present, and empty until a pane writes one: an absent key means\n // \"no override\", which an empty map already says. See the field's doc.\n columnAggregates: Object.freeze({}),\n observedRowModelRevision: null,\n });\n const assertActive = () => {\n if (disposed) {\n throw new PretableGridUiError(\"disposed-grid-ui\", \"The grid UI store has been disposed.\");\n }\n };\n const drain = () => {\n if (notifying || draining || projecting || disposed)\n return;\n draining = true;\n try {\n while (queuedActions.length > 0 && !disposed) {\n try {\n queuedActions.shift().action();\n }\n catch {\n // Reentrant commands have no synchronous error channel after listener return.\n }\n }\n }\n finally {\n draining = false;\n }\n };\n const notify = () => {\n notifying = true;\n try {\n for (const listener of Array.from(listeners)) {\n try {\n listener();\n }\n catch {\n // One external-store subscriber cannot block the remaining listeners.\n }\n }\n }\n finally {\n notifying = false;\n }\n drain();\n };\n const publish = (next) => {\n if (next === state)\n return;\n state = Object.freeze(next);\n notify();\n };\n const command = (action) => {\n assertActive();\n if (notifying || draining || projecting) {\n queuedActions.push({\n action,\n ...(projecting && activeProjectionToken !== undefined\n ? { projectionToken: activeProjectionToken }\n : {}),\n });\n return;\n }\n action();\n };\n const discardProjectionActions = (token) => {\n for (let index = queuedActions.length - 1; index >= 0; index -= 1) {\n if (queuedActions[index].projectionToken === token) {\n queuedActions.splice(index, 1);\n }\n }\n };\n const observationError = (message, cause) => cause instanceof PretableGridUiError &&\n cause.code === \"row-model-observation-failed\"\n ? cause\n : new PretableGridUiError(\"row-model-observation-failed\", message, cause);\n const snapshotForInteraction = () => {\n try {\n return observed?.snapshot ?? options.rowModel.getState().snapshot;\n }\n catch (cause) {\n throw new PretableGridUiError(\"row-model-observation-failed\", \"The row-model snapshot could not be read for a UI interaction.\", cause);\n }\n };\n /**\n * The snapshot an interaction must express dataset positions in, paired\n * with the window those positions are offsets into.\n *\n * Both come from `observed` — the single binding `observeRowModelRevision`\n * commits atomically — and never from a fresh `getSelectionWindow()` read\n * against a snapshot from some other moment. That combination is a\n * chimera, and it is not hypothetical: the react surface publishes the\n * window from `resultMeta` in an insertion effect, while the matching rows\n * reach the row model through `setRows`, which settles across cooperative\n * slices. In between, the window says \"the loaded rows start at 5\" and the\n * snapshot still holds the rows that start at 0 — so every loaded row\n * resolves to a position five rows too high, and a selection written in\n * that instant records a span five rows off, permanently.\n *\n * With nothing observed yet there is no committed pairing at all, so the\n * window is reported as absent rather than guessed: no span is derived,\n * which is exactly the pre-eviction behaviour.\n */\n const interactionContext = () => observed ?? {\n snapshot: snapshotForInteraction(),\n window: null,\n windowed: false,\n };\n const navigationColumnIds = () => {\n if (cachedNavigationLayout !== state.columnLayout) {\n cachedNavigationLayout = state.columnLayout;\n // Drawn columns only: keyboard movement over the full layout would let\n // an arrow key land focus on a hidden column — exactly the state\n // `setColumnVisible` repairs its way out of.\n cachedNavigationColumnIds = Object.freeze(state.columnLayout\n .filter((column) => column.hidden !== true)\n .map((column) => column.id));\n }\n return cachedNavigationColumnIds;\n };\n const performDispose = () => {\n if (disposed)\n return;\n disposed = true;\n activeProjectionToken = undefined;\n observed = undefined;\n releaseIndexedRowSelectionProgram(state.selection.rows);\n queuedActions.length = 0;\n const captured = Array.from(listeners);\n listeners.clear();\n for (const listener of captured) {\n try {\n listener();\n }\n catch {\n // Disposal still detaches every listener after a hostile callback.\n }\n }\n };\n const grid = {\n rowModel: options.rowModel,\n getState: () => state,\n subscribe(listener) {\n if (disposed)\n return () => undefined;\n listeners.add(listener);\n let active = true;\n return () => {\n if (!active)\n return;\n active = false;\n listeners.delete(listener);\n };\n },\n setViewport(viewport) {\n const next = normalizeViewport(viewport);\n command(() => {\n if (sameViewport(state.viewport, next))\n return;\n publish({ ...state, viewport: next });\n });\n },\n setFocus(focus) {\n const next = Object.freeze({\n ref: focus.ref === null ? null : Object.freeze({ ...focus.ref }),\n columnId: focus.columnId,\n });\n command(() => {\n if (sameFocus(state.focus, next))\n return;\n publish({ ...state, focus: next });\n });\n },\n moveFocus(movement, moveOptions) {\n command(() => {\n let next;\n try {\n const context = interactionContext();\n next = moveIndexedFocus({\n snapshot: context.snapshot,\n columns: navigationColumnIds(),\n focus: state.focus,\n movement,\n pageRows: moveOptions?.pageRows,\n // The same window the reconcile path judges absence against, so a\n // keystroke and a revision cannot disagree about whether the\n // cursor's row was evicted or deleted.\n //\n // No `previous`: the only committed snapshot/window pairing at\n // interaction time is this one, so nothing here could prove a\n // deletion anyway — and nothing needs to. A row deleted since the\n // last revision was already reconciled out of `state.focus` when\n // that revision was observed; what is left absent is either\n // evicted or an address a consumer handed to `setFocus`, and\n // holding the cursor is the right answer to both.\n eviction: { window: context.window, windowed: context.windowed },\n });\n }\n catch (cause) {\n throw observationError(\"Indexed focus navigation could not be completed atomically.\", cause);\n }\n if (sameFocus(state.focus, next))\n return;\n publish({ ...state, focus: next });\n });\n },\n setSelection(selection) {\n let next;\n try {\n const context = interactionContext();\n next = copySelection(selection, {\n replaced: state.selection.ranges,\n snapshot: context.snapshot,\n loadedWindow: context.window,\n });\n }\n catch (cause) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"The supplied selection could not be captured atomically.\", cause);\n }\n command(() => {\n if (sameSelection(state.selection, next))\n return;\n publish({ ...state, selection: next });\n });\n },\n setRowSelection(rows) {\n command(() => {\n let nextRows;\n try {\n nextRows = createIndexedRowSelection(rows, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"The supplied row selection could not be applied atomically.\", cause);\n }\n // Value equality, not `sameSelection`: a rebuilt slice never shares the\n // original's semantic program, so `sameSelection` would call every\n // re-application a change and a controlled caller pushing on each\n // render would publish forever.\n if (sameIndexedRowSelectionValue(state.selection.rows, nextRows))\n return;\n publish({\n ...state,\n selection: Object.freeze({ ...state.selection, rows: nextRows }),\n });\n });\n },\n toggleRowSelection(rowId) {\n command(() => {\n let next;\n try {\n next = toggleIndexedRowSelection(state.selection, rowId, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"Indexed selection could not be updated atomically.\", cause);\n }\n if (next === state.selection)\n return;\n publish({ ...state, selection: next });\n });\n },\n selectRowRange(startRowId, endRowId) {\n command(() => {\n let next;\n try {\n next = selectIndexedRowRange(state.selection, startRowId, endRowId, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"Indexed row range selection could not be updated atomically.\", cause);\n }\n if (next === state.selection)\n return;\n publish({ ...state, selection: next });\n });\n },\n isRowSelected(rowId) {\n try {\n return isIndexedRowSelected(state.selection, { kind: \"data\", rowId }, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"Indexed row selection could not be observed atomically.\", cause);\n }\n },\n getSelectionSummary() {\n try {\n return getIndexedSelectionSummary(state.selection, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"Indexed row selection summary could not be observed atomically.\", cause);\n }\n },\n getCellSelectionSummary() {\n try {\n const context = interactionContext();\n return getIndexedCellSelectionSummary(state.selection, context.snapshot, context.window);\n }\n catch (cause) {\n throw observationError(\"Indexed cell selection summary could not be observed atomically.\", cause);\n }\n },\n selectAllVisibleRows() {\n command(() => {\n let next;\n try {\n next = selectAllVisibleRows(state.selection, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"Indexed select-all could not be updated atomically.\", cause);\n }\n if (next === state.selection)\n return;\n publish({ ...state, selection: next });\n });\n },\n clearSelection() {\n command(() => {\n const next = createEmptyIndexedSelection();\n if (state.selection.rows.kind === \"explicit\" &&\n state.selection.rows.rowIds.size === 0 &&\n state.selection.ranges.length === 0 &&\n state.selection.anchor === null) {\n return;\n }\n publish({ ...state, selection: next });\n });\n },\n beginEdit(input) {\n const editing = Object.freeze({\n rowId: input.rowId,\n columnId: input.columnId,\n value: input.value,\n status: input.status ?? \"editing\",\n });\n command(() => {\n const snapshot = observed?.snapshot;\n let visible = false;\n try {\n visible =\n snapshot !== undefined &&\n snapshot.indexOf({ kind: \"data\", rowId: input.rowId }) >= 0;\n }\n catch (cause) {\n throw observationError(\"The edit target could not be resolved atomically.\", cause);\n }\n // Widened to `string` by assignment (not asserted): `TEditColumnId`\n // ranges over the SCHEMA ids and `columnLayout` over the DRAWN ones,\n // and the question being asked is precisely whether this schema\n // column is among the drawn ones — which no relation between the two\n // parameters can answer, because a presentation layer is free to omit\n // a schema column. So it is answered at runtime, over the one\n // vocabulary both sides provably share.\n const editColumnId = input.columnId;\n if (!visible ||\n !state.columnLayout.some(\n // A hidden column has no cell on screen to host an editor, so it\n // is no more editable than a column outside the layout.\n (column) => column.id === editColumnId && column.hidden !== true)) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"Editing requires a visible data row and visual column from the observed layout.\");\n }\n publish({ ...state, editing });\n });\n },\n setEditDraft(value) {\n command(() => {\n if (state.editing === null || Object.is(state.editing.value, value))\n return;\n publish({\n ...state,\n editing: Object.freeze({\n ...state.editing,\n value,\n status: \"editing\",\n error: undefined,\n }),\n });\n });\n },\n setEditStatus(status, error) {\n command(() => {\n if (state.editing === null)\n return;\n if (state.editing.status === status && state.editing.error === error)\n return;\n publish({\n ...state,\n editing: Object.freeze({\n ...state.editing,\n status,\n ...(error === undefined ? { error: undefined } : { error }),\n }),\n });\n });\n },\n cancelEdit() {\n command(() => {\n if (state.editing === null)\n return;\n publish({ ...state, editing: null });\n });\n },\n setColumns(columns) {\n const nextLayout = normalizeColumns(columns);\n command(() => {\n const same = nextLayout.length === state.columnLayout.length &&\n nextLayout.every((column, index) => {\n const current = state.columnLayout[index];\n return (current?.id === column.id &&\n current.widthPx === column.widthPx &&\n current.pinned === column.pinned &&\n current.hidden === column.hidden);\n });\n if (same)\n return;\n // `Set<string>`, not `Set<TColumnId>`: `editing.columnId` below is a\n // SCHEMA id, and the drawn vocabulary is a different parameter, so\n // membership is answerable only over `string`. This set is LAYOUT\n // membership — hidden entries included — which is what focus and\n // selection repair against; editing repairs against the stricter\n // drawn set below.\n const ids = new Set(nextLayout.map((column) => column.id));\n const focus = state.focus.columnId === null || ids.has(state.focus.columnId)\n ? state.focus\n : Object.freeze({ ref: null, columnId: null });\n const ranges = state.selection.ranges.filter((range) => ids.has(range.start.columnId) && ids.has(range.end.columnId));\n const anchor = state.selection.anchor !== null &&\n ids.has(state.selection.anchor.columnId)\n ? state.selection.anchor\n : null;\n const selection = ranges === state.selection.ranges && anchor === state.selection.anchor\n ? state.selection\n : Object.freeze({ ...state.selection, ranges, anchor });\n // Editing is stricter than focus and selection: `beginEdit` demands a\n // DRAWN column, so a column the incoming config hides cancels the\n // session exactly like one it removes — the same repair\n // `setColumnVisible` applies.\n const drawnIds = new Set(nextLayout.flatMap((column) => column.hidden === true ? [] : [column.id]));\n // Overrides for columns this config drops go with them. Not because\n // they would be unreachable — re-adding the column reaches them again\n // — but because that is the hazard: a stale override would silently\n // resurrect the moment the column came back, with no user action in\n // between. `ids`, so a column merely marked `hidden` keeps its\n // override; it is still in the layout, like its width and pin.\n const retainedAggregates = Object.fromEntries(Object.entries(state.columnAggregates).filter(([id]) => ids.has(id)));\n // Reuse the existing object when nothing was pruned. `setColumns`\n // publishes regardless (`columnLayout` changed), so this branch buys\n // nothing but referential stability — which is the whole input to a\n // downstream memo over the overrides.\n const columnAggregates = Object.keys(retainedAggregates).length ===\n Object.keys(state.columnAggregates).length\n ? state.columnAggregates\n : Object.freeze(retainedAggregates);\n publish({\n ...state,\n columnLayout: nextLayout,\n columnAggregates,\n focus,\n selection,\n editing: state.editing !== null && drawnIds.has(state.editing.columnId)\n ? state.editing\n : null,\n });\n });\n },\n setColumnWidth(columnId, width) {\n if (!Number.isFinite(width) || width <= 0) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"Visual column width must be positive.\");\n }\n command(() => {\n const index = state.columnLayout.findIndex((column) => column.id === columnId);\n if (index < 0 || state.columnLayout[index].widthPx === width)\n return;\n const next = state.columnLayout.slice();\n next[index] = Object.freeze({ ...next[index], widthPx: width });\n publish({\n ...state,\n columnLayout: Object.freeze(orderPinnedColumns(next)),\n });\n });\n },\n setColumnPinned(columnId, pinned) {\n command(() => {\n const index = state.columnLayout.findIndex((column) => column.id === columnId);\n const current = state.columnLayout[index];\n if (current === undefined || (current.pinned ?? null) === pinned)\n return;\n const next = state.columnLayout.slice();\n // Clearing rebuilds the entry to strip `pinned` (never writes\n // `pinned: undefined`), but every OTHER optional key must survive the\n // rebuild — unpinning a hidden column must not reveal it.\n next[index] = Object.freeze(pinned === null\n ? {\n id: current.id,\n widthPx: current.widthPx,\n ...(current.hidden === true ? { hidden: true } : {}),\n }\n : { ...current, pinned });\n publish({\n ...state,\n columnLayout: Object.freeze(orderPinnedColumns(next)),\n });\n });\n },\n setColumnVisible(columnId, visible) {\n command(() => {\n const index = state.columnLayout.findIndex((column) => column.id === columnId);\n const current = state.columnLayout[index];\n if (current === undefined || (current.hidden !== true) === visible)\n return;\n const next = state.columnLayout.slice();\n next[index] = Object.freeze(visible\n ? {\n id: current.id,\n widthPx: current.widthPx,\n ...(current.pinned === undefined\n ? {}\n : { pinned: current.pinned }),\n }\n : { ...current, hidden: true });\n // Visibility does not reorder — hidden entries hold their place so\n // re-showing restores it — so `orderPinnedColumns` need not re-run.\n const columnLayout = Object.freeze(next);\n if (visible) {\n publish({ ...state, columnLayout });\n return;\n }\n // The cursor and the anchor cannot keep addressing a hidden column:\n // re-seat each onto the nearest still-visible neighbor in layout\n // order, left first, then right — inside this same command so the\n // layout change and its repairs publish as one wake.\n const neighbor = nearestVisibleColumnId(next, index);\n const focus = state.focus.columnId !== columnId\n ? state.focus\n : neighbor === null\n ? Object.freeze({ ref: null, columnId: null })\n : Object.freeze({ ref: state.focus.ref, columnId: neighbor });\n const anchor = state.selection.anchor !== null &&\n state.selection.anchor.columnId === columnId\n ? neighbor === null\n ? null\n : Object.freeze({ ...state.selection.anchor, columnId: neighbor })\n : state.selection.anchor;\n const selection = anchor === state.selection.anchor\n ? state.selection\n : Object.freeze({ ...state.selection, anchor });\n // An open edit session on the hidden column loses its cell, so it is\n // cancelled — the same repair `setColumns` applies when the edited\n // column leaves the layout entirely.\n const editing = state.editing !== null &&\n state.editing.columnId === columnId\n ? null\n : state.editing;\n publish({ ...state, columnLayout, focus, selection, editing });\n });\n },\n setColumnOrder(nextColumnIds) {\n command(() => {\n if (nextColumnIds.length !== state.columnLayout.length) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"Column order must contain every column in the layout, hidden included, exactly once.\");\n }\n const byId = new Map(state.columnLayout.map((column) => [column.id, column]));\n const next = nextColumnIds.map((columnId) => {\n const column = byId.get(columnId);\n if (column === undefined) {\n throw new PretableGridUiError(\"invalid-ui-state\", `Unknown or repeated visual column id: ${columnId}`);\n }\n byId.delete(columnId);\n return column;\n });\n if (byId.size > 0) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"Column order must contain every column in the layout, hidden included, exactly once.\");\n }\n const ordered = orderPinnedColumns(next);\n if (ordered.every((column, index) => column === state.columnLayout[index]))\n return;\n publish({ ...state, columnLayout: Object.freeze(ordered) });\n });\n },\n setHideGroupedColumns(value) {\n command(() => {\n if (state.hideGroupedColumns === value)\n return;\n publish({ ...state, hideGroupedColumns: value });\n });\n },\n setColumnAggregate(columnId, aggregate) {\n command(() => {\n // LAYOUT membership, hidden entries included — not the drawn set: a\n // hidden column takes an override exactly as it takes a width or a\n // pin. An id the layout does not hold at all is a no-op, matching\n // `setColumnPinned`/`setColumnWidth`: an override is not geometry, but\n // one recorded for an id the layout never holds has nothing to evict\n // it.\n if (!state.columnLayout.some((column) => column.id === columnId))\n return;\n const present = columnId in state.columnAggregates;\n if (aggregate === undefined) {\n // Strip-when-clearing, never `{ [columnId]: undefined }`: a present\n // key is what marks a column as pane-chosen, so writing the key back\n // as undefined would pin the column to \"no aggregate\" instead of\n // returning it to the one declared on the prop.\n if (!present)\n return;\n const next = { ...state.columnAggregates };\n delete next[columnId];\n publish({ ...state, columnAggregates: Object.freeze(next) });\n return;\n }\n // No `present &&` guard: `aggregate` is non-`undefined` here, so a\n // matching `===` already implies the key is present.\n if (state.columnAggregates[columnId] === aggregate)\n return;\n publish({\n ...state,\n columnAggregates: Object.freeze({\n ...state.columnAggregates,\n [columnId]: aggregate,\n }),\n });\n });\n },\n observeRowModelRevision(revision) {\n command(() => {\n const token = {};\n activeProjectionToken = token;\n projecting = true;\n let committed = false;\n try {\n const modelState = options.rowModel.getState();\n const snapshot = modelState.snapshot;\n const capturedRevision = snapshot.revision;\n if (!Number.isSafeInteger(capturedRevision) || capturedRevision < 0) {\n throw new TypeError(\"The row-model snapshot revision must be a non-negative safe integer.\");\n }\n if (capturedRevision !== revision ||\n state.observedRowModelRevision === revision) {\n return;\n }\n // ONE read of the window channel per revision, into one object:\n // windowed-ness and the window itself must describe the same\n // instant or the engine can conclude \"local mode\" from a windowed\n // grid's momentary gate closure.\n const windowing = options.getWindowing?.() ?? null;\n const selectionWindow = windowing?.window ?? null;\n // `observed` is read here, before the sole reassignment below (at\n // the end of this same block, after every read), so it still\n // holds the snapshot/window pairing from the LAST successful\n // commit — the only pairing a data-only rank recorded against\n // `observed.snapshot` is valid for.\n //\n // The cursor and the selection are handed the SAME context, from\n // the same two reads: they have to reach the same verdict about a\n // row, or a grid retains a selection under a cursor that moved.\n const eviction = {\n window: selectionWindow,\n windowed: windowing !== null,\n previous: observed,\n };\n const focus = reconcileIndexedFocus(state.focus, snapshot, eviction);\n const selection = reconcileIndexedSelection(observed === undefined\n ? state.selection\n : projectIndexedSelection(state.selection, observed.snapshot, snapshot, options.rowModel.changesSince(observed.snapshot.revision)), snapshot, eviction);\n let editing = state.editing;\n if (editing !== null &&\n snapshot.indexOf({ kind: \"data\", rowId: editing.rowId }) < 0) {\n editing = null;\n }\n if (disposed || activeProjectionToken !== token)\n return;\n const currentModelState = options.rowModel.getState();\n const currentSnapshot = currentModelState.snapshot;\n const currentRevision = currentSnapshot.revision;\n if (currentSnapshot !== snapshot ||\n currentRevision !== capturedRevision ||\n currentRevision !== revision) {\n throw new Error(\"The row-model snapshot changed during atomic UI reconciliation.\");\n }\n if (disposed || activeProjectionToken !== token)\n return;\n observed = {\n snapshot,\n window: selectionWindow,\n windowed: windowing !== null,\n };\n committed = true;\n publish({\n ...state,\n focus,\n selection,\n editing,\n observedRowModelRevision: revision,\n });\n }\n catch (cause) {\n if (disposed || activeProjectionToken !== token)\n return;\n throw observationError(\"The row-model revision could not be observed atomically.\", cause);\n }\n finally {\n if (!committed)\n discardProjectionActions(token);\n if (activeProjectionToken === token) {\n activeProjectionToken = undefined;\n }\n projecting = false;\n drain();\n }\n });\n },\n dispose() {\n if (disposed)\n return;\n if (projecting && !notifying) {\n performDispose();\n return;\n }\n if (notifying || draining) {\n queuedActions.push({ action: performDispose });\n return;\n }\n performDispose();\n },\n };\n return grid;\n}\n","/** Id of the synthetic visual column that carries grouped row labels. @public */\nexport const GROUP_COLUMN_ID = \"__pretable_group__\";\n","import { createGridUiCore } from \"@pretable-internal/grid-core\";\nimport type {\n CreateGridUiCoreOptions,\n PretableGridUiCore,\n} from \"@pretable-internal/grid-core\";\nimport type { PretableRowId } from \"@pretable-internal/row-model\";\n\n/**\n * Create a framework-independent UI-state grid over an explicit indexed row\n * model. Data, queries, grouping, aggregation, and expansion remain owned by\n * `rowModel`; this handle owns only focus, selection, editing, viewport, and\n * visual column layout.\n *\n * @public\n */\nexport function createGrid<\n TRow extends object,\n TRowId extends PretableRowId,\n TColumns,\n>(\n options: CreateGridUiCoreOptions<TRow, TRowId, TColumns>,\n): PretableGridUiCore<TRow, TRowId, TColumns> {\n return createGridUiCore(options);\n}\n","/** @public */\nexport function createColumnHelper() {\n return {\n accessor(id, accessorOrOptions, maybeOptions) {\n const isFunctionAccessor = typeof accessorOrOptions === \"function\";\n const accessor = isFunctionAccessor\n ? accessorOrOptions\n : (row) => row[id];\n const options = isFunctionAccessor ? maybeOptions : accessorOrOptions;\n return {\n ...options,\n id,\n accessorKey: isFunctionAccessor\n ? undefined\n : id,\n accessor,\n value: accessor,\n };\n },\n };\n}\n/**\n * Narrows one filter-tree node to a group. Checked positively on the group's\n * own fields, so an unknown shape fails closed rather than being treated as a\n * branch with no children.\n * @public\n */\nexport function isPretableFilterGroup(node) {\n return (typeof node === \"object\" &&\n node !== null &&\n \"children\" in node &&\n (node.op === \"and\" ||\n node.op === \"or\"));\n}\n","export const MIN_DATE_VALUE = \"0000-01-01\";\nexport const MAX_DATE_VALUE = \"9999-12-31\";\nconst DATE_VALUE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst MS_PER_DAY = 86_400_000;\nconst DAYS_PER_GREGORIAN_CYCLE = 146_097;\nconst MAX_YEAR = 9_999;\nconst MONTHS_PER_YEAR = 12;\nconst MAX_MONTH_INDEX = MAX_YEAR * MONTHS_PER_YEAR + 11;\nconst ASCII_ZERO = 48;\nconst ASCII_NINE = 57;\nconst ASCII_HYPHEN = 45;\nconst isLeapYear = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\nconst getDaysInMonth = (year, month) => {\n if (month === 2)\n return isLeapYear(year) ? 29 : 28;\n if (month === 4 || month === 6 || month === 9 || month === 11)\n return 30;\n return 31;\n};\nconst isAsciiDigitAt = (value, index) => {\n const code = value.charCodeAt(index);\n return code >= ASCII_ZERO && code <= ASCII_NINE;\n};\nconst hasDateValueShape = (value) => value.length === 10 &&\n isAsciiDigitAt(value, 0) &&\n isAsciiDigitAt(value, 1) &&\n isAsciiDigitAt(value, 2) &&\n isAsciiDigitAt(value, 3) &&\n value.charCodeAt(4) === ASCII_HYPHEN &&\n isAsciiDigitAt(value, 5) &&\n isAsciiDigitAt(value, 6) &&\n value.charCodeAt(7) === ASCII_HYPHEN &&\n isAsciiDigitAt(value, 8) &&\n isAsciiDigitAt(value, 9);\nconst readTwoDigits = (value, offset) => (value.charCodeAt(offset) - ASCII_ZERO) * 10 +\n value.charCodeAt(offset + 1) -\n ASCII_ZERO;\nconst readFourDigits = (value) => (value.charCodeAt(0) - ASCII_ZERO) * 1_000 +\n (value.charCodeAt(1) - ASCII_ZERO) * 100 +\n (value.charCodeAt(2) - ASCII_ZERO) * 10 +\n value.charCodeAt(3) -\n ASCII_ZERO;\nconst hasValidDateParts = (year, month, day) => month >= 1 && month <= 12 && day >= 1 && day <= getDaysInMonth(year, month);\nconst formatDateValue = (year, month, day) => `${year.toString().padStart(4, \"0\")}-${month\n .toString()\n .padStart(2, \"0\")}-${day.toString().padStart(2, \"0\")}`;\nexport function parseDateValue(value) {\n if (typeof value !== \"string\")\n return null;\n const match = DATE_VALUE_PATTERN.exec(value);\n if (match === null)\n return null;\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n if (!hasValidDateParts(year, month, day))\n return null;\n return { year, month, day };\n}\n/** @public */\nexport function isValidDateValue(value) {\n if (typeof value !== \"string\" || !hasDateValueShape(value))\n return false;\n const year = readFourDigits(value);\n const month = readTwoDigits(value, 5);\n const day = readTwoDigits(value, 8);\n return hasValidDateParts(year, month, day);\n}\nexport function dateValueToUtcMs(value) {\n if (typeof value !== \"string\" || !hasDateValueShape(value)) {\n return Number.NaN;\n }\n const year = readFourDigits(value);\n const month = readTwoDigits(value, 5);\n const day = readTwoDigits(value, 8);\n if (!hasValidDateParts(year, month, day))\n return Number.NaN;\n if (year < 100) {\n return (Date.UTC(year + 400, month - 1, day) -\n DAYS_PER_GREGORIAN_CYCLE * MS_PER_DAY);\n }\n return Date.UTC(year, month - 1, day);\n}\nexport function compareDateValues(left, right) {\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n return 0;\n}\nexport function addDateValueDays(value, days) {\n const timestamp = dateValueToUtcMs(value);\n if (Number.isNaN(timestamp) || Number.isNaN(days))\n return value;\n const wholeDays = Math.trunc(days);\n const minimumTimestamp = dateValueToUtcMs(MIN_DATE_VALUE);\n const maximumTimestamp = dateValueToUtcMs(MAX_DATE_VALUE);\n const destinationTimestamp = timestamp + wholeDays * MS_PER_DAY;\n if (destinationTimestamp <= minimumTimestamp)\n return MIN_DATE_VALUE;\n if (destinationTimestamp >= maximumTimestamp)\n return MAX_DATE_VALUE;\n const destination = new Date(destinationTimestamp);\n return formatDateValue(destination.getUTCFullYear(), destination.getUTCMonth() + 1, destination.getUTCDate());\n}\nexport function addDateValueMonths(value, months) {\n const parsed = parseDateValue(value);\n if (parsed === null || Number.isNaN(months))\n return value;\n const destinationMonthIndex = parsed.year * MONTHS_PER_YEAR + parsed.month - 1 + Math.trunc(months);\n if (destinationMonthIndex < 0)\n return MIN_DATE_VALUE;\n if (destinationMonthIndex > MAX_MONTH_INDEX)\n return MAX_DATE_VALUE;\n const year = Math.floor(destinationMonthIndex / MONTHS_PER_YEAR);\n const month = (destinationMonthIndex % MONTHS_PER_YEAR) + 1;\n const day = Math.min(parsed.day, getDaysInMonth(year, month));\n return formatDateValue(year, month, day);\n}\n","import { isValidDateValue } from \"@pretable-internal/calendar-date\";\nfunction calendarDateExtremum(kind) {\n return Object.freeze({\n init: () => null,\n accumulate: (accumulator, value) => {\n if (!isValidDateValue(value))\n return accumulator;\n if (accumulator === null)\n return value;\n return kind === \"min\"\n ? value < accumulator\n ? value\n : accumulator\n : value > accumulator\n ? value\n : accumulator;\n },\n merge: (left, right) => {\n if (left === null)\n return right;\n if (right === null)\n return left;\n return kind === \"min\"\n ? left < right\n ? left\n : right\n : left > right\n ? left\n : right;\n },\n finalize: (accumulator) => accumulator,\n });\n}\nconst calendarDateMin = calendarDateExtremum(\"min\");\nconst calendarDateMax = calendarDateExtremum(\"max\");\nexport function lowerCalendarDateAggregate(columnType, aggregate) {\n if (columnType !== \"date\")\n return aggregate;\n if (aggregate === \"min\") {\n return calendarDateMin;\n }\n if (aggregate === \"max\") {\n return calendarDateMax;\n }\n return aggregate;\n}\nexport function isCalendarDateAggregate(aggregate) {\n return aggregate === calendarDateMin || aggregate === calendarDateMax;\n}\n","/** @public */\nexport class PretableRowModelError extends Error {\n name = \"PretableRowModelError\";\n code;\n operation;\n rowId;\n columnId;\n constructor(code, message, context) {\n super(message, { cause: context.cause });\n this.code = code;\n this.operation = context.operation;\n this.rowId = context.rowId;\n this.columnId = context.columnId;\n }\n}\n/** @public */\nexport class PretableDisposedModelError extends PretableRowModelError {\n name = \"PretableDisposedModelError\";\n constructor(operation) {\n super(\"disposed-model\", \"The row model has been disposed.\", { operation });\n }\n}\n/** @public */\nexport class PretableReentrantMutationError extends PretableRowModelError {\n activeOperation;\n name = \"PretableReentrantMutationError\";\n constructor(operation, activeOperation) {\n super(\"reentrant-mutation\", `Cannot run ${operation} while ${activeOperation} is preparing an atomic publication.`, { operation });\n this.activeOperation = activeOperation;\n }\n}\n/** Finds a nested guard failure through structured callback-error causes. */\nexport function findPretableReentrantMutationError(error) {\n const visited = new Set();\n let current = error;\n while (current !== null && typeof current === \"object\") {\n if (current instanceof PretableReentrantMutationError)\n return current;\n if (visited.has(current))\n return undefined;\n visited.add(current);\n current = \"cause\" in current ? current.cause : undefined;\n }\n return undefined;\n}\n/** @public */\nexport class PretableRowIdentityChangeError extends PretableRowModelError {\n nextRowId;\n name = \"PretableRowIdentityChangeError\";\n constructor(rowId, nextRowId, cause) {\n super(\"row-identity-change\", `An update for row ${String(rowId)} changed its configured identity.`, { operation: \"apply-transaction\", rowId, cause });\n this.nextRowId = nextRowId;\n }\n}\n/** @public */\nexport class PretableUnsupportedRowUpdateError extends PretableRowModelError {\n name = \"PretableUnsupportedRowUpdateError\";\n constructor(rowId, cause) {\n super(\"unsupported-row-update\", \"Partial updates require an ordinary object or null-prototype record; replace class and exotic rows with setRows instead.\", { operation: \"apply-transaction\", rowId, cause });\n }\n}\n/** @public */\nexport class PretableInvalidGroupKeyError extends PretableRowModelError {\n value;\n name = \"PretableInvalidGroupKeyError\";\n constructor(operation, rowId, columnId, value, cause = new TypeError(\"Group keys must be strings, numbers, bigints, booleans, null, or undefined.\")) {\n super(\"invalid-group-key\", `Column ${columnId} produced an unsupported group key.`, { operation, rowId, columnId, cause });\n this.value = value;\n }\n}\n/** Runtime complement to the wholly-assignable `PretableRowGroupFor` check. */\nexport function isPretableGroupKey(value) {\n if (value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\") {\n return true;\n }\n return false;\n}\n/** @public */\nexport class PretableTransitionCancelledError extends Error {\n transitionId;\n reason;\n name = \"PretableTransitionCancelledError\";\n constructor(transitionId, reason) {\n super(`Row-model transition ${transitionId} was ${reason}.`);\n this.transitionId = transitionId;\n this.reason = reason;\n }\n}\n","function isRuntimeFilterGroup(node) {\n return \"children\" in node;\n}\nfunction readDateTimestamp(value) {\n try {\n return Date.prototype.getTime.call(value);\n }\n catch {\n return undefined;\n }\n}\nexport function isPlainObject(value) {\n if (value === null || typeof value !== \"object\")\n return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\nexport function semanticValueEqual(left, right) {\n if (Object.is(left, right))\n return true;\n if (Array.isArray(left) && Array.isArray(right)) {\n return (left.length === right.length &&\n left.every((value, index) => semanticValueEqual(value, right[index])));\n }\n if (left instanceof Date && right instanceof Date) {\n return Object.is(readDateTimestamp(left), readDateTimestamp(right));\n }\n if (isPlainObject(left) && isPlainObject(right)) {\n const leftKeys = Object.keys(left).sort();\n const rightKeys = Object.keys(right).sort();\n return (leftKeys.length === rightKeys.length &&\n leftKeys.every((key, index) => key === rightKeys[index] && semanticValueEqual(left[key], right[key])));\n }\n return false;\n}\nexport function orderingEqual(left, right) {\n return (left.length === right.length &&\n left.every((entry, index) => entry.columnId === right[index]?.columnId &&\n (entry.direction ?? \"asc\") === (right[index]?.direction ?? \"asc\") &&\n (entry.nulls ?? \"last\") === (right[index]?.nulls ?? \"last\")));\n}\nfunction filterNodeEqual(left, right) {\n if (isRuntimeFilterGroup(left) || isRuntimeFilterGroup(right)) {\n return (isRuntimeFilterGroup(left) &&\n isRuntimeFilterGroup(right) &&\n left.op === right.op &&\n filterNodeListEqual(left.children, right.children));\n }\n return (left.columnId === right.columnId &&\n left.operator === right.operator &&\n semanticValueEqual(left.value, right.value));\n}\nexport function filterNodeListEqual(left, right) {\n if (left.length !== right.length)\n return false;\n const used = new Set();\n return left.every((filter) => {\n const index = right.findIndex((candidate, candidateIndex) => !used.has(candidateIndex) && filterNodeEqual(filter, candidate));\n if (index < 0)\n return false;\n used.add(index);\n return true;\n });\n}\nexport function queryEqual(left, right) {\n return (filterNodeListEqual(left.filters, right.filters) &&\n orderingEqual(left.sort, right.sort) &&\n orderingEqual(left.rowGroups, right.rowGroups));\n}\n/** @internal Shared semantic query identity for renderer authority decisions. */\nexport function ɵqueriesSemanticallyEqual(left, right) {\n return queryEqual(left, right);\n}\n","import { compareDateValues, isValidDateValue, } from \"@pretable-internal/calendar-date\";\nimport { lowerCalendarDateAggregate } from \"./calendar-date-aggregates\";\nimport { PretableRowModelError } from \"./errors\";\nimport { filterNodeListEqual, isPlainObject, orderingEqual, queryEqual, semanticValueEqual, } from \"./query-equality\";\nexport class CompiledQueryValidationError extends TypeError {\n detail;\n path;\n columnId;\n name = \"CompiledQueryValidationError\";\n code = \"invalid-query\";\n constructor(detail, path, columnId, options) {\n super(`Invalid compiled query at ${path}: ${detail}`, options);\n this.detail = detail;\n this.path = path;\n this.columnId = columnId;\n }\n}\nexport class CompiledQueryComparatorError extends PretableRowModelError {\n rowIds;\n name = \"CompiledQueryComparatorError\";\n groupValues;\n constructor(message, rowIds, context) {\n super(\"comparator-failed\", message, {\n operation: context.operation ?? \"set-query\",\n rowId: rowIds?.[0],\n columnId: context.columnId,\n cause: context.cause,\n });\n this.rowIds = rowIds;\n this.groupValues = context.groupValues;\n }\n}\n/**\n * The internal twin of `isPretableFilterGroup`, deliberately WEAKER: the\n * public guard re-checks `op` because it runs on whatever a caller hands it,\n * whereas capture has already rejected any node carrying `children` without a\n * valid `op`. Over a captured tree the presence of `children` is therefore\n * decisive on its own. Never call this on un-captured input.\n */\nfunction isRuntimeFilterGroup(node) {\n return \"children\" in node;\n}\n/**\n * The leaves of a filter tree, in depth-first order — the tree's COLUMN\n * DEPENDENCY set, flattened deliberately. Join operators are irrelevant here:\n * a column is read if any leaf anywhere in the tree mentions it, whatever\n * joins that leaf to its siblings. Evaluation does NOT go through this — see\n * `compileFilterNodes`.\n */\nfunction filterLeavesOf(nodes) {\n const leaves = [];\n const visit = (node) => {\n if (isRuntimeFilterGroup(node))\n node.children.forEach(visit);\n else\n leaves.push(node);\n };\n nodes.forEach(visit);\n return leaves;\n}\n/*\n * Its own const rather than the `FilterPredicate` twin a thousand lines down:\n * the two are structurally identical and tsc would accept either, but a\n * predicate answers about a VALUE and a matcher about a ROW, and borrowing\n * one for the other is a pun a reader has to unpick.\n */\nconst alwaysMatches = () => true;\n/**\n * Compiles a sibling list joined by `op` into a single matcher. Used for\n * groups and for the query's root list alike — the roots are an `and`, which\n * is exactly what a top-level filter list has always meant.\n *\n * The join loops are indexed rather than `every`/`some`, which is not a style\n * preference: a callback join allocates a closure per group PER ROW, on the\n * hottest loop in the package. Deliberately unquantified — two harnesses\n * measured the gap differently enough to disagree, and a figure pasted here\n * would rot where no reader could re-derive it. Measure it yourself on an\n * isolated verdict loop; a whole-model benchmark cannot resolve it.\n *\n * Both operators are written once here, so there is one implementation of\n * `and` and one of `or` whatever shape the tree has.\n */\nfunction compileFilterNodes(nodes, op, byId) {\n /*\n * An EMPTY list is TRUE under BOTH joins — it constrains nothing, so it\n * removes nothing. The branch is not decoration: the `or` loop below falls\n * through to `false` on no children, which would make a half-built `or`\n * group in a builder UI blank the grid the instant a user adds it and\n * before they fill it in.\n */\n if (nodes.length === 0)\n return alwaysMatches;\n const matchers = nodes.map((node) => {\n if (isRuntimeFilterGroup(node))\n return compileFilterNodes(node.children, node.op, byId);\n const { columnId } = node;\n const predicate = compileFilterPredicate(node, byId.get(columnId));\n return (valueOf) => predicate(valueOf(columnId));\n });\n if (op === \"and\")\n return (valueOf) => {\n for (let index = 0; index < matchers.length; index += 1)\n if (!matchers[index](valueOf))\n return false;\n return true;\n };\n return (valueOf) => {\n for (let index = 0; index < matchers.length; index += 1)\n if (matchers[index](valueOf))\n return true;\n return false;\n };\n}\nconst internals = Symbol(\"compiled-query-internals\");\nconst collator = new Intl.Collator(undefined, {\n numeric: true,\n sensitivity: \"base\",\n});\nexport const FILTER_OPERATORS = {\n text: new Set([\n \"contains\",\n \"notContains\",\n \"equals\",\n \"notEquals\",\n \"startsWith\",\n \"endsWith\",\n \"isEmpty\",\n \"isNotEmpty\",\n ]),\n number: new Set([\n \"equals\",\n \"notEquals\",\n \"gt\",\n \"gte\",\n \"lt\",\n \"lte\",\n \"between\",\n \"isEmpty\",\n \"isNotEmpty\",\n ]),\n date: new Set([\n \"on\",\n \"before\",\n \"after\",\n \"dateBetween\",\n \"isEmpty\",\n \"isNotEmpty\",\n ]),\n enum: new Set([\"isAnyOf\", \"isNoneOf\", \"isEmpty\", \"isNotEmpty\"]),\n boolean: new Set([\"isAnyOf\", \"isNoneOf\", \"isEmpty\", \"isNotEmpty\"]),\n};\nconst BUILTIN_AGGREGATES = new Set([\"sum\", \"avg\", \"min\", \"max\", \"count\"]);\nconst NUMBER_ONLY_AGGREGATES = new Set([\"sum\", \"avg\"]);\nconst EXTREMA_AGGREGATES = new Set([\"min\", \"max\"]);\nconst COLUMN_TYPES = new Set([\"text\", \"number\", \"date\", \"enum\", \"boolean\"]);\nfunction captureCompileInput(input) {\n const rawColumns = captureProperty(input, \"derivations\", \"input.derivations\");\n const rawQuery = captureProperty(input, \"query\", \"input.query\");\n const previous = captureProperty(input, \"previous\", \"input.previous\");\n const rawAuthority = captureProperty(input, \"filterAuthority\", \"input.filterAuthority\");\n const rawSortAuthority = captureProperty(input, \"sortAuthority\", \"input.sortAuthority\");\n if (rawQuery === null || typeof rawQuery !== \"object\")\n fail(\"query must be an object\", \"input.query\");\n if (rawAuthority !== undefined &&\n rawAuthority !== \"engine\" &&\n rawAuthority !== \"external\")\n fail('filterAuthority must be \"engine\" or \"external\"', \"input.filterAuthority\");\n if (rawSortAuthority !== undefined &&\n rawSortAuthority !== \"engine\" &&\n rawSortAuthority !== \"external\")\n fail('sortAuthority must be \"engine\" or \"external\"', \"input.sortAuthority\");\n return {\n columns: captureColumns(rawColumns),\n query: captureQuery(rawQuery),\n previous: previous,\n filterAuthority: (rawAuthority ?? \"engine\"),\n sortAuthority: (rawSortAuthority ?? \"engine\"),\n };\n}\nfunction captureColumns(rawColumns) {\n return captureDenseArray(rawColumns, \"derivations\", \"derivations must be an array\", (rawColumn, index) => {\n const path = `derivations[${index}]`;\n if (rawColumn === null || typeof rawColumn !== \"object\")\n fail(\"a derivation is not an object\", path);\n const id = captureProperty(rawColumn, \"id\", `${path}.id`);\n const columnId = typeof id === \"string\" ? id : undefined;\n const type = captureProperty(rawColumn, \"type\", `${path}.type`, columnId);\n const accessor = captureProperty(rawColumn, \"accessor\", `${path}.accessor`, columnId);\n const value = captureProperty(rawColumn, \"value\", `${path}.value`, columnId);\n const compare = captureProperty(rawColumn, \"compare\", `${path}.compare`, columnId);\n const rawAggregate = captureProperty(rawColumn, \"aggregate\", `${path}.aggregate`, columnId);\n const aggregate = rawAggregate !== null && typeof rawAggregate === \"object\"\n ? captureAggregator(rawAggregate, `${path}.aggregate`, columnId)\n : rawAggregate;\n return Object.freeze({\n id,\n type,\n accessor,\n value,\n compare,\n aggregate,\n });\n });\n}\nfunction captureAggregator(source, path, columnId) {\n let keys;\n try {\n keys = Object.keys(source);\n if (Object.getOwnPropertySymbols(source).length > 0)\n fail(\"symbol-keyed aggregate options are not supported\", path, columnId);\n }\n catch (cause) {\n if (cause instanceof CompiledQueryValidationError)\n throw cause;\n throw new CompiledQueryValidationError(\"aggregate property discovery threw while compiling\", path, columnId, { cause });\n }\n const required = [\"init\", \"accumulate\", \"merge\", \"finalize\"];\n const allKeys = [...new Set([...keys, ...required, \"snapshotAccumulator\"])];\n const clone = {};\n for (const key of allKeys) {\n const captured = captureProperty(source, key, `${path}.${key}`, columnId);\n clone[key] = required.includes(key)\n ? captured\n : cloneOwnedValue(captured, `${path}.${key}`, new WeakSet(), columnId);\n }\n return Object.freeze(clone);\n}\nfunction captureQuery(source) {\n const rawFilters = captureProperty(source, \"filters\", \"query.filters\");\n const rawSort = captureProperty(source, \"sort\", \"query.sort\");\n const rawRowGroups = captureProperty(source, \"rowGroups\", \"query.rowGroups\");\n return Object.freeze({\n filters: captureDenseArray(rawFilters, \"query.filters\", \"filters must be an array\", (entry, index) => captureFilterNode(entry, `query.filters[${index}]`)),\n sort: captureDenseArray(rawSort, \"query.sort\", \"sort must be an array\", (entry, index) => captureOrdering(entry, \"sort\", index)),\n rowGroups: captureDenseArray(rawRowGroups, \"query.rowGroups\", \"rowGroups must be an array\", (entry, index) => captureOrdering(entry, \"rowGroups\", index)),\n });\n}\nfunction captureDenseArray(source, path, notArrayDetail, captureEntry) {\n let isArray;\n try {\n isArray = Array.isArray(source);\n }\n catch (cause) {\n throw new CompiledQueryValidationError(\"array brand check threw while compiling\", path, undefined, { cause });\n }\n if (!isArray)\n fail(notArrayDetail, path);\n const array = source;\n const length = captureProperty(array, \"length\", `${path}.length`);\n if (typeof length !== \"number\" ||\n !Number.isInteger(length) ||\n length < 0 ||\n length > 0xffff_ffff) {\n fail(\"array length is invalid\", `${path}.length`);\n }\n const captured = [];\n for (let index = 0; index < length; index += 1) {\n const entryPath = `${path}[${index}]`;\n let hasOwnIndex;\n try {\n hasOwnIndex = Object.prototype.hasOwnProperty.call(array, index);\n }\n catch (cause) {\n throw new CompiledQueryValidationError(\"array index presence check threw while compiling\", entryPath, undefined, { cause });\n }\n if (!hasOwnIndex)\n fail(\"array index is missing\", entryPath);\n const entry = captureProperty(array, index, entryPath);\n captured.push(captureEntry(entry, index));\n }\n return Object.freeze(captured);\n}\n/*\n * The deepest a captured filter tree may nest, counting root nodes as depth 0.\n *\n * Capture is the chokepoint: validation, snapshotting, descriptor keys, leaf\n * collection, structural equality and per-row evaluation all recurse over a\n * tree only AFTER it has been captured, so bounding it here bounds every one\n * of them at once. Without the bound the failure mode was not merely a deep\n * tree — measured against this file's pre-bound revision, a 1000-level tree\n * CAPTURED cleanly and then overflowed the stack in `filterNodeListEqual` on\n * the next recompile, so the `RangeError` surfaced from a later `setQuery` on\n * a plan the engine had already accepted; at 2000 `compileQuery` threw a raw\n * `RangeError` instead of this module's validation error.\n *\n * 64 is chosen as far beyond any tree a human or a builder UI produces (real\n * filter trees nest a handful of levels) while sitting an order of magnitude\n * below the depth at which any of the downstream recursions is at risk.\n */\nconst MAX_FILTER_TREE_DEPTH = 64;\n/**\n * One node of the filter tree. A node carrying `children` is a group and is\n * captured recursively, breadcrumbed as `<path>.children[i]`; anything else is\n * captured as a leaf. Every level is frozen on the way out, so the captured\n * tree is owned by the plan rather than aliasing the caller's objects.\n *\n * `depth` is the node's own nesting level and is bounded — see\n * `MAX_FILTER_TREE_DEPTH` for why the bound lives here and nowhere else.\n */\nfunction captureFilterNode(raw, path, depth = 0) {\n if (depth > MAX_FILTER_TREE_DEPTH)\n fail(`filter group nesting exceeds ${MAX_FILTER_TREE_DEPTH} levels`, path);\n if (raw === null || typeof raw !== \"object\")\n fail(\"filter entry is not an object\", path);\n const children = captureProperty(raw, \"children\", `${path}.children`);\n if (children === undefined)\n return captureFilter(raw, path);\n const op = captureProperty(raw, \"op\", `${path}.op`);\n if (op !== \"and\" && op !== \"or\")\n fail(\"filter group must join with and or or\", `${path}.op`);\n return Object.freeze({\n op,\n children: captureDenseArray(children, `${path}.children`, \"filter group children must be an array\", (entry, index) => captureFilterNode(entry, `${path}.children[${index}]`, depth + 1)),\n });\n}\nfunction captureFilter(raw, path) {\n const columnId = captureProperty(raw, \"columnId\", `${path}.columnId`);\n const contextId = typeof columnId === \"string\" ? columnId : undefined;\n const operator = captureProperty(raw, \"operator\", `${path}.operator`, contextId);\n const value = captureProperty(raw, \"value\", `${path}.value`, contextId);\n return Object.freeze({\n columnId,\n operator,\n value: cloneOwnedValue(value, `${path}.value`, new WeakSet(), contextId),\n });\n}\nfunction captureOrdering(raw, area, index) {\n const path = `query.${area}[${index}]`;\n if (raw === null || typeof raw !== \"object\")\n fail(`${area} entry is not an object`, path);\n const columnId = captureProperty(raw, \"columnId\", `${path}.columnId`);\n const contextId = typeof columnId === \"string\" ? columnId : undefined;\n const direction = captureProperty(raw, \"direction\", `${path}.direction`, contextId);\n const nulls = captureProperty(raw, \"nulls\", `${path}.nulls`, contextId);\n return Object.freeze({\n columnId,\n direction,\n nulls,\n });\n}\nfunction fail(message, path = \"query\", columnId) {\n throw new CompiledQueryValidationError(message, path, columnId);\n}\nfunction captureProperty(source, property, path, columnId) {\n try {\n return Reflect.get(source, property);\n }\n catch (cause) {\n throw new CompiledQueryValidationError(\"property getter threw while compiling\", path, columnId, { cause });\n }\n}\nfunction validateDerivations(columns) {\n const ids = new Set();\n for (let index = 0; index < columns.length; index += 1) {\n const column = columns[index];\n const path = `derivations[${index}]`;\n if (!column || typeof column !== \"object\")\n fail(\"a derivation is not an object\", path);\n if (typeof column.id !== \"string\" || column.id.length === 0)\n fail(\"a derivation has no column ID\", `${path}.id`);\n if (ids.has(column.id))\n fail(`duplicate derivation column ID ${column.id}`, `${path}.id`, column.id);\n ids.add(column.id);\n if (!COLUMN_TYPES.has(column.type))\n fail(`column has invalid type ${column.type}`, `${path}.type`, column.id);\n if (typeof column.accessor !== \"function\" ||\n typeof column.value !== \"function\") {\n fail(\"column has no accessor\", `${path}.accessor`, column.id);\n }\n if (column.compare !== undefined && typeof column.compare !== \"function\") {\n fail(\"column has an invalid comparator\", `${path}.compare`, column.id);\n }\n validateAggregate(column, `${path}.aggregate`);\n }\n}\nfunction validateAggregate(column, path) {\n const aggregate = column.aggregate;\n if (aggregate === undefined)\n return;\n if (typeof aggregate === \"string\") {\n if (!BUILTIN_AGGREGATES.has(aggregate))\n fail(`unknown aggregate ${aggregate}`, path, column.id);\n if (NUMBER_ONLY_AGGREGATES.has(aggregate) && column.type !== \"number\") {\n fail(`numeric aggregate ${aggregate} requires a number column`, path, column.id);\n }\n if (EXTREMA_AGGREGATES.has(aggregate) &&\n column.type !== \"number\" &&\n column.type !== \"date\") {\n fail(`aggregate ${aggregate} requires a number or date column`, path, column.id);\n }\n return;\n }\n if (!aggregate || typeof aggregate !== \"object\")\n fail(\"aggregate must be a built-in name or object\", path, column.id);\n for (const operation of [\n \"init\",\n \"accumulate\",\n \"merge\",\n \"finalize\",\n ]) {\n if (typeof aggregate[operation] !== \"function\")\n fail(`aggregate has no ${operation}`, `${path}.${operation}`, column.id);\n }\n if (aggregate.snapshotAccumulator !== undefined &&\n typeof aggregate.snapshotAccumulator !== \"function\") {\n fail(\"aggregate has an invalid snapshotAccumulator\", `${path}.snapshotAccumulator`, column.id);\n }\n}\nfunction resolveColumn(columns, columnId, area) {\n const column = columns.get(columnId);\n if (!column)\n fail(`references unknown column ${columnId}`, area, columnId);\n return column;\n}\nfunction validateOrdering(entry, columns, area, index) {\n const path = `query.${area}[${index}]`;\n if (!entry || typeof entry !== \"object\")\n fail(`${area} entry is not an object`, path);\n resolveColumn(columns, entry.columnId, `${path}.columnId`);\n const direction = entry.direction ?? \"asc\";\n if (direction !== \"asc\" && direction !== \"desc\")\n fail(`invalid direction ${direction}`, `${path}.direction`, entry.columnId);\n if (entry.nulls !== undefined &&\n entry.nulls !== \"first\" &&\n entry.nulls !== \"last\") {\n fail(`invalid null placement ${entry.nulls}`, `${path}.nulls`, entry.columnId);\n }\n}\nfunction validateFilterNode(node, columns, path) {\n if (isRuntimeFilterGroup(node)) {\n node.children.forEach((child, index) => validateFilterNode(child, columns, `${path}.children[${index}]`));\n return;\n }\n validateFilter(node, columns, path);\n}\nfunction validateFilter(filter, columns, path) {\n if (!filter || typeof filter !== \"object\")\n fail(\"filter entry is not an object\", path);\n const column = resolveColumn(columns, filter.columnId, `${path}.columnId`);\n const operators = FILTER_OPERATORS[column.type];\n if (!operators?.has(filter.operator))\n fail(`column cannot use operator ${filter.operator}`, `${path}.operator`, filter.columnId);\n if (filter.operator === \"isEmpty\" || filter.operator === \"isNotEmpty\")\n return;\n if (filter.value === undefined || filter.value === null)\n fail(\"filter is missing its operand\", `${path}.value`, filter.columnId);\n validateFilterOperand(column, filter, `${path}.value`);\n}\nfunction validateFilterOperand(column, filter, path) {\n const value = filter.value;\n if (column.type === \"number\") {\n const values = filter.operator === \"between\" ? value : [value];\n if (!Array.isArray(values) ||\n (filter.operator === \"between\" && values.length !== 2) ||\n values.some((entry) => typeof entry !== \"number\" || Number.isNaN(entry))) {\n fail(filter.operator === \"between\"\n ? \"number range must contain exactly two non-NaN numbers\"\n : \"number operand must be a non-NaN number\", path, column.id);\n }\n return;\n }\n if (column.type === \"date\") {\n if (filter.operator === \"dateBetween\") {\n if (!Array.isArray(value) ||\n value.length !== 2 ||\n value.some((entry) => typeof entry !== \"string\")) {\n fail(\"date range must contain exactly two strings\", path, column.id);\n }\n }\n else if (typeof value !== \"string\") {\n fail(\"date operand must be a string\", path, column.id);\n }\n return;\n }\n if (column.type === \"text\") {\n if (typeof value !== \"string\")\n fail(\"text operand must be a string\", path, column.id);\n return;\n }\n if (!Array.isArray(value))\n fail(\"selection operand must be an array\", path, column.id);\n if (column.type === \"boolean\") {\n // A boolean column's operand must match what `booleanValue()` treats as\n // one of the two states AND what the docs promise the funnel can send:\n // real booleans, or the string literals \"true\"/\"false\" (the only values\n // a column's `options` are allowed to relabel to, per\n // content/docs/grid/filtering.mdx). Deliberately excludes 1/0/\"1\"/\"0\" —\n // `booleanValue()` also coerces those, but the docs never promise them,\n // so accepting them here would be validator-only drift ahead of the\n // documented contract instead of behind it.\n if (value.some((entry) => typeof entry !== \"boolean\" && entry !== \"true\" && entry !== \"false\")) {\n fail('boolean selection must contain only boolean values or the strings \"true\"/\"false\"', path, column.id);\n }\n return;\n }\n if (value.some((entry) => typeof entry !== \"string\")) {\n fail(`${column.type} selection must contain only string values`, path, column.id);\n }\n}\nfunction validateQuery(query, columns) {\n if (!query || typeof query !== \"object\")\n fail(\"query is not an object\");\n if (!Array.isArray(query.filters) ||\n !Array.isArray(query.sort) ||\n !Array.isArray(query.rowGroups)) {\n fail(\"filters, sort, and rowGroups must be arrays\");\n }\n const byId = new Map(columns.map((column) => [column.id, column]));\n query.filters.forEach((node, index) => validateFilterNode(node, byId, `query.filters[${index}]`));\n query.sort.forEach((entry, index) => validateOrdering(entry, byId, \"sort\", index));\n query.rowGroups.forEach((entry, index) => validateOrdering(entry, byId, \"rowGroups\", index));\n}\n/*\n * Nodes are matched STRUCTURALLY, never by a serialized key: the descriptor\n * key is raw concatenation over unframed user operands, so a filter value can\n * forge the separators and impersonate a sibling — harmless for the ordering\n * job the key exists for, a wrong-results bug as an identity test (the plan\n * would be reused and the incoming query silently discarded).\n *\n * Groups match when their join operators match and their children match as an\n * unordered multiset, recursively — the same used-set shape the node list one\n * level up uses, for the same reason: both joins are commutative.\n */\n/*\n * `filterLeaves` is the caller's own `#filterLeaves`, passed rather than\n * re-derived: this runs on every recompile check (`semanticallyMatches`, so\n * every `setQuery`), and walking the tree here would allocate a fresh leaf\n * array per call for a set the plan already holds.\n */\nfunction derivationsEqualForPlan(left, right, query, filterLeaves) {\n if (left.length !== right.length)\n return false;\n const accessorIds = new Set();\n const comparatorIds = new Set();\n filterLeaves.forEach((entry) => accessorIds.add(entry.columnId));\n query.sort.forEach((entry) => {\n accessorIds.add(entry.columnId);\n comparatorIds.add(entry.columnId);\n });\n query.rowGroups.forEach((entry) => {\n accessorIds.add(entry.columnId);\n comparatorIds.add(entry.columnId);\n });\n return left.every((column, index) => {\n const other = right[index];\n if (column.id !== other.id || column.type !== other.type)\n return false;\n if (!semanticValueEqual(column.aggregate, other.aggregate))\n return false;\n if (column.aggregate !== undefined)\n accessorIds.add(column.id);\n if (accessorIds.has(column.id) && column.accessor !== other.accessor)\n return false;\n if (comparatorIds.has(column.id) && column.compare !== other.compare)\n return false;\n return true;\n });\n}\nfunction cloneOwnedValue(value, path, seen, columnId) {\n if (value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"bigint\" ||\n typeof value === \"function\") {\n return value;\n }\n if (typeof value === \"symbol\")\n fail(\"symbols are not supported in compiled inputs\", path, columnId);\n let dateLike;\n try {\n dateLike = value instanceof Date;\n }\n catch (cause) {\n throw new CompiledQueryValidationError(\"value brand check threw while compiling\", path, columnId, { cause });\n }\n if (dateLike) {\n const timestamp = readDateTimestamp(value);\n if (timestamp === undefined)\n fail(\"value has an invalid Date brand\", path, columnId);\n return Object.freeze(new Date(timestamp));\n }\n if (typeof value !== \"object\")\n fail(\"unsupported compiled input value\", path, columnId);\n if (seen.has(value))\n fail(\"cyclic values are not supported\", path, columnId);\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n const captured = [];\n for (let index = 0; index < value.length; index += 1) {\n captured.push(cloneOwnedValue(captureProperty(value, index, `${path}[${index}]`, columnId), `${path}[${index}]`, seen, columnId));\n }\n return Object.freeze(captured);\n }\n if (!isPlainObject(value)) {\n fail(\"only Date, arrays, and plain objects are supported in compiled inputs\", path, columnId);\n }\n const clone = {};\n for (const key of Object.keys(value)) {\n clone[key] = cloneOwnedValue(captureProperty(value, key, `${path}.${key}`, columnId), `${path}.${key}`, seen, columnId);\n }\n return Object.freeze(clone);\n }\n finally {\n seen.delete(value);\n }\n}\nfunction readDateTimestamp(value) {\n try {\n return Date.prototype.getTime.call(value);\n }\n catch {\n return undefined;\n }\n}\nfunction snapshotColumns(columns, path) {\n return Object.freeze(columns.map((column, index) => {\n const aggregate = column.aggregate === undefined || typeof column.aggregate === \"string\"\n ? column.aggregate\n : snapshotAggregator(column.aggregate, `${path}[${index}].aggregate`, column.id);\n return Object.freeze({ ...column, aggregate });\n }));\n}\nfunction snapshotAggregator(aggregator, path, columnId) {\n const source = aggregator;\n const clone = {};\n const callbacks = new Set([\n \"init\",\n \"accumulate\",\n \"merge\",\n \"snapshotAccumulator\",\n \"finalize\",\n ]);\n try {\n if (Object.getOwnPropertySymbols(aggregator).length > 0) {\n fail(\"symbol-keyed aggregate options are not supported\", path, columnId);\n }\n for (const key of Object.keys(aggregator)) {\n if (!callbacks.has(key)) {\n clone[key] = cloneOwnedValue(source[key], `${path}.${key}`, new WeakSet());\n }\n }\n }\n catch (error) {\n if (error instanceof CompiledQueryValidationError &&\n error.columnId === undefined) {\n throw new CompiledQueryValidationError(error.detail, error.path, columnId);\n }\n throw error;\n }\n clone.init = aggregator.init;\n clone.accumulate = aggregator.accumulate;\n clone.merge = aggregator.merge;\n clone.snapshotAccumulator = aggregator.snapshotAccumulator;\n clone.finalize = aggregator.finalize;\n return Object.freeze(clone);\n}\nfunction snapshotQuery(query, path, canonicalFilters = false) {\n const snapshotNode = (node, nodePath) => isRuntimeFilterGroup(node)\n ? Object.freeze({\n op: node.op,\n children: Object.freeze(node.children.map((child, index) => snapshotNode(child, `${nodePath}.children[${index}]`))),\n })\n : Object.freeze({\n ...node,\n value: cloneOwnedValue(node.value, `${nodePath}.value`, new WeakSet()),\n });\n const filters = query.filters.map((node, index) => snapshotNode(node, `${path}.filters[${index}]`));\n if (canonicalFilters)\n filters.sort(compareFilterDescriptors);\n return Object.freeze({\n filters: Object.freeze(filters),\n sort: Object.freeze(query.sort.map((entry) => Object.freeze({ ...entry }))),\n rowGroups: Object.freeze(query.rowGroups.map((entry) => Object.freeze({ ...entry }))),\n });\n}\nconst EMPTY_FILTERS = Object.freeze([]);\nconst EMPTY_SORT = Object.freeze([]);\n/**\n * The query the plan APPLIES, as opposed to the one it reports. Filters are\n * sorted into a canonical order so plan identity survives a reordered filter\n * list — and dropped outright under external filter authority, which is the\n * single point where \"the caller already selected these records\" takes effect.\n *\n * Sort is the same idea one axis over: dropped under external sort authority,\n * which is where \"the caller already ranked these records\" takes effect. Note\n * that only `query.sort` goes — `rowGroups` keeps its own ordering, because\n * grouping is not in `PretableProcessingOptions` and a consumer who declared\n * external sort authority said nothing about it.\n */\nfunction canonicalRuntimeQuery(query, filterAuthority, sortAuthority) {\n return Object.freeze({\n filters: filterAuthority === \"external\"\n ? EMPTY_FILTERS\n : Object.freeze([...query.filters].sort(compareFilterDescriptors)),\n sort: sortAuthority === \"external\" ? EMPTY_SORT : query.sort,\n rowGroups: query.rowGroups,\n });\n}\nfunction compareFilterDescriptors(left, right) {\n return filterDescriptorKey(left).localeCompare(filterDescriptorKey(right));\n}\nfunction filterDescriptorKey(node) {\n if (isRuntimeFilterGroup(node)) {\n // Children are keyed then sorted for the same reason the roots are\n // sorted in `canonicalRuntimeQuery`: both joins are commutative, so a\n // reordered group is the same question and must reuse the same plan.\n return `group\\u0000${node.op}\\u0000[${node.children\n .map(filterDescriptorKey)\n .sort()\n .join(\"\\u0001\")}]`;\n }\n return `${node.columnId}\\u0000${node.operator}\\u0000${filterValueKey(node.value)}`;\n}\nfunction filterValueKey(value) {\n if (value instanceof Date)\n return `date:${String(readDateTimestamp(value))}`;\n if (Array.isArray(value))\n return `array:[${value.map(filterValueKey).join(\",\")}]`;\n if (typeof value === \"number\") {\n if (Object.is(value, -0))\n return \"number:-0\";\n return `number:${String(value)}`;\n }\n return `${typeof value}:${String(value)}`;\n}\nfunction isEmptyValue(value) {\n return (value === null ||\n value === undefined ||\n (typeof value === \"number\" && Number.isNaN(value)) ||\n (typeof value === \"string\" && value.trim() === \"\"));\n}\nfunction booleanValue(value) {\n if (typeof value === \"boolean\")\n return value;\n if (value === \"true\" || value === 1 || value === \"1\")\n return true;\n if (value === \"false\" || value === 0 || value === \"0\")\n return false;\n return Boolean(value);\n}\nconst alwaysTrue = () => true;\nconst alwaysFalse = () => false;\nfunction isNumberCell(value) {\n return typeof value === \"number\" && !Number.isNaN(value);\n}\nfunction textCell(value) {\n return String(value ?? \"\").toLocaleLowerCase();\n}\nfunction compileNumberPredicate(operator, operand) {\n if (operator === \"between\") {\n const range = operand;\n const a = range[0];\n const b = range[1];\n if (typeof a !== \"number\" || typeof b !== \"number\")\n return alwaysFalse;\n const lower = Math.min(a, b);\n const upper = Math.max(a, b);\n return (value) => isNumberCell(value) && value >= lower && value <= upper;\n }\n if (typeof operand !== \"number\" || Number.isNaN(operand))\n return alwaysFalse;\n switch (operator) {\n case \"equals\":\n return (value) => isNumberCell(value) && value === operand;\n case \"notEquals\":\n return (value) => isNumberCell(value) && value !== operand;\n case \"gt\":\n return (value) => isNumberCell(value) && value > operand;\n case \"gte\":\n return (value) => isNumberCell(value) && value >= operand;\n case \"lt\":\n return (value) => isNumberCell(value) && value < operand;\n default:\n return (value) => isNumberCell(value) && value <= operand;\n }\n}\nfunction compileDatePredicate(operator, operand) {\n if (operator === \"dateBetween\") {\n const range = operand;\n const a = range[0];\n const b = range[1];\n if (!isValidDateValue(a) || !isValidDateValue(b))\n return alwaysFalse;\n const [lower, upper] = compareDateValues(a, b) <= 0 ? [a, b] : [b, a];\n return (value) => isValidDateValue(value) &&\n compareDateValues(value, lower) >= 0 &&\n compareDateValues(value, upper) <= 0;\n }\n if (!isValidDateValue(operand))\n return alwaysFalse;\n if (operator === \"on\")\n return (value) => isValidDateValue(value) && compareDateValues(value, operand) === 0;\n if (operator === \"before\")\n return (value) => isValidDateValue(value) && compareDateValues(value, operand) < 0;\n return (value) => isValidDateValue(value) && compareDateValues(value, operand) > 0;\n}\nfunction compileSelectionPredicate(operator, operand, coerce) {\n const entries = operand;\n // An empty selection matches EVERYTHING, regardless of direction.\n if (entries.length === 0)\n return alwaysTrue;\n const included = new Set(entries.map((entry) => coerce(entry)));\n return operator === \"isAnyOf\"\n ? (value) => included.has(coerce(value))\n : (value) => !included.has(coerce(value));\n}\nfunction compileTextPredicate(operator, operand) {\n const search = String(operand).toLocaleLowerCase();\n switch (operator) {\n case \"contains\":\n return (value) => textCell(value).includes(search);\n case \"notContains\":\n return (value) => !textCell(value).includes(search);\n case \"equals\":\n return (value) => textCell(value) === search;\n case \"notEquals\":\n return (value) => textCell(value) !== search;\n case \"startsWith\":\n return (value) => textCell(value).startsWith(search);\n default:\n return (value) => textCell(value).endsWith(search);\n }\n}\n/**\n * The ONE home of filter-predicate semantics: resolves a validated runtime\n * filter's column type + operator into a monomorphic `(value) => boolean`\n * closure with operand normalization hoisted out of the row loop (between\n * bounds destructured and min/maxed once, date operands collapsed to UTC\n * day-ms once, text needles lowercased once, selection operands coerced into\n * a Set once). Called once per filter at plan construction; filters reaching\n * a plan have passed `validateFilter`, so the defensive `alwaysFalse` arms\n * for malformed operands are unreachable there and exist only to preserve the\n * legacy per-row semantics for direct callers. Predicates only ever read the\n * CELL value — a throwing accessor throws at the value source\n * (`#readColumnValue`), never here.\n */\nexport function compileFilterPredicate(filter, column) {\n if (filter.operator === \"isEmpty\")\n return isEmptyValue;\n if (filter.operator === \"isNotEmpty\")\n return (value) => !isEmptyValue(value);\n const operand = filter.value;\n switch (column.type) {\n case \"number\":\n return compileNumberPredicate(filter.operator, operand);\n case \"date\":\n return compileDatePredicate(filter.operator, operand);\n case \"enum\":\n return compileSelectionPredicate(filter.operator, operand, String);\n case \"boolean\":\n return compileSelectionPredicate(filter.operator, operand, booleanValue);\n default:\n return compileTextPredicate(filter.operator, operand);\n }\n}\nfunction isNullSortValue(value) {\n return (value === null ||\n value === undefined ||\n (typeof value === \"number\" && Number.isNaN(value)));\n}\nfunction compareValues(left, right, column, ordering) {\n if (!column.compare && column.type === \"date\") {\n const leftValid = isValidDateValue(left);\n const rightValid = isValidDateValue(right);\n if (leftValid || rightValid) {\n if (!leftValid)\n return 1;\n if (!rightValid)\n return -1;\n const result = compareDateValues(left, right);\n return ordering.direction === \"desc\" ? -result : result;\n }\n return 0;\n }\n const leftNull = isNullSortValue(left);\n const rightNull = isNullSortValue(right);\n if (leftNull || rightNull) {\n if (leftNull && rightNull)\n return 0;\n const nullResult = ordering.nulls === \"first\" ? -1 : 1;\n return leftNull ? nullResult : -nullResult;\n }\n let result;\n if (column.compare) {\n const customResult = column.compare(left, right);\n if (typeof customResult !== \"number\" || Number.isNaN(customResult)) {\n throw new TypeError(\"Custom comparators must return a number other than NaN.\");\n }\n result = customResult;\n }\n else if (column.type === \"number\" &&\n typeof left === \"number\" &&\n typeof right === \"number\") {\n result = left === right ? 0 : left < right ? -1 : 1;\n }\n else {\n result = collator.compare(String(left), String(right));\n }\n return ordering.direction === \"desc\" ? -result : result;\n}\nclass CompiledQueryPlan {\n activeColumnIds;\n #publicColumns;\n #publicQuery;\n #runtimeColumns;\n #runtimeQuery;\n #byId;\n /*\n * The LEAVES of `#runtimeQuery.filters`, depth-first — not the filter list\n * itself, which under a tree holds groups and has a different length. This\n * is a DEPENDENCY set (which columns the filters read), never the evaluation\n * order: joins are honoured by `#compiledFilterTree`.\n */\n #filterLeaves;\n /*\n * The whole filter tree as ONE closure, built at construction so no verdict\n * re-normalizes an operand, re-resolves a column, or reads a join per row.\n *\n * Built the same way for EVERY query, grouped or flat. A flat query briefly\n * had a second, separate predicate array and loop of its own; that bought a\n * real cost (a grouped query compiled every leaf predicate twice) and the\n * standing risk of two implementations of one semantics drifting apart,\n * catchable only after the fact. It bought no speed either: the flat loop\n * it saved allocated a closure per row of its own, so the single path is\n * measurably the FASTER of the two on an isolated verdict loop.\n */\n #compiledFilterTree;\n #active;\n #aggregateColumns;\n #operation;\n #filterAuthority;\n #sortAuthority;\n // Not `readonly`: `adoptEvaluationCache` repoints it at a previous plan's\n // map (by reference — no copy, no per-row work) on a filter-only change.\n #evaluationCache = new WeakMap();\n /*\n * The recompile cache compares against the PUBLIC query, not the runtime\n * one: under external authority the runtime query has no filters at all, so\n * comparing it would declare every filtered query a mismatch and rebuild on\n * every `setQuery`. Authority joins the comparison in its own right — it is\n * a render-time read on the React surface, never a memo dependency, so a\n * consumer really can flip it while a plan is alive, and reusing that plan\n * would leave suppression latched at whatever it was on the first compile.\n */\n [internals] = {\n semanticallyMatches: (derivations, query, filterAuthority, sortAuthority) => this.#filterAuthority === filterAuthority &&\n this.#sortAuthority === sortAuthority &&\n derivationsEqualForPlan(this.#runtimeColumns, derivations, this.#runtimeQuery, this.#filterLeaves) &&\n queryEqual(this.#publicQuery, query),\n };\n get derivations() {\n return snapshotColumns(this.#publicColumns, \"derivations\");\n }\n get query() {\n return snapshotQuery(this.#publicQuery, \"query\");\n }\n constructor(capturedColumns, capturedQuery, operation, filterAuthority, sortAuthority) {\n this.#publicColumns = capturedColumns;\n this.#publicQuery = capturedQuery;\n this.#runtimeColumns = capturedColumns;\n this.#filterAuthority = filterAuthority;\n this.#sortAuthority = sortAuthority;\n this.#runtimeQuery = canonicalRuntimeQuery(capturedQuery, filterAuthority, sortAuthority);\n this.#operation = operation;\n this.#byId = new Map(this.#runtimeColumns.map((column) => [column.id, column]));\n this.#filterLeaves = filterLeavesOf(this.#runtimeQuery.filters);\n this.#compiledFilterTree = compileFilterNodes(this.#runtimeQuery.filters, \"and\", this.#byId);\n const activeIds = new Set();\n this.#filterLeaves.forEach((entry) => activeIds.add(entry.columnId));\n this.#runtimeQuery.rowGroups.forEach((entry) => activeIds.add(entry.columnId));\n this.#runtimeQuery.sort.forEach((entry) => activeIds.add(entry.columnId));\n this.#aggregateColumns = this.#runtimeColumns.filter((column) => column.aggregate !== undefined);\n this.#aggregateColumns.forEach((column) => activeIds.add(column.id));\n this.#active = this.#runtimeColumns.filter((column) => activeIds.has(column.id));\n this.activeColumnIds = Object.freeze(this.#active.map((column) => column.id));\n }\n evaluate(input) {\n const cached = this.#evaluationCache.get(input.row);\n if (cached &&\n cached.metadata !== undefined &&\n Object.is(cached.rowId, input.rowId) &&\n cached.sourceOrder === input.sourceOrder) {\n return cached.metadata;\n }\n const values = new Map();\n for (const column of this.#active) {\n values.set(column.id, this.#readColumnValue(column, input.row, input.rowId));\n }\n const filterPasses = this.#filterVerdict((columnId) => values.get(columnId));\n const groupPath = Object.freeze(this.#runtimeQuery.rowGroups.map((entry) => Object.freeze({\n columnId: entry.columnId,\n value: values.get(entry.columnId),\n })));\n return this.#finalizeMetadata({\n rowId: input.rowId,\n row: input.row,\n sourceOrder: input.sourceOrder,\n filterPasses,\n groupPath,\n valueOf: (columnId) => values.get(columnId),\n });\n }\n /*\n * Tail of `evaluate`: writes the row's sort keys to the plan's store,\n * builds the dependency, aggregate leaves, and the frozen metadata from a\n * per-column value source, then seeds the evaluation cache. `valueOf` must\n * cover every sorted and aggregated column of THIS plan.\n *\n * `filterPasses` reaches the cache entry and nothing else: the metadata it\n * builds carries no verdict, because a verdict lives in the structure the\n * row lands in, not on the row.\n */\n #finalizeMetadata(input) {\n const sortKeys = Object.freeze(this.#runtimeQuery.sort.map((entry) => Object.freeze({\n columnId: entry.columnId,\n value: input.valueOf(entry.columnId),\n })));\n const dependency = Object.freeze({\n sourceOrder: input.sourceOrder,\n sortKeys,\n });\n const aggregateLeaves = Object.freeze(this.#aggregateColumns.map((column) => Object.freeze({\n columnId: column.id,\n aggregate: lowerCalendarDateAggregate(column.type, column.aggregate),\n allLeaf: Object.freeze({\n id: input.rowId,\n row: input.row,\n value: input.valueOf(column.id),\n dependency,\n }),\n })));\n const metadata = Object.freeze({\n rowId: input.rowId,\n row: input.row,\n sourceOrder: input.sourceOrder,\n groupPath: input.groupPath,\n aggregateLeaves,\n });\n const existing = this.#evaluationCache.get(input.row);\n if (existing === undefined) {\n this.#evaluationCache.set(input.row, {\n rowId: input.rowId,\n sourceOrder: input.sourceOrder,\n metadata,\n filterPasses: input.filterPasses,\n verdictPlan: this,\n sortKeys,\n });\n }\n else {\n // Upgrade a keys-only entry (or refresh a stale full one) in place —\n // no second WeakMap.set, so no second rehash risk.\n existing.rowId = input.rowId;\n existing.sourceOrder = input.sourceOrder;\n existing.metadata = metadata;\n existing.filterPasses = input.filterPasses;\n existing.verdictPlan = this;\n existing.sortKeys = sortKeys;\n }\n return metadata;\n }\n /*\n * The one accessor-read site: every column value this plan reads for\n * evaluation flows through here so the accessor-failed error shape cannot\n * fork between `evaluate` and the verdict-only path.\n */\n #readColumnValue(column, row, rowId) {\n try {\n return column.accessor(row);\n }\n catch (cause) {\n throw new PretableRowModelError(\"accessor-failed\", `Column ${column.id} accessor failed.`, {\n operation: this.#operation,\n rowId,\n columnId: column.id,\n cause,\n });\n }\n }\n /*\n * The ONE filter verdict, parameterized over the value source the same way\n * `#finalizeMetadata` is: `evaluate` supplies its collected value map, the\n * verdict-only path supplies live accessor reads. Predicate semantics live\n * in `compileFilterPredicate` and join semantics in `compileFilterNodes`,\n * both reached through the construction-time `#compiledFilterTree` — no\n * `#byId` lookup and no operand re-normalization per row.\n *\n * The ROOT list joins conjunctively, as it always has — a query's top-level\n * filters all have to hold. Below the roots, groups join by their own `op`.\n */\n #filterVerdict(valueOf) {\n return this.#compiledFilterTree(valueOf);\n }\n /**\n * The plan's OWN captured filter tree — the objects `captureFilterNode`\n * produced, not the re-frozen copy the `query` getter hands out.\n * @internal\n */\n static capturedFilterTreeForTesting(plan) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Captured filters require a compiled query plan.\");\n }\n return plan.#publicQuery.filters;\n }\n /**\n * This plan's filter verdict for one row — accessor reads over the runtime\n * filter columns only, no metadata construction, no cache writes. Error\n * semantics match `evaluate`: a throwing accessor surfaces the same\n * accessor-failed shape.\n *\n * A row this plan has already evaluated answers from the evaluation cache\n * under `evaluate`'s own guard, so `evaluate` + this call costs ONE\n * accessor pass, not two (the pinned per-row work budgets are exact). The\n * memo is exactly as fresh as the metadata `evaluate` would hand back for\n * the same input, and never answers for a DIFFERENT plan — old verdicts\n * come from root membership, not from here. The `verdictPlan` arm is what\n * makes that last clause true once a cache is SHARED: an adopted entry's\n * memo belongs to the plan that wrote it, so this plan re-reads accessors\n * rather than repeating a verdict its own filters never produced.\n */\n static filterVerdict(plan, input, instrumentation) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Filter verdicts require a compiled query plan.\");\n }\n const compiled = plan;\n if (instrumentation !== undefined)\n instrumentation.work.evaluationCacheLookups += 1;\n const cached = compiled.#evaluationCache.get(input.row);\n if (cached !== undefined &&\n cached.metadata !== undefined &&\n cached.filterPasses !== undefined &&\n cached.verdictPlan === compiled &&\n Object.is(cached.rowId, input.rowId) &&\n cached.sourceOrder === input.sourceOrder) {\n return cached.filterPasses;\n }\n return compiled.#filterVerdict((columnId) => compiled.#readColumnValue(compiled.#byId.get(columnId), input.row, input.rowId));\n }\n /**\n * Fused verdict + sort-key resolution for the ADOPTED identity-carry\n * sweep: ONE evaluation-cache read answers both questions\n * `filterVerdict` + `fillSortKeysFromPrevious` used to pay two reads for\n * (the verdict lookup discarded its entry, then the fill looked the same\n * key up again to hit its early return — one redundant get per survivor).\n *\n * Returns the row's sort keys when the row passes THIS plan's filters and\n * `undefined` when it does not; a rejected row's keys are never read, so\n * key resolution rides the verdict's single lookup for free.\n *\n * Precondition (CALLER-OWNED, exactly `adoptEvaluationCache`'s): this\n * plan's cache was adopted from the plan whose lineage evaluated\n * `input.row` — a filter-only change — so the cached `sortKeys` are the\n * ones this plan's accessors would produce (same orderings, same\n * accessors; see the adoption proof). The verdict is still recomputed\n * under this plan whenever the memo's `verdictPlan` is not this plan —\n * adopted entries always miss that guard, exactly as before the fusion.\n */\n static sortKeysIfPasses(plan, input, instrumentation) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Filter verdicts require a compiled query plan.\");\n }\n const compiled = plan;\n if (instrumentation !== undefined)\n instrumentation.work.evaluationCacheLookups += 1;\n const cached = compiled.#evaluationCache.get(input.row);\n const passes = cached !== undefined &&\n cached.metadata !== undefined &&\n cached.filterPasses !== undefined &&\n cached.verdictPlan === compiled &&\n Object.is(cached.rowId, input.rowId) &&\n cached.sourceOrder === input.sourceOrder\n ? cached.filterPasses\n : compiled.#filterVerdict((columnId) => compiled.#readColumnValue(compiled.#byId.get(columnId), input.row, input.rowId));\n if (!passes)\n return undefined;\n if (cached !== undefined) {\n // The same UNGUARDED read the carry fill's early return performs:\n // sort keys depend only on the row object and the (unchanged) sort\n // columns, so an entry from anywhere in the adopted lineage answers.\n return cached.sortKeys;\n }\n // A row the adopted lineage never evaluated: resolve keys by accessor\n // and seed a keys-only entry, mirroring the carry fill's miss arm with\n // nothing to carry (`metadata` absent, so a later `evaluate` upgrades).\n const sortKeys = Object.freeze(compiled.#runtimeQuery.sort.map((entry) => {\n const value = compiled.#readColumnValue(compiled.#byId.get(entry.columnId), input.row, input.rowId);\n if (instrumentation !== undefined)\n instrumentation.work.sortKeyEvaluations += 1;\n return Object.freeze({ columnId: entry.columnId, value });\n }));\n compiled.#evaluationCache.set(input.row, {\n rowId: input.rowId,\n sourceOrder: input.sourceOrder,\n metadata: undefined,\n filterPasses: undefined,\n verdictPlan: undefined,\n sortKeys,\n });\n return sortKeys;\n }\n /*\n * The single comparison loop behind `compareRecordRows`: per-ordering\n * `compareValues` over store-resolved keys, then the `sourceOrder`\n * tiebreak. Kept separate from key resolution so both sides resolve\n * before any comparison runs.\n */\n #compareBySortKeys(left, leftKeys, right, rightKeys) {\n for (let index = 0; index < this.#runtimeQuery.sort.length; index += 1) {\n const ordering = this.#runtimeQuery.sort[index];\n const column = this.#byId.get(ordering.columnId);\n try {\n const result = compareValues(leftKeys[index]?.value, rightKeys[index]?.value, column, ordering);\n if (result !== 0)\n return result;\n }\n catch (cause) {\n throw new CompiledQueryComparatorError(\"A compiled row comparator failed.\", [left.rowId, right.rowId], { columnId: ordering.columnId, cause, operation: this.#operation });\n }\n }\n return left.sourceOrder - right.sourceOrder;\n }\n #resolveSortKeys(input) {\n const keys = this.#evaluationCache.get(input.row)?.sortKeys;\n if (keys === undefined) {\n throw new Error(`Row ${String(input.rowId)} has no sort keys under this plan.`);\n }\n return keys;\n }\n /**\n * Orders two evaluated rows by the plan's own sort-key store. A missing\n * store entry is a defect — the fill points (`evaluate` and\n * `fillSortKeysFromPrevious`) are exhaustive — so resolution throws rather\n * than lazily re-running accessors.\n */\n static compareRecordRows(plan, left, right) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Record comparison requires a compiled query plan.\");\n }\n const compiled = plan;\n return compiled.#compareBySortKeys(left, compiled.#resolveSortKeys(left), right, compiled.#resolveSortKeys(right));\n }\n /**\n * Orders two rows by keys the CALLER already resolved — no store lookups.\n * Exists so O(n log n) sorts resolve keys once per row (decorate) instead\n * of once per comparison; `compareRecordRows` remains the general entry.\n * The comparison semantics are the same shared loop.\n */\n static compareWithSortKeys(plan, left, leftKeys, right, rightKeys) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Key comparison requires a compiled query plan.\");\n }\n return plan.#compareBySortKeys(left, leftKeys, right, rightKeys);\n }\n /**\n * Resolves one evaluated row's keys from the plan's own store. Same\n * fail-loud contract as `compareRecordRows`: a missing entry is a defect.\n */\n static sortKeysOf(plan, input) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Sort-key resolution requires a compiled query plan.\");\n }\n return plan.#resolveSortKeys(input);\n }\n /**\n * Fills `nextPlan`'s store for one row from `previousPlan`'s: values carry\n * by columnId where the sort columns overlap, accessors run only for\n * newly-active sort columns. Precondition (caller-owned): the plan change\n * preserves every carried sort column's accessor semantics, so carried\n * values are the ones the next plan's accessors would produce — both\n * `isSortOnlyChange` and `isFilterOnlyChange` qualify. When instrumentation is\n * supplied, one counter is bumped per (row, sort column) entry — carry vs\n * accessor — and an already-filled row counts nothing.\n */\n static fillSortKeysFromPrevious(nextPlan, previousPlan, input, instrumentation) {\n if (!(nextPlan instanceof CompiledQueryPlan) ||\n !(previousPlan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Sort-key carryover requires compiled query plans.\");\n }\n const next = nextPlan;\n const previous = previousPlan;\n if (instrumentation !== undefined)\n instrumentation.work.evaluationCacheLookups += 1;\n const existing = next.#evaluationCache.get(input.row);\n if (existing !== undefined) {\n return existing.sortKeys;\n }\n if (instrumentation !== undefined)\n instrumentation.work.evaluationCacheLookups += 1;\n const carried = previous.#evaluationCache.get(input.row)?.sortKeys;\n const sortKeys = Object.freeze(next.#runtimeQuery.sort.map((entry) => {\n const previousKey = carried?.find((key) => key.columnId === entry.columnId);\n if (previousKey !== undefined) {\n if (instrumentation !== undefined)\n instrumentation.work.sortKeyCarries += 1;\n return Object.freeze({\n columnId: entry.columnId,\n value: previousKey.value,\n });\n }\n let value;\n try {\n value = next.#byId.get(entry.columnId).accessor(input.row);\n }\n catch (cause) {\n throw new PretableRowModelError(\"accessor-failed\", `Column ${entry.columnId} accessor failed.`, {\n operation: next.#operation,\n rowId: input.rowId,\n columnId: entry.columnId,\n cause,\n });\n }\n if (instrumentation !== undefined)\n instrumentation.work.sortKeyEvaluations += 1;\n return Object.freeze({ columnId: entry.columnId, value });\n }));\n // Keys-only entry: `metadata` stays absent, so a later `evaluate` for\n // this row misses the metadata guard and upgrades the entry in place.\n next.#evaluationCache.set(input.row, {\n rowId: input.rowId,\n sourceOrder: input.sourceOrder,\n metadata: undefined,\n filterPasses: undefined,\n verdictPlan: undefined,\n sortKeys,\n });\n return sortKeys;\n }\n /**\n * Points `nextPlan`'s evaluation cache at `previousPlan`'s — one reference\n * assignment for the whole store, no copy and no per-row work. Replaces the\n * per-row `fillSortKeysFromPrevious` walk on the filter fast path.\n *\n * Precondition (CALLER-OWNED, exactly like `fillSortKeysFromPrevious`):\n * `isFilterOnlyChange(previousPlan, nextPlan)`. Only the plan-shape check\n * is enforced here; passing a plan pair the classifier would reject\n * silently corrupts `nextPlan`'s reads, so callers assert first.\n *\n * Why every cached field survives, field by field — this is the safety\n * proof, and a filter-only delta is what each line spends:\n *\n * - `rowId` / `sourceOrder`: guard fields, not derived state. They record\n * the input the entry was written for, and both `evaluate` and\n * `filterVerdict` re-check them against the live input, so a drift\n * demotes to a miss under either plan.\n * - `row`: the WeakMap KEY. Adoption cannot change which row an entry\n * describes.\n * - `metadata.rowId` / `.row` / `.sourceOrder`: copies of the guarded\n * input, so they are correct under any plan that hits the guard.\n * - `metadata.groupPath`: one entry per `rowGroups` ordering, valued by\n * that column's accessor. `isFilterOnlyChange` requires\n * `!groupsChanged` (identical orderings) and `!derivationsChanged`,\n * which compares the accessor IDENTITY of every grouped column in BOTH\n * plans' queries. Same orderings + same accessors + same row object ⇒\n * the same path. (In practice the fast path also refuses grouped\n * queries outright.)\n * - `metadata.aggregateLeaves`: one entry per column with an `aggregate`,\n * carrying the aggregate spec, the row, the accessor value, and a\n * `dependency`. `derivationsEqualForPlan` compares column id, type and\n * ORDER positionally, requires `semanticValueEqual` on every\n * `aggregate`, and forces accessor identity for every aggregated\n * column — so the leaf set, its order, its specs and its values are all\n * identical.\n * - the leaves' `dependency` (`{ sourceOrder, sortKeys }`): guarded\n * `sourceOrder` plus the keys below.\n * - `sortKeys` (on the entry and inside the dependency): one value per\n * `sort` ordering. `isFilterOnlyChange` requires `!sortChanged`, and\n * `derivationsEqualForPlan` pins both the accessor and the comparator of\n * every sorted column. Identical orderings over identical accessors ⇒\n * value-identical keys, which is precisely why the per-row fill this\n * replaces reported 100% carries and zero evaluations.\n * - `filterPasses`: the ONE filter-dependent field, and the reason\n * `verdictPlan` exists. The memo is only read when `verdictPlan` is the\n * reading plan, so an adopted entry's verdict is invisible to the\n * adopter and it runs its own filters instead. Nothing stale leaks; the\n * adopter pays exactly the accessor pass it paid before this change.\n *\n * Sharing is symmetric-safe: the previous plan keeps reading the same map,\n * and anything the next plan writes into it is either value-identical\n * under the argument above or tagged with the writer (`verdictPlan`).\n */\n static adoptEvaluationCache(nextPlan, previousPlan) {\n if (!(nextPlan instanceof CompiledQueryPlan) ||\n !(previousPlan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Evaluation-cache adoption requires compiled query plans.\");\n }\n nextPlan.#evaluationCache = previousPlan.#evaluationCache;\n }\n compareGroupKeys(level, left, right) {\n const ordering = this.#runtimeQuery.rowGroups[level];\n if (!ordering)\n throw new RangeError(`Unknown row-group level ${level}.`);\n const column = this.#byId.get(ordering.columnId);\n try {\n return compareValues(left.value, right.value, column, ordering);\n }\n catch (cause) {\n throw new CompiledQueryComparatorError(\"A compiled group comparator failed.\", undefined, {\n columnId: ordering.columnId,\n cause,\n groupValues: [left.value, right.value],\n operation: this.#operation,\n });\n }\n }\n /**\n * Facet delta between two plans this module compiled. `undefined` means\n * \"treat as everything changed\" — a foreign object cannot be inspected, so\n * it never qualifies as a narrow change. Facets are compared on the RUNTIME\n * query, not the public one: under external sort authority the runtime\n * sort is `[]` on both sides, so a public-only sort change classifies as\n * `sortChanged: false` here, same as a true no-op.\n */\n static classifyDelta(previous, next) {\n if (!(previous instanceof CompiledQueryPlan) ||\n !(next instanceof CompiledQueryPlan))\n return undefined;\n // Both directions are required: a column active under only ONE side's\n // query (e.g. sorted in `next` but not in `previous`) would escape a\n // single-sided comparison, narrowing the conservatism guarantee.\n const derivationsChanged = !(derivationsEqualForPlan(previous.#runtimeColumns, next.#runtimeColumns, previous.#runtimeQuery, previous.#filterLeaves) &&\n derivationsEqualForPlan(previous.#runtimeColumns, next.#runtimeColumns, next.#runtimeQuery, next.#filterLeaves));\n const filtersChanged = !filterNodeListEqual(previous.#runtimeQuery.filters, next.#runtimeQuery.filters);\n const groupsChanged = !orderingEqual(previous.#runtimeQuery.rowGroups, next.#runtimeQuery.rowGroups);\n const sortChanged = !orderingEqual(previous.#runtimeQuery.sort, next.#runtimeQuery.sort);\n const authorityChanged = previous.#filterAuthority !== next.#filterAuthority ||\n previous.#sortAuthority !== next.#sortAuthority;\n return Object.freeze({\n derivationsChanged,\n filtersChanged,\n groupsChanged,\n sortChanged,\n authorityChanged,\n });\n }\n}\nexport function classifyQueryDelta(previous, next) {\n return CompiledQueryPlan.classifyDelta(previous, next);\n}\n/**\n * True only when the applied sort is the sole difference between the plans.\n */\nexport function isSortOnlyChange(previous, next) {\n const delta = classifyQueryDelta(previous, next);\n return (delta !== undefined &&\n delta.sortChanged &&\n !delta.derivationsChanged &&\n !delta.filtersChanged &&\n !delta.groupsChanged &&\n !delta.authorityChanged);\n}\n/**\n * True only when the applied filters are the sole difference between the\n * plans.\n */\nexport function isFilterOnlyChange(previous, next) {\n const delta = classifyQueryDelta(previous, next);\n return (delta !== undefined &&\n delta.filtersChanged &&\n !delta.derivationsChanged &&\n !delta.groupsChanged &&\n !delta.sortChanged &&\n !delta.authorityChanged);\n}\n/**\n * Orders two evaluated row records under `plan` via the plan's own sort-key\n * store. Both rows must already be in the store (`evaluate` or\n * `fillSortKeysFromPrevious`); a missing entry throws — it is a defect, not a\n * lazy-fill opportunity.\n */\nexport function compareRecordRows(plan, left, right) {\n return CompiledQueryPlan.compareRecordRows(plan, left, right);\n}\n/**\n * The plan's OWN captured filter tree — the objects `captureFilterNode`\n * produced, not the re-frozen copy the `query` getter hands out. Exists so\n * capture-level invariants (freezing, ownership) are assertable at all.\n * @internal\n */\nexport function getCapturedFilterTreeForTesting(plan) {\n return CompiledQueryPlan.capturedFilterTreeForTesting(plan);\n}\n/**\n * Orders two rows by keys the caller already resolved (via `sortKeysOf` or\n * `fillSortKeysFromPrevious`) — no store lookups. Exists so O(n log n) sorts\n * resolve keys once per row instead of once per comparison;\n * `compareRecordRows` remains the general entry with identical semantics.\n */\nexport function compareWithSortKeys(plan, left, leftKeys, right, rightKeys) {\n return CompiledQueryPlan.compareWithSortKeys(plan, left, leftKeys, right, rightKeys);\n}\n/**\n * Resolves one evaluated row's sort keys from `plan`'s own store. Both the\n * shape and the fail-loud contract match `compareRecordRows`: the row must\n * already be in the store, and a missing entry throws.\n */\nexport function sortKeysOf(plan, input) {\n return CompiledQueryPlan.sortKeysOf(plan, input);\n}\n/**\n * Fills `nextPlan`'s sort-key store for one row, carrying values from\n * `previousPlan`'s store where the sort columns overlap and running accessors\n * only for newly-active sort columns. Idempotent per row. Valid ONLY under a\n * plan change that preserves every carried sort column's accessor semantics\n * (`isSortOnlyChange` and `isFilterOnlyChange` both qualify) — the caller\n * owns that check.\n */\nexport function fillSortKeysFromPrevious(nextPlan, previousPlan, input, instrumentation) {\n return CompiledQueryPlan.fillSortKeysFromPrevious(nextPlan, previousPlan, input, instrumentation);\n}\n/**\n * Points `nextPlan` at `previousPlan`'s whole evaluation cache — sort keys\n * AND metadata — by reference. One assignment replaces a per-row fill, which\n * is why the filter fast path uses it instead of walking every row.\n *\n * Valid ONLY when `isFilterOnlyChange(previousPlan, nextPlan)` holds; the\n * caller owns that check. The field-by-field argument for why every cached\n * field survives such a change lives on\n * `CompiledQueryPlan.adoptEvaluationCache`.\n */\nexport function adoptEvaluationCache(nextPlan, previousPlan) {\n CompiledQueryPlan.adoptEvaluationCache(nextPlan, previousPlan);\n}\n/**\n * Computes `plan`'s filter verdict for one row: each runtime filter's column\n * accessor runs and its predicate is evaluated, with the same semantics and\n * accessor-failed error shape as `evaluate` — the predicate loop is shared,\n * not duplicated. No metadata is built and no cache entry is written.\n */\nexport function filterVerdict(plan, input, instrumentation) {\n return CompiledQueryPlan.filterVerdict(plan, input, instrumentation);\n}\n/**\n * Fused verdict + sort-key resolution under an ADOPTED evaluation cache —\n * one cache read instead of `filterVerdict` + `fillSortKeysFromPrevious`'s\n * two. Returns the keys when the row passes `plan`'s filters, `undefined`\n * when it does not. Valid ONLY after `adoptEvaluationCache(plan, previous)`\n * for the plan lineage that evaluated the row (a filter-only change); see\n * `CompiledQueryPlan.sortKeysIfPasses` for the semantics proof.\n */\nexport function sortKeysIfPasses(plan, input, instrumentation) {\n return CompiledQueryPlan.sortKeysIfPasses(plan, input, instrumentation);\n}\nexport function compileQuery(input) {\n const captured = captureCompileInput(input);\n validateDerivations(captured.columns);\n validateQuery(captured.query, captured.columns);\n const previous = captured.previous;\n if (previous?.[internals]?.semanticallyMatches(captured.columns, captured.query, captured.filterAuthority, captured.sortAuthority))\n return previous;\n return new CompiledQueryPlan(captured.columns, captured.query, input.operation ?? \"set-query\", captured.filterAuthority, captured.sortAuthority);\n}\n","/**\n * Membership bitsets: one bit per SLOT (see `slot-allocator`). A committed\n * root's verdict is its membership (the filter-membership invariant); the\n * bitset is a faster INDEX of that same structural answer for flat roots,\n * never a stored verdict. Grouped roots carry `EMPTY_MEMBERSHIP` and keep\n * answering from the group index.\n *\n * Mutable while a producer is building the next revision's set; frozen by\n * convention once a root captures it (no Object.freeze — typed arrays do not\n * support it; discipline is \"producers build fresh or clone, never write a\n * captured root's bitset\", the same convention every persistent structure\n * here relies on).\n *\n * Whole-copy on change is the point: 50k rows is 6.25KB, negligible per\n * commit (M0 measured ~1µs), so no COW machinery exists at this layer.\n */\n/** Shared sentinel for roots whose membership lives elsewhere (grouped). */\nexport const EMPTY_MEMBERSHIP = new Uint32Array(0);\nexport function createMembership(capacity) {\n return new Uint32Array((capacity + 31) >>> 5);\n}\n/** Clone, growing to `capacity` when it exceeds the source's words. */\nexport function cloneMembership(bits, capacity) {\n const words = Math.max(bits.length, (capacity + 31) >>> 5);\n const next = new Uint32Array(words);\n next.set(bits);\n return next;\n}\nexport function setMembershipBit(bits, slot) {\n bits[slot >>> 5] |= 1 << (slot & 31);\n}\nexport function clearMembershipBit(bits, slot) {\n bits[slot >>> 5] &= ~(1 << (slot & 31));\n}\n/** Out-of-range slots read as false — the EMPTY sentinel relies on this. */\nexport function testMembershipBit(bits, slot) {\n const word = bits[slot >>> 5];\n return word === undefined ? false : ((word >>> (slot & 31)) & 1) === 1;\n}\n","export class TransientEditToken {\n #editable = true;\n assertEditable() {\n if (!this.#editable) {\n throw new Error(\"Cannot mutate a frozen transient map.\");\n }\n }\n freeze() {\n this.#editable = false;\n }\n}\n","import { TransientEditToken } from \"./transient\";\nconst inspectPersistentPath = Symbol(\"inspectPersistentPath\");\nconst inspectTransientPath = Symbol(\"inspectTransientPath\");\nconst attachInstrumentation = Symbol(\"attachInstrumentation\");\nfunction hashString(value) {\n let hash = 0x811c9dc5;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\nfunction hashKey(key) {\n return hashString(typeof key === \"string\" ? `s:${key}` : `n:${String(key)}`);\n}\nfunction sameKey(left, right) {\n return left === right || (left !== left && right !== right);\n}\nfunction fragment(hash, shift) {\n return (hash >>> shift) & 0b1_1111;\n}\nfunction bitPosition(hash, shift) {\n return 1 << fragment(hash, shift);\n}\nfunction populationCount(value) {\n let remaining = value >>> 0;\n remaining -= (remaining >>> 1) & 0x55555555;\n remaining = (remaining & 0x33333333) + ((remaining >>> 2) & 0x33333333);\n return (((remaining + (remaining >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24;\n}\nfunction childIndex(bitmap, bit) {\n return populationCount(bitmap & (bit - 1));\n}\nfunction createLeaf(edit, hash, key, value) {\n return { kind: \"leaf\", edit, hash, entries: [[key, value]] };\n}\nfunction editableLeaf(node, edit, instrumentation) {\n if (edit !== null && node.edit === edit)\n return node;\n if (instrumentation !== undefined)\n instrumentation.work.hamtNodesCopied += 1;\n return { ...node, edit, entries: node.entries.slice() };\n}\nfunction editableBranch(node, edit, instrumentation) {\n if (edit !== null && node.edit === edit)\n return node;\n if (instrumentation !== undefined)\n instrumentation.work.hamtNodesCopied += 1;\n return { ...node, edit, children: node.children.slice() };\n}\nfunction mergeLeaves(shift, left, right, edit) {\n const leftBit = bitPosition(left.hash, shift);\n const rightBit = bitPosition(right.hash, shift);\n if (leftBit === rightBit) {\n return {\n kind: \"branch\",\n edit,\n bitmap: leftBit,\n children: [mergeLeaves(shift + 5, left, right, edit)],\n };\n }\n return {\n kind: \"branch\",\n edit,\n bitmap: leftBit | rightBit,\n children: leftBit >>> 0 < rightBit >>> 0 ? [left, right] : [right, left],\n };\n}\nfunction setNode(node, shift, hash, key, value, edit, instrumentation) {\n if (node === null) {\n return {\n node: createLeaf(edit, hash, key, value),\n changed: true,\n sizeDelta: 1,\n };\n }\n if (node.kind === \"leaf\") {\n if (node.hash !== hash) {\n return {\n node: mergeLeaves(shift, node, createLeaf(edit, hash, key, value), edit),\n changed: true,\n sizeDelta: 1,\n };\n }\n const entryIndex = node.entries.findIndex(([entryKey]) => sameKey(entryKey, key));\n if (entryIndex >= 0) {\n if (Object.is(node.entries[entryIndex][1], value)) {\n return { node, changed: false, sizeDelta: 0 };\n }\n const updated = editableLeaf(node, edit, instrumentation);\n updated.entries[entryIndex] = [key, value];\n return { node: updated, changed: true, sizeDelta: 0 };\n }\n const updated = editableLeaf(node, edit, instrumentation);\n updated.entries.push([key, value]);\n return { node: updated, changed: true, sizeDelta: 1 };\n }\n const bit = bitPosition(hash, shift);\n const index = childIndex(node.bitmap, bit);\n if ((node.bitmap & bit) === 0) {\n const updated = editableBranch(node, edit, instrumentation);\n updated.bitmap |= bit;\n updated.children.splice(index, 0, createLeaf(edit, hash, key, value));\n return { node: updated, changed: true, sizeDelta: 1 };\n }\n const childChange = setNode(node.children[index], shift + 5, hash, key, value, edit, instrumentation);\n if (!childChange.changed)\n return { node, changed: false, sizeDelta: 0 };\n const updated = editableBranch(node, edit, instrumentation);\n updated.children[index] = childChange.node;\n return {\n node: updated,\n changed: true,\n sizeDelta: childChange.sizeDelta,\n };\n}\nfunction deleteNode(node, shift, hash, key, edit, instrumentation) {\n if (node === null)\n return { node, changed: false, sizeDelta: 0 };\n if (node.kind === \"leaf\") {\n if (node.hash !== hash)\n return { node, changed: false, sizeDelta: 0 };\n const entryIndex = node.entries.findIndex(([entryKey]) => sameKey(entryKey, key));\n if (entryIndex < 0)\n return { node, changed: false, sizeDelta: 0 };\n if (node.entries.length === 1) {\n return { node: null, changed: true, sizeDelta: -1 };\n }\n const updated = editableLeaf(node, edit, instrumentation);\n updated.entries.splice(entryIndex, 1);\n return { node: updated, changed: true, sizeDelta: -1 };\n }\n const bit = bitPosition(hash, shift);\n if ((node.bitmap & bit) === 0) {\n return { node, changed: false, sizeDelta: 0 };\n }\n const index = childIndex(node.bitmap, bit);\n const childChange = deleteNode(node.children[index], shift + 5, hash, key, edit, instrumentation);\n if (!childChange.changed)\n return { node, changed: false, sizeDelta: 0 };\n const updated = editableBranch(node, edit, instrumentation);\n if (childChange.node === null) {\n updated.bitmap &= ~bit;\n updated.children.splice(index, 1);\n if (updated.children.length === 0) {\n return { node: null, changed: true, sizeDelta: -1 };\n }\n }\n else {\n updated.children[index] = childChange.node;\n }\n if (updated.children.length === 1 && updated.children[0].kind === \"leaf\") {\n return { node: updated.children[0], changed: true, sizeDelta: -1 };\n }\n return { node: updated, changed: true, sizeDelta: -1 };\n}\nfunction lookupEntry(root, hash, key) {\n let node = root;\n let shift = 0;\n while (node !== null) {\n if (node.kind === \"leaf\") {\n if (node.hash !== hash)\n return undefined;\n return node.entries.find(([entryKey]) => sameKey(entryKey, key));\n }\n const bit = bitPosition(hash, shift);\n if ((node.bitmap & bit) === 0)\n return undefined;\n node = node.children[childIndex(node.bitmap, bit)];\n shift += 5;\n }\n return undefined;\n}\nfunction nodePath(root, hash) {\n const path = [];\n let node = root;\n let shift = 0;\n while (node !== null) {\n path.push(node);\n if (node.kind === \"leaf\")\n break;\n const bit = bitPosition(hash, shift);\n if ((node.bitmap & bit) === 0)\n break;\n node = node.children[childIndex(node.bitmap, bit)];\n shift += 5;\n }\n return path;\n}\n/**\n * Pre-order walk over an EXPLICIT stack, for the same reason the order-\n * statistic tree's walk uses one: `yield*` delegation routes every element\n * through one generator frame per trie level on its way out, so the cost of a\n * full walk scales with depth as well as size. The order-statistic tree\n * measured 30.04ms → 1.77ms at 50,000 entries on exactly this change; a\n * 32-way trie is shallower, so the win is smaller, but the shape is the same\n * mistake. Children are pushed in reverse so they pop in bitmap order —\n * iteration order is unspecified but must stay stable run to run.\n */\nfunction* iterateEntries(node) {\n if (node === null)\n return;\n const pending = [node];\n for (;;) {\n const visited = pending.pop();\n if (visited === undefined)\n return;\n if (visited.kind === \"leaf\") {\n for (const [key, value] of visited.entries)\n yield [key, value];\n continue;\n }\n for (let index = visited.children.length - 1; index >= 0; index -= 1) {\n const child = visited.children[index];\n if (child !== undefined)\n pending.push(child);\n }\n }\n}\nclass PersistentHashMap {\n #size;\n #root;\n #hash;\n #instrumentation;\n constructor(size, root, hash, instrumentation) {\n this.#size = size;\n this.#root = root;\n this.#hash = hash;\n this.#instrumentation = instrumentation;\n }\n get size() {\n return this.#size;\n }\n get(key) {\n return lookupEntry(this.#root, this.#hash(key) >>> 0, key)?.[1];\n }\n has(key) {\n return lookupEntry(this.#root, this.#hash(key) >>> 0, key) !== undefined;\n }\n set(key, value) {\n const change = setNode(this.#root, 0, this.#hash(key) >>> 0, key, value, null, this.#instrumentation);\n if (!change.changed)\n return this;\n return new PersistentHashMap(this.#size + change.sizeDelta, change.node, this.#hash, this.#instrumentation);\n }\n delete(key) {\n const change = deleteNode(this.#root, 0, this.#hash(key) >>> 0, key, null, this.#instrumentation);\n if (!change.changed)\n return this;\n return new PersistentHashMap(this.#size + change.sizeDelta, change.node, this.#hash, this.#instrumentation);\n }\n asTransient() {\n return new TransientHashMap(this.#size, this.#root, this.#hash, this.#instrumentation);\n }\n entries() {\n return iterateEntries(this.#root);\n }\n [inspectPersistentPath](key) {\n return nodePath(this.#root, this.#hash(key) >>> 0);\n }\n [attachInstrumentation](instrumentation) {\n return new PersistentHashMap(this.#size, this.#root, this.#hash, instrumentation);\n }\n}\nclass TransientHashMap {\n #size;\n #root;\n #hash;\n #edit = new TransientEditToken();\n #instrumentation;\n #frozen;\n constructor(size, root, hash, instrumentation) {\n this.#size = size;\n this.#root = root;\n this.#hash = hash;\n this.#instrumentation = instrumentation;\n }\n get size() {\n return this.#size;\n }\n get(key) {\n return lookupEntry(this.#root, this.#hash(key) >>> 0, key)?.[1];\n }\n has(key) {\n return lookupEntry(this.#root, this.#hash(key) >>> 0, key) !== undefined;\n }\n set(key, value) {\n this.#edit.assertEditable();\n const change = setNode(this.#root, 0, this.#hash(key) >>> 0, key, value, this.#edit, this.#instrumentation);\n this.#root = change.node;\n this.#size += change.sizeDelta;\n return this;\n }\n delete(key) {\n this.#edit.assertEditable();\n const change = deleteNode(this.#root, 0, this.#hash(key) >>> 0, key, this.#edit, this.#instrumentation);\n this.#root = change.node;\n this.#size += change.sizeDelta;\n return this;\n }\n freeze() {\n if (this.#frozen !== undefined)\n return this.#frozen;\n this.#edit.freeze();\n this.#frozen = new PersistentHashMap(this.#size, this.#root, this.#hash, this.#instrumentation);\n return this.#frozen;\n }\n entries() {\n return iterateEntries(this.#root);\n }\n [inspectTransientPath](key) {\n return nodePath(this.#root, this.#hash(key) >>> 0);\n }\n}\nexport function createPersistentMap() {\n return new PersistentHashMap(0, null, hashKey);\n}\nexport function instrumentPersistentMap(map, instrumentation) {\n if (instrumentation === undefined)\n return map;\n if (!(map instanceof PersistentHashMap)) {\n throw new TypeError(\"Instrumentation requires a map created by this module.\");\n }\n return map[attachInstrumentation](instrumentation);\n}\nexport function createPersistentMapForTesting(hash) {\n return new PersistentHashMap(0, null, hash);\n}\nexport function getPersistentMapPathForTesting(map, key) {\n if (!(map instanceof PersistentHashMap)) {\n throw new TypeError(\"Diagnostics require a map created by this module.\");\n }\n return map[inspectPersistentPath](key);\n}\nexport function getTransientMapPathForTesting(map, key) {\n if (!(map instanceof TransientHashMap)) {\n throw new TypeError(\"Diagnostics require a map created by this module.\");\n }\n return map[inspectTransientPath](key);\n}\n","var _a;\nimport { createPersistentMap } from \"./persistent-map\";\nimport { instrumentPersistentMap } from \"./persistent-map\";\nconst attachInstrumentation = Symbol(\"attachOrderInstrumentation\");\nconst createDeferredMeasureDraft = Symbol(\"createDeferredMeasureDraft\");\nconst buildFromSortedEntries = Symbol(\"buildFromSortedEntries\");\nclass TreeEditToken {\n #editable = true;\n assertEditable() {\n if (!this.#editable) {\n throw new Error(\"Cannot mutate a frozen transient order-statistic tree.\");\n }\n }\n freeze() {\n this.#editable = false;\n }\n}\nexport class PoisonedTransientOrderStatisticTreeError extends Error {\n code = \"poisoned-transient-order-statistic-tree\";\n constructor(cause) {\n super(\"Cannot use a transient order-statistic tree after a callback failure.\", { cause });\n this.name = \"PoisonedTransientOrderStatisticTreeError\";\n }\n}\nconst persistentRoots = new WeakMap();\nfunction sameId(left, right) {\n return left === right || (left !== left && right !== right);\n}\nfunction compareIds(left, right) {\n if (sameId(left, right))\n return 0;\n if (typeof left !== typeof right)\n return typeof left === \"number\" ? -1 : 1;\n if (typeof left === \"number\" && typeof right === \"number\") {\n if (Number.isNaN(left))\n return 1;\n if (Number.isNaN(right))\n return -1;\n return left < right ? -1 : 1;\n }\n return left < right ? -1 : 1;\n}\nfunction compareEntries(left, leftId, right, rightId, context) {\n const comparison = context.compare(left, right);\n if (comparison < 0)\n return -1;\n if (comparison > 0)\n return 1;\n return compareIds(leftId, rightId);\n}\nfunction nodeHeight(node) {\n return node?.height ?? 0;\n}\nfunction createNode(entry, id, context, edit) {\n const ownMeasure = context.measure.fromEntry(entry);\n return {\n edit,\n id,\n entry,\n ownMeasure,\n measure: ownMeasure,\n count: 1,\n height: 1,\n left: null,\n right: null,\n };\n}\nfunction editableNode(node, edit, instrumentation) {\n if (edit !== null && node.edit === edit)\n return node;\n if (instrumentation !== undefined)\n instrumentation.work.orderNodesCopied += 1;\n return { ...node, edit };\n}\nfunction refreshNode(node, context) {\n node.count = (node.left?.count ?? 0) + 1 + (node.right?.count ?? 0);\n node.height = 1 + Math.max(nodeHeight(node.left), nodeHeight(node.right));\n refreshNodeMeasure(node, context);\n}\nfunction refreshNodeMeasure(node, context) {\n const left = node.left?.measure ?? context.measure.empty;\n const right = node.right?.measure ?? context.measure.empty;\n node.measure = context.measure.combine(context.measure.combine(left, node.ownMeasure), right);\n}\nfunction refreshDeferredNodeMeasure(node, context) {\n let measure = node.ownMeasure;\n if (node.left !== null) {\n measure = context.measure.combine(node.left.measure, measure);\n }\n if (node.right !== null) {\n measure = context.measure.combine(measure, node.right.measure);\n }\n node.measure = measure;\n}\nfunction refreshNodeStructure(node) {\n node.count = (node.left?.count ?? 0) + 1 + (node.right?.count ?? 0);\n node.height = 1 + Math.max(nodeHeight(node.left), nodeHeight(node.right));\n}\nfunction refreshForMode(node, context, deferMeasure) {\n if (deferMeasure)\n refreshNodeStructure(node);\n else\n refreshNode(node, context);\n}\nfunction balanceFactor(node) {\n return nodeHeight(node.left) - nodeHeight(node.right);\n}\nfunction rotateRight(root, context, edit, deferMeasure = false) {\n const lower = editableNode(root, edit, context.instrumentation);\n const pivot = editableNode(lower.left, edit, context.instrumentation);\n lower.left = pivot.right;\n refreshForMode(lower, context, deferMeasure);\n pivot.right = lower;\n refreshForMode(pivot, context, deferMeasure);\n return pivot;\n}\nfunction rotateLeft(root, context, edit, deferMeasure = false) {\n const lower = editableNode(root, edit, context.instrumentation);\n const pivot = editableNode(lower.right, edit, context.instrumentation);\n lower.right = pivot.left;\n refreshForMode(lower, context, deferMeasure);\n pivot.left = lower;\n refreshForMode(pivot, context, deferMeasure);\n return pivot;\n}\nfunction rebalance(root, context, edit, deferMeasure = false) {\n refreshForMode(root, context, deferMeasure);\n const balance = balanceFactor(root);\n if (balance > 1) {\n if (balanceFactor(root.left) < 0) {\n root.left = rotateLeft(root.left, context, edit, deferMeasure);\n }\n return rotateRight(root, context, edit, deferMeasure);\n }\n if (balance < -1) {\n if (balanceFactor(root.right) > 0) {\n root.right = rotateRight(root.right, context, edit, deferMeasure);\n }\n return rotateLeft(root, context, edit, deferMeasure);\n }\n return root;\n}\nfunction insertNode(root, inserted, context, edit, deferMeasure = false) {\n if (root === null)\n return inserted;\n const comparison = compareEntries(inserted.entry, inserted.id, root.entry, root.id, context);\n if (comparison === 0)\n return root;\n const updated = editableNode(root, edit, context.instrumentation);\n if (comparison < 0) {\n updated.left = insertNode(updated.left, inserted, context, edit, deferMeasure);\n }\n else {\n updated.right = insertNode(updated.right, inserted, context, edit, deferMeasure);\n }\n return rebalance(updated, context, edit, deferMeasure);\n}\nfunction extractMinimum(root, context, edit) {\n if (root.left === null)\n return { minimum: root, node: root.right };\n const extracted = extractMinimum(root.left, context, edit);\n const updated = editableNode(root, edit, context.instrumentation);\n updated.left = extracted.node;\n return {\n minimum: extracted.minimum,\n node: rebalance(updated, context, edit),\n };\n}\nfunction removeNode(root, removedEntry, removedId, context, edit) {\n if (root === null)\n return { node: null, changed: false };\n const comparison = compareEntries(removedEntry, removedId, root.entry, root.id, context);\n if (comparison === 0) {\n if (root.left === null)\n return { node: root.right, changed: true };\n if (root.right === null)\n return { node: root.left, changed: true };\n const extracted = extractMinimum(root.right, context, edit);\n const replacement = editableNode(extracted.minimum, edit, context.instrumentation);\n replacement.left = root.left;\n replacement.right = extracted.node;\n return {\n node: rebalance(replacement, context, edit),\n changed: true,\n };\n }\n if (comparison < 0) {\n const change = removeNode(root.left, removedEntry, removedId, context, edit);\n if (!change.changed)\n return { node: root, changed: false };\n const updated = editableNode(root, edit, context.instrumentation);\n updated.left = change.node;\n return { node: rebalance(updated, context, edit), changed: true };\n }\n const change = removeNode(root.right, removedEntry, removedId, context, edit);\n if (!change.changed)\n return { node: root, changed: false };\n const updated = editableNode(root, edit, context.instrumentation);\n updated.right = change.node;\n return { node: rebalance(updated, context, edit), changed: true };\n}\nfunction entryAtNode(root, index) {\n if (!Number.isInteger(index) || index < 0 || index >= (root?.count ?? 0)) {\n return undefined;\n }\n let node = root;\n let remaining = index;\n while (node !== null) {\n const leftCount = node.left?.count ?? 0;\n if (remaining < leftCount)\n node = node.left;\n else if (remaining === leftCount)\n return node.entry;\n else {\n remaining -= leftCount + 1;\n node = node.right;\n }\n }\n return undefined;\n}\nfunction rankOfNode(root, entry, id, context) {\n let node = root;\n let rank = 0;\n while (node !== null) {\n if (sameId(id, node.id))\n return rank + (node.left?.count ?? 0);\n const comparison = compareEntries(entry, id, node.entry, node.id, context);\n if (comparison < 0)\n node = node.left;\n else if (comparison > 0) {\n rank += (node.left?.count ?? 0) + 1;\n node = node.right;\n }\n else\n return rank + (node.left?.count ?? 0);\n }\n return undefined;\n}\nfunction normalizedBound(bound, size) {\n if (Number.isNaN(bound))\n return 0;\n return Math.max(0, Math.min(size, Math.trunc(bound)));\n}\nfunction appendRange(node, offset, start, end, result) {\n if (node === null || start >= end)\n return;\n const nodeRank = offset + (node.left?.count ?? 0);\n if (start < nodeRank)\n appendRange(node.left, offset, start, end, result);\n if (start <= nodeRank && nodeRank < end)\n result.push(node.entry);\n if (nodeRank + 1 < end) {\n appendRange(node.right, nodeRank + 1, start, end, result);\n }\n}\nfunction rangeFromNode(root, start, end) {\n const size = root?.count ?? 0;\n const normalizedStart = normalizedBound(start, size);\n const normalizedEnd = normalizedBound(end, size);\n if (normalizedStart >= normalizedEnd)\n return [];\n const result = [];\n appendRange(root, 0, normalizedStart, normalizedEnd, result);\n return result;\n}\n/**\n * In-order walk over an EXPLICIT stack, and it must stay that way.\n *\n * The obvious shape — `yield* iterateEntries(node.left)` — makes every\n * element bubble up through one generator frame per tree level on its way\n * out, so walking n entries of a ~log2(n)-deep tree costs O(n log n)\n * generator resumptions rather than O(n). Measured on a 50,000-entry tree:\n * `yield*` delegation 30.04ms, this shape 1.77ms. The delegating version is\n * shorter and 17× slower; do not \"simplify\" it back.\n *\n * Laziness is part of the contract — callers step this iterator across\n * cooperative-transition slices — so materializing into an array here is not\n * an option either. Callers that materialize anyway should use `range(0,\n * size)`, which is faster still because it never suspends.\n */\nfunction* iterateEntries(node) {\n const pending = [];\n let current = node;\n for (;;) {\n while (current !== null) {\n pending.push(current);\n current = current.left;\n }\n const visited = pending.pop();\n if (visited === undefined)\n return;\n yield visited.entry;\n current = visited.right;\n }\n}\n/**\n * The transient walk, same explicit-stack shape and same reason (see\n * `iterateEntries`), plus the liveness guard a draft owes its callers: the\n * draft is checked on first resumption and again before every element, so a\n * walk in flight when the draft freezes or is abandoned fails on its next\n * step rather than yielding from a structure that has moved on.\n */\nfunction* iterateTransientEntries(node, assertHealthy) {\n assertHealthy();\n const pending = [];\n let current = node;\n for (;;) {\n while (current !== null) {\n pending.push(current);\n current = current.left;\n }\n const visited = pending.pop();\n if (visited === undefined)\n return;\n assertHealthy();\n yield visited.entry;\n current = visited.right;\n }\n}\nclass PersistentOrderStatisticTree {\n #root;\n #byId;\n #context;\n constructor(root, byId, context) {\n this.#root = root;\n this.#byId = byId;\n this.#context = context;\n persistentRoots.set(this, root);\n }\n get size() {\n return this.#root?.count ?? 0;\n }\n get measure() {\n return this.#root?.measure ?? this.#context.measure.empty;\n }\n get(id) {\n return this.#byId.get(id);\n }\n entryAt(index) {\n return entryAtNode(this.#root, index);\n }\n rankOf(id) {\n const entry = this.#byId.get(id);\n if (entry === undefined && !this.#byId.has(id))\n return undefined;\n return rankOfNode(this.#root, entry, id, this.#context);\n }\n range(start, end) {\n return rangeFromNode(this.#root, start, end);\n }\n insertOrReplace(entry) {\n const id = this.#context.getId(entry);\n const previous = this.#byId.get(id);\n const exists = previous !== undefined || this.#byId.has(id);\n if (exists && Object.is(previous, entry))\n return this;\n let root = this.#root;\n if (exists) {\n const removal = removeNode(root, previous, id, this.#context, null);\n if (!removal.changed)\n return this;\n root = removal.node;\n }\n root = insertNode(root, createNode(entry, id, this.#context, null), this.#context, null);\n return new _a(root, this.#byId.set(id, entry), this.#context);\n }\n remove(id) {\n const entry = this.#byId.get(id);\n if (entry === undefined && !this.#byId.has(id))\n return this;\n const removal = removeNode(this.#root, entry, id, this.#context, null);\n if (!removal.changed)\n return this;\n return new _a(removal.node, this.#byId.delete(id), this.#context);\n }\n asTransient() {\n return new TransientOrderStatisticTreeImpl(this.#root, this.#byId.asTransient(), this.#context, false);\n }\n /**\n * The strict-order check is unconditional by default: a misordered build\n * silently corrupts every later rank and lookup, which is strictly worse\n * than the O(n) cost of checking. Duplicates compare 0 and are rejected by\n * the same check.\n *\n * `proof.orderIsProven` is the only opt-out, and it exists for the two\n * in-package callers whose input is strictly sorted BY CONSTRUCTION, not by\n * assumption:\n *\n * - `filter-rebuild` merges the captured visible tree's in-order walk (the\n * tree's own order, minus a skipped subset — still strictly increasing)\n * with a subset it just sorted under the identical composite comparator\n * (`compareWithSortKeys` then id). A merge of two strictly-increasing\n * sequences under one total order is strictly increasing, and the two\n * sequences are disjoint by id (a flipped-in row was not visible).\n * - `sort-rebuild` hands over `Array.sort` output under that same composite\n * comparator, id tiebreak included, so it is totally ordered and the ids\n * are unique because they come from a HAMT keyed by id.\n *\n * Any caller that cannot make that argument from its own code — including\n * every external caller, which is why the option is package-internal — must\n * leave the check on. The escape hatch buys n−1 comparator calls per commit\n * and nothing else; it is not worth taking on a hunch.\n */\n [buildFromSortedEntries](sorted, proof) {\n const context = this.#context;\n const entryIds = sorted.map((entry) => context.getId(entry));\n if (proof?.orderIsProven === true) {\n if (context.instrumentation !== undefined) {\n context.instrumentation.work.bulkOrderVerificationsSkipped += 1;\n }\n }\n else {\n for (let index = 1; index < sorted.length; index += 1) {\n const comparison = compareEntries(sorted[index - 1], entryIds[index - 1], sorted[index], entryIds[index], context);\n if (comparison >= 0) {\n throw new TypeError(\"Bulk build input must be strictly sorted by the tree's total order.\");\n }\n }\n }\n const byId = this.#buildById(sorted, entryIds, proof?.derivedById);\n const build = (low, high) => {\n if (low > high)\n return null;\n const middle = (low + high) >> 1;\n const node = createNode(sorted[middle], entryIds[middle], context, null);\n node.left = build(low, middle - 1);\n node.right = build(middle + 1, high);\n if (node.left !== null || node.right !== null) {\n refreshNode(node, context);\n }\n return node;\n };\n return new _a(build(0, sorted.length - 1), byId, context);\n }\n [createDeferredMeasureDraft]() {\n if (this.size !== 0) {\n throw new Error(\"Deferred measure drafts require an empty tree.\");\n }\n return new TransientOrderStatisticTreeImpl(this.#root, this.#byId.asTransient(), this.#context, true);\n }\n entries() {\n return iterateEntries(this.#root);\n }\n /**\n * Builds the id→entry map by whichever of the two routes does fewer map\n * operations, and the choice is made HERE because this is the only place\n * that holds both counts.\n *\n * - Refill: `sorted.length` inserts into a fresh transient.\n * - Derive: `removedIds.size` deletes plus `addedEntries.length` inserts on\n * a transient over the base map.\n *\n * CONSTRAINT — a derivation offered is not a derivation taken. Deriving is\n * only cheaper when its edit count is below the refill's insert count, and\n * the difference is not academic: at S2's 50,000-row target the filter drops\n * to 12,500 survivors, so an unconditional derivation ran **37,500 removes\n * to replace 12,500 inserts — three times the work**. Measured, on that\n * scenario, by single-variable A/B: 217.1ms settle with the derivation\n * always on against 208.3ms with it always off, and 15.3ms of the\n * interaction window's persistent-map time attributed to this method. The\n * comparison below is algebraically `removals < survivors` (the added\n * entries are inserted on either route and cancel), so a narrow flip\n * derives and a wide one refills.\n *\n * The derivation is otherwise a CLAIM, and only one half of it is verified.\n * The\n * post-edit size check below is O(1) and catches the whole class of\n * \"wrong edit set\" slips (leavers left in, an added entry missing, a\n * duplicate id). What it cannot catch is a STALE survivor: derived mode\n * never touches an id that is neither removed nor added, so it keeps\n * whatever entry object the base map held for it. That is only correct\n * when the caller REUSES survivors' entry objects by identity, which is\n * exactly the precondition filter-rebuild's merge satisfies (a still-passing\n * row is unflipped, so its record and keys are both unchanged) and exactly\n * the one sort-rebuild does NOT: it allocates a fresh entry per row to\n * carry the new plan's keys, so its survivors are new objects and derived\n * mode would leave the map pointing at the previous plan's entries. That is\n * why sort-rebuild takes `orderIsProven` and nothing else.\n */\n #buildById(sorted, entryIds, derived) {\n const context = this.#context;\n if (derived !== undefined &&\n !(derived.base instanceof _a)) {\n // Checked before the routing decision, so an unusable base is a hard\n // error rather than a silent fall-through to the refill.\n throw new TypeError(\"Derived bulk-build maps require a base tree created by this module.\");\n }\n if (derived === undefined ||\n derived.removedIds.size + derived.addedEntries.length >= sorted.length) {\n const draft = createPersistentMap().asTransient();\n for (let index = 0; index < sorted.length; index += 1) {\n draft.set(entryIds[index], sorted[index]);\n }\n return draft.freeze();\n }\n const base = derived.base;\n // The base map is taken as-is rather than re-instrumented: the refill it\n // replaces built into a FRESH, uninstrumented map, so re-instrumenting\n // here would start charging visible-index byId churn to\n // `hamtNodesCopied` — the counter the suite uses as the record-rebuild\n // proxy, which must stay zero across a filter commit. The derivation's\n // own cost is reported by `bulkByIdDerived` instead.\n const draft = base.#byId.asTransient();\n for (const id of derived.removedIds)\n draft.delete(id);\n for (const entry of derived.addedEntries) {\n draft.set(context.getId(entry), entry);\n }\n const byId = draft.freeze();\n if (byId.size !== sorted.length) {\n throw new TypeError(\"Derived bulk-build map size must equal the built entry count.\");\n }\n if (context.instrumentation !== undefined) {\n context.instrumentation.work.bulkByIdDerived += 1;\n }\n return byId;\n }\n [attachInstrumentation](instrumentation, beforeCombine) {\n const measure = beforeCombine === undefined\n ? this.#context.measure\n : {\n ...this.#context.measure,\n combine: (left, right) => {\n beforeCombine();\n return this.#context.measure.combine(left, right);\n },\n };\n return new _a(this.#root, instrumentPersistentMap(this.#byId, instrumentation), { ...this.#context, measure, instrumentation });\n }\n}\n_a = PersistentOrderStatisticTree;\nclass TransientOrderStatisticTreeImpl {\n #root;\n #byId;\n #context;\n #edit = new TreeEditToken();\n #deferredMeasure;\n #frozen;\n #measureFrames;\n #pendingMeasureCount = 0;\n #poisoned = false;\n #poisonCause;\n constructor(root, byId, context, deferredMeasure) {\n this.#root = root;\n this.#byId = byId;\n this.#context = context;\n this.#deferredMeasure = deferredMeasure;\n }\n #assertHealthy() {\n if (this.#poisoned) {\n throw new PoisonedTransientOrderStatisticTreeError(this.#poisonCause);\n }\n }\n #assertMutable() {\n this.#assertHealthy();\n this.#edit.assertEditable();\n }\n #guard(operation) {\n try {\n return operation();\n }\n catch (error) {\n this.#poisoned = true;\n this.#poisonCause = error;\n throw error;\n }\n }\n get size() {\n this.#assertHealthy();\n return this.#root?.count ?? 0;\n }\n get measure() {\n this.#assertHealthy();\n if (this.#deferredMeasure && this.#pendingMeasureCount > 0) {\n throw new Error(\"Deferred tree measures must seal before they are read.\");\n }\n return this.#root?.measure ?? this.#context.measure.empty;\n }\n get(id) {\n this.#assertHealthy();\n return this.#byId.get(id);\n }\n entryAt(index) {\n this.#assertHealthy();\n return entryAtNode(this.#root, index);\n }\n rankOf(id) {\n this.#assertHealthy();\n return this.#guard(() => {\n const entry = this.#byId.get(id);\n if (entry === undefined && !this.#byId.has(id))\n return undefined;\n return rankOfNode(this.#root, entry, id, this.#context);\n });\n }\n range(start, end) {\n this.#assertHealthy();\n return rangeFromNode(this.#root, start, end);\n }\n insertOrReplace(entry) {\n this.#assertMutable();\n if (this.#measureFrames !== undefined) {\n throw new Error(\"Cannot insert after deferred measure sealing started.\");\n }\n return this.#guard(() => {\n const id = this.#context.getId(entry);\n const previous = this.#byId.get(id);\n const exists = previous !== undefined || this.#byId.has(id);\n if (exists && Object.is(previous, entry))\n return this;\n let root = this.#root;\n if (exists) {\n const removal = removeNode(root, previous, id, this.#context, this.#edit);\n if (!removal.changed)\n return this;\n root = removal.node;\n }\n root = insertNode(root, createNode(entry, id, this.#context, this.#edit), this.#context, this.#edit, this.#deferredMeasure);\n this.#root = root;\n this.#byId.set(id, entry);\n if (this.#deferredMeasure)\n this.#pendingMeasureCount = this.size;\n return this;\n });\n }\n remove(id) {\n this.#assertMutable();\n if (this.#deferredMeasure) {\n throw new Error(\"Deferred measure drafts do not support removal.\");\n }\n return this.#guard(() => {\n const entry = this.#byId.get(id);\n if (entry === undefined && !this.#byId.has(id))\n return this;\n const removal = removeNode(this.#root, entry, id, this.#context, this.#edit);\n if (!removal.changed)\n return this;\n this.#root = removal.node;\n this.#byId.delete(id);\n return this;\n });\n }\n freeze() {\n this.#assertHealthy();\n if (this.#deferredMeasure && this.#pendingMeasureCount > 0) {\n throw new Error(\"Deferred tree measures must seal before freezing.\");\n }\n if (this.#frozen !== undefined)\n return this.#frozen;\n this.#edit.freeze();\n this.#frozen = new PersistentOrderStatisticTree(this.#root, this.#byId.freeze(), this.#context);\n return this.#frozen;\n }\n entries() {\n this.#assertHealthy();\n return iterateTransientEntries(this.#root, () => this.#assertHealthy());\n }\n get pendingMeasureCount() {\n this.#assertHealthy();\n return this.#deferredMeasure ? this.#pendingMeasureCount : 0;\n }\n sealMeasureStep() {\n this.#assertMutable();\n if (!this.#deferredMeasure || this.#pendingMeasureCount === 0)\n return true;\n return this.#guard(() => {\n if (this.#measureFrames === undefined) {\n this.#measureFrames =\n this.#root === null ? [] : [{ node: this.#root, exit: false }];\n }\n for (;;) {\n const frame = this.#measureFrames.pop();\n if (frame.exit) {\n refreshDeferredNodeMeasure(frame.node, this.#context);\n break;\n }\n else {\n this.#measureFrames.push({ node: frame.node, exit: true });\n if (frame.node.right !== null) {\n this.#measureFrames.push({ node: frame.node.right, exit: false });\n }\n if (frame.node.left !== null) {\n this.#measureFrames.push({ node: frame.node.left, exit: false });\n }\n }\n }\n this.#pendingMeasureCount -= 1;\n return this.#pendingMeasureCount === 0;\n });\n }\n}\n/** Creates an empty persistent AVL order-statistic tree. */\nexport function createOrderStatisticTree(options) {\n const context = {\n getId: options.getId,\n compare: options.compare,\n measure: {\n empty: options.measure.empty,\n fromEntry: options.measure.fromEntry,\n combine: options.measure.combine,\n },\n };\n return new PersistentOrderStatisticTree(null, createPersistentMap(), context);\n}\n/** Internal bulk-build primitive; deliberately omitted from the package index. */\nexport function createDeferredMeasureTransientOrderStatisticTree(tree) {\n if (!(tree instanceof PersistentOrderStatisticTree)) {\n throw new TypeError(\"Deferred measure drafts require a tree created by this module.\");\n }\n return tree[createDeferredMeasureDraft]();\n}\n/** Internal bulk-build primitive; deliberately omitted from the package index. */\nexport function compareOrderStatisticTreeIds(left, right) {\n return compareIds(left, right);\n}\n/**\n * Internal bulk-build primitive; deliberately omitted from the package index.\n *\n * Builds a balanced tree in O(n) from `sorted`, which must be strictly\n * increasing under `like`'s total order (comparator, ties broken by ID).\n * Throws TypeError when adjacent entries compare `>= 0` — misordered input,\n * equal-compare entries with misordered IDs, and duplicate IDs alike — or\n * when `like` was not created by this module.\n *\n * `proof` lets an in-package caller trade a claim it can prove from its own\n * construction for work the builder would otherwise redo; see\n * {@link BulkBuildProof}. Omitting it keeps every check on.\n */\nexport function createOrderStatisticTreeFromSortedEntries(like, sorted, proof) {\n if (!(like instanceof PersistentOrderStatisticTree)) {\n throw new TypeError(\"Bulk builds require a tree created by this module.\");\n }\n return like[buildFromSortedEntries](sorted, proof);\n}\nexport function instrumentOrderStatisticTree(tree, instrumentation) {\n if (instrumentation === undefined)\n return tree;\n if (!(tree instanceof PersistentOrderStatisticTree)) {\n throw new TypeError(\"Instrumentation requires an order tree created by this module.\");\n }\n return tree[attachInstrumentation](instrumentation);\n}\nexport function instrumentMeasuredOrderStatisticTree(tree, instrumentation, beforeCombine) {\n if (!(tree instanceof PersistentOrderStatisticTree)) {\n throw new TypeError(\"Instrumentation requires an order tree created by this module.\");\n }\n return tree[attachInstrumentation](instrumentation, beforeCombine);\n}\nfunction inspectNode(node) {\n if (node === null) {\n return { snapshot: null, balanced: true, count: 0, height: 0 };\n }\n const left = inspectNode(node.left);\n const right = inspectNode(node.right);\n const count = left.count + 1 + right.count;\n const height = 1 + Math.max(left.height, right.height);\n const balance = left.height - right.height;\n const snapshot = Object.freeze({\n id: node.id,\n count: node.count,\n height: node.height,\n balance,\n left: left.snapshot,\n right: right.snapshot,\n });\n return {\n snapshot,\n balanced: left.balanced &&\n right.balanced &&\n Math.abs(balance) <= 1 &&\n node.count === count &&\n node.height === height,\n count,\n height,\n };\n}\nfunction collectNodes(node, result) {\n if (node === null)\n return;\n result.add(node);\n collectNodes(node.left, result);\n collectNodes(node.right, result);\n}\nfunction countSharedNodes(node, candidates) {\n if (node === null)\n return 0;\n return ((candidates.has(node) ? 1 : 0) +\n countSharedNodes(node.left, candidates) +\n countSharedNodes(node.right, candidates));\n}\nexport function getOrderStatisticTreeDiagnosticsForTesting(tree, comparedWith) {\n if (!persistentRoots.has(tree)) {\n throw new TypeError(\"Diagnostics require a tree created by this module.\");\n }\n const root = persistentRoots.get(tree);\n const inspected = inspectNode(root);\n let sharedNodeCount = 0;\n if (comparedWith !== undefined) {\n if (!persistentRoots.has(comparedWith)) {\n throw new TypeError(\"Diagnostics require a tree created by this module.\");\n }\n const comparedRoot = persistentRoots.get(comparedWith);\n const candidates = new Set();\n collectNodes(comparedRoot, candidates);\n sharedNodeCount = countSharedNodes(root, candidates);\n }\n return Object.freeze({\n count: inspected.count,\n height: inspected.height,\n balanced: inspected.balanced,\n sharedNodeCount,\n root: inspected.snapshot,\n });\n}\n","/**\n * Immutable chunked slot-indexed vector: a chunk table over\n * `SLOT_VECTOR_CHUNK`-element chunks, copy-on-write per commit. A commit\n * touching k slots copies the table plus each touched chunk once — this is\n * what keeps old snapshots valid under slot reuse: every revision holds its\n * own table, so revision N still binds slot s to whatever row owned s at\n * revision N no matter what later commits do (M0 priced maintenance at\n * ~33–98µs per 100-write commit).\n *\n * Holes (`undefined`) are free slots. Iteration hole-skips, which is why no\n * separate \"live\" bitset exists (recorded plan deviation from the spec).\n */\nexport const SLOT_VECTOR_CHUNK = 1024;\nconst EMPTY = Object.freeze({ chunks: Object.freeze([]) });\nexport function emptySlotVector() {\n return EMPTY;\n}\nexport function slotVectorFromEntries(entries, capacity) {\n const tableSize = Math.ceil(capacity / SLOT_VECTOR_CHUNK);\n const limit = tableSize * SLOT_VECTOR_CHUNK;\n const chunks = new Array(tableSize);\n for (const [slot, value] of entries) {\n if (slot >= limit) {\n throw new RangeError(`Slot ${slot} is beyond capacity ${capacity}.`);\n }\n const index = (slot / SLOT_VECTOR_CHUNK) | 0;\n let chunk = chunks[index];\n if (chunk === undefined) {\n chunk = new Array(SLOT_VECTOR_CHUNK);\n chunks[index] = chunk;\n }\n chunk[slot % SLOT_VECTOR_CHUNK] = value;\n }\n return { chunks };\n}\nexport function slotVectorGet(vector, slot) {\n const chunk = vector.chunks[(slot / SLOT_VECTOR_CHUNK) | 0];\n return chunk === undefined ? undefined : chunk[slot % SLOT_VECTOR_CHUNK];\n}\n/**\n * One commit's writes (`undefined` value = clear the slot), COW: table copied\n * once, each touched chunk copied once. `capacity` may exceed the old\n * table's reach (allocator growth).\n *\n * `chunksTouched` counts every chunk this commit allocated or copied,\n * including a brand-new chunk created for a hole beyond the old table — that\n * counts as touched even though nothing was copied.\n */\nexport function slotVectorWithAll(vector, writes, capacity) {\n const tableSize = Math.max(vector.chunks.length, Math.ceil(capacity / SLOT_VECTOR_CHUNK));\n const limit = tableSize * SLOT_VECTOR_CHUNK;\n const chunks = new Array(tableSize);\n for (let i = 0; i < vector.chunks.length; i += 1)\n chunks[i] = vector.chunks[i];\n let chunksTouched = 0;\n for (const [slot, value] of writes) {\n if (slot >= limit) {\n throw new RangeError(`Slot ${slot} is beyond capacity ${capacity}.`);\n }\n const index = (slot / SLOT_VECTOR_CHUNK) | 0;\n // A chunk still equal to the base's (or absent) hasn't been copied for\n // this commit yet; after copy/create it is a fresh object, so identity\n // alone tells touched from untouched with no separate tracking set.\n if (chunks[index] === undefined || chunks[index] === vector.chunks[index]) {\n const existing = chunks[index];\n chunks[index] =\n existing === undefined\n ? new Array(SLOT_VECTOR_CHUNK)\n : existing.slice();\n chunksTouched += 1;\n }\n chunks[index][slot % SLOT_VECTOR_CHUNK] = value;\n }\n return { next: { chunks }, chunksTouched };\n}\n/** Hole-skipping walk in slot order. */\nexport function forEachSlotEntry(vector, callback) {\n for (let index = 0; index < vector.chunks.length; index += 1) {\n const chunk = vector.chunks[index];\n if (chunk === undefined)\n continue;\n const base = index * SLOT_VECTOR_CHUNK;\n for (let offset = 0; offset < chunk.length; offset += 1) {\n const value = chunk[offset];\n if (value !== undefined)\n callback(value, base + offset);\n }\n }\n}\n","import { sortKeysOf } from \"./compiled-query\";\n/**\n * Standalone module because both visible-index and group-index need it and\n * visible-index already imports group-index — either home would cycle.\n *\n * Decorates a record for tree residence: ONE store get, at insert time. The\n * record must already be evaluated (or swap-filled) under `queryPlan` —\n * `sortKeysOf` throws otherwise, which is the fail-loud contract. Entry keys\n * stay valid for the tree's lifetime because a tree is bound to one plan\n * (the A2 rebuild-or-reseed invariant) and row updates replace the entry.\n */\nexport function orderedRowEntry(queryPlan, record) {\n return Object.freeze({\n record,\n keys: sortKeysOf(queryPlan, record),\n });\n}\n","import { createDeferredMeasureTransientOrderStatisticTree, createOrderStatisticTree, instrumentMeasuredOrderStatisticTree, } from \"./order-statistic-tree\";\nconst attachInstrumentation = Symbol(\"attachAggregateInstrumentation\");\nconst createDeferredMeasureDraft = Symbol(\"createDeferredMeasureDraft\");\nconst DEVELOPMENT = process.env.NODE_ENV !== \"production\";\nexport function isScalarBuiltinAggregator(aggregator) {\n return aggregator === \"sum\" || aggregator === \"avg\" || aggregator === \"count\";\n}\nfunction aggregatableNumber(value) {\n return typeof value === \"number\" && !Number.isNaN(value);\n}\n// BigInt is a runtime requirement for exact sum/average accumulation, but\n// literal syntax (`1n`) is newer than the public package's ES2018 grammar\n// contract. Constructor calls preserve the arithmetic while allowing older\n// parsers and bundlers to load the package; consumers still need BigInt support\n// (native or polyfilled) at runtime.\nconst BIGINT_ZERO = BigInt(0);\nconst BIGINT_ONE = BigInt(1);\nconst BIGINT_TWO = BigInt(2);\nconst FRACTION_BITS = BigInt(52);\nconst FRACTION_MASK = (BIGINT_ONE << FRACTION_BITS) - BIGINT_ONE;\nconst IMPLICIT_BIT = BIGINT_ONE << FRACTION_BITS;\nconst SIGN_BIT = BIGINT_ONE << BigInt(63);\nconst MAX_FINITE_UNITS = ((BIGINT_ONE << BigInt(53)) - BIGINT_ONE) << BigInt(2045);\nconst OVERFLOW_THRESHOLD_UNITS = MAX_FINITE_UNITS + (BIGINT_ONE << BigInt(2044));\nconst BINARY64_VIEW = new DataView(new ArrayBuffer(8));\nfunction finiteNumberUnits(value) {\n BINARY64_VIEW.setFloat64(0, value);\n const bits = BINARY64_VIEW.getBigUint64(0);\n const negative = (bits & SIGN_BIT) !== BIGINT_ZERO;\n const exponent = Number((bits >> FRACTION_BITS) & BigInt(0x7ff));\n const fraction = bits & FRACTION_MASK;\n const magnitude = exponent === 0\n ? fraction\n : (IMPLICIT_BIT + fraction) << BigInt(exponent - 1);\n return negative ? -magnitude : magnitude;\n}\nfunction roundDivideEven(numerator, denominator) {\n const quotient = numerator / denominator;\n const remainder = numerator % denominator;\n const comparison = remainder * BIGINT_TWO - denominator;\n return comparison > BIGINT_ZERO ||\n (comparison === BIGINT_ZERO && (quotient & BIGINT_ONE) === BIGINT_ONE)\n ? quotient + BIGINT_ONE\n : quotient;\n}\nfunction bitLength(value) {\n return value.toString(2).length;\n}\nfunction floorLog2Ratio(numerator, denominator) {\n let exponent = bitLength(numerator) - bitLength(denominator);\n const belowCandidate = exponent >= 0\n ? numerator < denominator << BigInt(exponent)\n : numerator << BigInt(-exponent) < denominator;\n if (belowCandidate)\n exponent -= 1;\n return exponent;\n}\nfunction numberFromBits(bits) {\n BINARY64_VIEW.setBigUint64(0, bits);\n return BINARY64_VIEW.getFloat64(0);\n}\n/** Rounds an exact `(units / divisor) * 2^-1074` rational once to binary64. */\nfunction roundedUnits(units, divisor = BIGINT_ONE) {\n if (units === BIGINT_ZERO)\n return 0;\n const negative = units < BIGINT_ZERO;\n const magnitude = negative ? -units : units;\n if (magnitude >= OVERFLOW_THRESHOLD_UNITS * divisor) {\n return negative ? -Infinity : Infinity;\n }\n const exponent = floorLog2Ratio(magnitude, divisor);\n let shift = Math.max(0, exponent - 52);\n let significand = roundDivideEven(magnitude, divisor << BigInt(shift));\n if (significand >= BIGINT_ONE << BigInt(53)) {\n significand >>= BIGINT_ONE;\n shift += 1;\n }\n const sign = negative ? SIGN_BIT : BIGINT_ZERO;\n if (significand < IMPLICIT_BIT) {\n return numberFromBits(sign | significand);\n }\n const exponentBits = BigInt(shift + 1);\n return numberFromBits(sign | (exponentBits << FRACTION_BITS) | (significand - IMPLICIT_BIT));\n}\nfunction emptySumAccumulator() {\n return {\n finiteUnits: BIGINT_ZERO,\n count: 0,\n positiveInfinity: false,\n negativeInfinity: false,\n };\n}\nfunction accumulateSum(accumulator, value) {\n if (!aggregatableNumber(value))\n return accumulator;\n return {\n finiteUnits: Number.isFinite(value)\n ? accumulator.finiteUnits + finiteNumberUnits(value)\n : accumulator.finiteUnits,\n count: accumulator.count + 1,\n positiveInfinity: accumulator.positiveInfinity || value === Infinity,\n negativeInfinity: accumulator.negativeInfinity || value === -Infinity,\n };\n}\nfunction mergeSums(left, right) {\n return {\n finiteUnits: left.finiteUnits + right.finiteUnits,\n count: left.count + right.count,\n positiveInfinity: left.positiveInfinity || right.positiveInfinity,\n negativeInfinity: left.negativeInfinity || right.negativeInfinity,\n };\n}\nfunction finalizedSum(accumulator, average) {\n if (accumulator.count === 0)\n return null;\n if (accumulator.positiveInfinity && accumulator.negativeInfinity)\n return NaN;\n if (accumulator.positiveInfinity)\n return Infinity;\n if (accumulator.negativeInfinity)\n return -Infinity;\n return roundedUnits(accumulator.finiteUnits, average ? BigInt(accumulator.count) : BIGINT_ONE);\n}\nconst sum = {\n init: emptySumAccumulator,\n accumulate: accumulateSum,\n merge: mergeSums,\n finalize: (accumulator) => finalizedSum(accumulator, false),\n};\nconst avg = {\n init: sum.init,\n accumulate: sum.accumulate,\n merge: sum.merge,\n finalize: (accumulator) => finalizedSum(accumulator, true),\n};\nfunction extremum(kind) {\n return {\n init: () => ({ value: null }),\n accumulate(accumulator, value) {\n if (!aggregatableNumber(value))\n return accumulator;\n if (accumulator.value === null)\n return { value };\n return {\n value: kind === \"min\"\n ? value < accumulator.value\n ? value\n : accumulator.value\n : value > accumulator.value\n ? value\n : accumulator.value,\n };\n },\n merge(left, right) {\n if (left.value === null)\n return right;\n if (right.value === null)\n return left;\n return {\n value: kind === \"min\"\n ? right.value < left.value\n ? right.value\n : left.value\n : right.value > left.value\n ? right.value\n : left.value,\n };\n },\n finalize: (accumulator) => accumulator.value,\n };\n}\nconst count = {\n init: () => ({ count: 0 }),\n accumulate: (accumulator) => ({ count: accumulator.count + 1 }),\n merge: (left, right) => ({ count: left.count + right.count }),\n finalize: (accumulator) => accumulator.count === 0 ? null : accumulator.count,\n};\n/**\n * Pure, persistent-safe built-in monoids. Numeric admission, empty output, and\n * ordered extrema match the legacy grid. Sum and average intentionally use an\n * exact binary64 superaccumulator so cached merges are genuinely associative;\n * they round only once when finalized rather than reproducing history-dependent\n * floating-point folds.\n */\nexport const aggregateTreeBuiltinAggregators = Object.freeze({\n sum,\n avg,\n min: extremum(\"min\"),\n max: extremum(\"max\"),\n count,\n});\nfunction sameLeaf(left, right) {\n return (Object.is(left.row, right.row) &&\n Object.is(left.value, right.value) &&\n Object.is(left.dependency, right.dependency));\n}\nfunction normalizedLeaf(leaf) {\n // A frozen leaf with exactly the four data properties IS the canonical\n // shape (compiled queries freeze their leaves at construction); copying it\n // again on every insert was ~157ms of allocation + GC at 50k rows × 10\n // aggregated columns (#500 cycle 2 decision 3).\n if (Object.isFrozen(leaf) && Reflect.ownKeys(leaf).length === 4)\n return leaf;\n return Object.freeze({\n id: leaf.id,\n row: leaf.row,\n value: leaf.value,\n dependency: leaf.dependency,\n });\n}\nfunction containsSharedMemory(value, seen = new Set()) {\n if (value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")) {\n return false;\n }\n if (typeof SharedArrayBuffer !== \"undefined\" &&\n value instanceof SharedArrayBuffer) {\n return true;\n }\n if (seen.has(value))\n return false;\n seen.add(value);\n if (ArrayBuffer.isView(value) && containsSharedMemory(value.buffer, seen)) {\n return true;\n }\n if (value instanceof Map) {\n for (const [key, entry] of value) {\n if (containsSharedMemory(key, seen) ||\n containsSharedMemory(entry, seen)) {\n return true;\n }\n }\n }\n if (value instanceof Set) {\n for (const entry of value) {\n if (containsSharedMemory(entry, seen))\n return true;\n }\n }\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor !== undefined &&\n \"value\" in descriptor &&\n containsSharedMemory(descriptor.value, seen)) {\n return true;\n }\n }\n return false;\n}\nfunction finalizedValue(accumulator, aggregator, cache, custom, snapshotAccumulator) {\n if (!Object.is(cache.accumulator, accumulator)) {\n throw new Error(\"Aggregate finalization cache does not match its root.\");\n }\n if (!cache.ready) {\n let finalizedAccumulator = accumulator;\n if (custom &&\n accumulator !== null &&\n (typeof accumulator === \"object\" || typeof accumulator === \"function\")) {\n if (snapshotAccumulator !== undefined) {\n finalizedAccumulator = snapshotAccumulator(accumulator);\n if (Object.is(finalizedAccumulator, accumulator)) {\n throw new TypeError(\"snapshotAccumulator must return a detached accumulator.\");\n }\n }\n else {\n try {\n finalizedAccumulator = structuredClone(accumulator);\n }\n catch (error) {\n throw new TypeError(\"Custom aggregator accumulators must be structured-cloneable or provide snapshotAccumulator.\", { cause: error });\n }\n }\n if (containsSharedMemory(finalizedAccumulator)) {\n throw new TypeError(\"Finalized accumulator snapshots cannot contain SharedArrayBuffer-backed memory; provide snapshotAccumulator that copies it into detached storage.\");\n }\n }\n cache.output = aggregator.finalize(finalizedAccumulator);\n cache.ready = true;\n }\n return cache.output;\n}\nclass PersistentAggregateTree {\n #tree;\n #context;\n #cache;\n constructor(tree, context, cache) {\n this.#tree = tree;\n this.#context = context;\n this.#cache =\n cache !== undefined && Object.is(cache.accumulator, tree.measure)\n ? cache\n : { accumulator: tree.measure, ready: false };\n }\n get size() {\n return this.#tree.size;\n }\n firstId() {\n return this.#tree.entryAt(0)?.id;\n }\n insertOrReplace(leaf) {\n const previous = this.#tree.get(leaf.id);\n if (previous !== undefined && sameLeaf(previous, leaf))\n return this;\n const nextTree = this.#tree.insertOrReplace(normalizedLeaf(leaf));\n if (nextTree === this.#tree)\n return this;\n if (this.#context.custom) {\n this.#context.lawValidator?.observe({\n aggregator: this.#context.aggregator,\n columnId: this.#context.columnId,\n leafId: leaf.id,\n row: leaf.row,\n value: leaf.value,\n });\n }\n return new PersistentAggregateTree(nextTree, this.#context, this.#cache);\n }\n remove(id) {\n const nextTree = this.#tree.remove(id);\n return nextTree === this.#tree\n ? this\n : new PersistentAggregateTree(nextTree, this.#context, this.#cache);\n }\n finalize() {\n return finalizedValue(this.#tree.measure, this.#context.aggregator, this.#cache, this.#context.custom, this.#context.snapshotAccumulator);\n }\n asTransient() {\n return new TransientAggregateTreeImpl(this.#tree.asTransient(), this.#context, this.#cache);\n }\n [createDeferredMeasureDraft]() {\n return new TransientAggregateTreeImpl(createDeferredMeasureTransientOrderStatisticTree(this.#tree), this.#context, this.#cache);\n }\n [attachInstrumentation](instrumentation) {\n if (this.#context.instrumentation === instrumentation)\n return this;\n const tree = instrumentMeasuredOrderStatisticTree(this.#tree, instrumentation, () => {\n instrumentation.work.aggregateMerges += 1;\n });\n return new PersistentAggregateTree(tree, { ...this.#context, instrumentation }, this.#cache);\n }\n}\nclass TransientAggregateTreeImpl {\n #tree;\n #context;\n #cache;\n #frozen;\n constructor(tree, context, cache) {\n this.#tree = tree;\n this.#context = context;\n this.#cache = cache;\n }\n get size() {\n return this.#tree.size;\n }\n firstId() {\n return this.#tree.entryAt(0)?.id;\n }\n insertOrReplace(leaf) {\n const previous = this.#tree.get(leaf.id);\n if (previous !== undefined && sameLeaf(previous, leaf)) {\n this.#tree.insertOrReplace(previous);\n return this;\n }\n this.#tree.insertOrReplace(normalizedLeaf(leaf));\n if (this.#context.custom) {\n this.#context.lawValidator?.observe({\n aggregator: this.#context.aggregator,\n columnId: this.#context.columnId,\n leafId: leaf.id,\n row: leaf.row,\n value: leaf.value,\n });\n }\n return this;\n }\n remove(id) {\n this.#tree.remove(id);\n return this;\n }\n finalize() {\n const accumulator = this.#tree.measure;\n if (!Object.is(this.#cache.accumulator, accumulator)) {\n this.#cache = { accumulator, ready: false };\n }\n return finalizedValue(accumulator, this.#context.aggregator, this.#cache, this.#context.custom, this.#context.snapshotAccumulator);\n }\n freeze() {\n if (this.#frozen !== undefined)\n return this.#frozen;\n const tree = this.#tree.freeze();\n this.#frozen = new PersistentAggregateTree(tree, this.#context, this.#cache);\n return this.#frozen;\n }\n get pendingMeasureCount() {\n return \"pendingMeasureCount\" in this.#tree\n ? this.#tree.pendingMeasureCount\n : 0;\n }\n sealMeasureStep() {\n if (!(\"sealMeasureStep\" in this.#tree))\n return true;\n return this.#tree.sealMeasureStep();\n }\n}\nconst EMPTY_SCALAR_STATE = Object.freeze({\n size: 0,\n admitted: 0,\n finiteUnits: BIGINT_ZERO,\n positiveInfinities: 0,\n negativeInfinities: 0,\n});\nfunction scalarStateWith(state, value, direction) {\n // Admission is applied SYMMETRICALLY: a value the insert did not\n // accumulate (NaN, null, non-number) must not be subtracted on remove.\n if (!aggregatableNumber(value)) {\n return { ...state, size: state.size + direction };\n }\n return {\n size: state.size + direction,\n admitted: state.admitted + direction,\n finiteUnits: Number.isFinite(value)\n ? direction === 1\n ? state.finiteUnits + finiteNumberUnits(value)\n : state.finiteUnits - finiteNumberUnits(value)\n : state.finiteUnits,\n positiveInfinities: state.positiveInfinities + (value === Infinity ? direction : 0),\n negativeInfinities: state.negativeInfinities + (value === -Infinity ? direction : 0),\n };\n}\nfunction finalizeScalarState(kind, state) {\n if (kind === \"count\")\n return state.size === 0 ? null : state.size;\n if (state.admitted === 0)\n return null;\n if (state.positiveInfinities > 0 && state.negativeInfinities > 0)\n return NaN;\n if (state.positiveInfinities > 0)\n return Infinity;\n if (state.negativeInfinities > 0)\n return -Infinity;\n return roundedUnits(state.finiteUnits, kind === \"avg\" ? BigInt(state.admitted) : BIGINT_ONE);\n}\nfunction requireRemovedLeaf(columnId, state, removedLeaf) {\n if (removedLeaf === undefined) {\n throw new TypeError(`Scalar aggregate cell for column ${columnId} needs the originally-inserted leaf to remove a row.`);\n }\n if (state.size === 0) {\n throw new Error(`Scalar aggregate cell for column ${columnId} removed a row it never inserted.`);\n }\n return removedLeaf;\n}\n/**\n * O(1) accumulator cell for `sum`/`avg`/`count` behind the aggregate-root\n * interface (#500 cycle 2 decision A): insert accumulates inline, remove\n * applies the exact inverse from the originally-inserted leaf, and there is\n * no per-row structure at all — so no seal work and no `firstId` (its only\n * consumer is custom-finalizer error context, and customs keep the tree).\n */\nclass ScalarAggregateCell {\n #kind;\n #columnId;\n #state;\n #output = null;\n #finalized = false;\n constructor(kind, columnId, state) {\n this.#kind = kind;\n this.#columnId = columnId;\n this.#state = state;\n }\n get size() {\n return this.#state.size;\n }\n firstId() {\n return undefined;\n }\n insertOrReplace(leaf) {\n return new ScalarAggregateCell(this.#kind, this.#columnId, scalarStateWith(this.#state, leaf.value, 1));\n }\n remove(id, removedLeaf) {\n void id;\n const leaf = requireRemovedLeaf(this.#columnId, this.#state, removedLeaf);\n return new ScalarAggregateCell(this.#kind, this.#columnId, scalarStateWith(this.#state, leaf.value, -1));\n }\n finalize() {\n if (!this.#finalized) {\n this.#output = finalizeScalarState(this.#kind, this.#state);\n this.#finalized = true;\n }\n return this.#output;\n }\n asTransient() {\n return new TransientScalarAggregateCell(this.#kind, this.#columnId, this.#state);\n }\n}\n/**\n * The mutable draft counterpart. It satisfies the deferred-measure draft\n * surface with a permanently-empty measure queue: scalar cells accumulate at\n * insert, so they charge NO seal units (#500 cycle 2).\n */\nclass TransientScalarAggregateCell {\n #kind;\n #columnId;\n #state;\n #frozen;\n constructor(kind, columnId, state) {\n this.#kind = kind;\n this.#columnId = columnId;\n this.#state = state;\n }\n get size() {\n return this.#state.size;\n }\n firstId() {\n return undefined;\n }\n #assertMutable() {\n if (this.#frozen !== undefined) {\n throw new Error(`Scalar aggregate cell draft for column ${this.#columnId} is frozen.`);\n }\n }\n insertOrReplace(leaf) {\n this.#assertMutable();\n this.#state = scalarStateWith(this.#state, leaf.value, 1);\n return this;\n }\n remove(id, removedLeaf) {\n void id;\n this.#assertMutable();\n const leaf = requireRemovedLeaf(this.#columnId, this.#state, removedLeaf);\n this.#state = scalarStateWith(this.#state, leaf.value, -1);\n return this;\n }\n finalize() {\n return finalizeScalarState(this.#kind, this.#state);\n }\n freeze() {\n this.#frozen ??= new ScalarAggregateCell(this.#kind, this.#columnId, this.#state);\n return this.#frozen;\n }\n get pendingMeasureCount() {\n return 0;\n }\n sealMeasureStep() {\n return true;\n }\n}\nexport function createScalarAggregateCell(options) {\n return new ScalarAggregateCell(options.aggregator, options.columnId, EMPTY_SCALAR_STATE);\n}\nexport function isScalarAggregateCell(value) {\n return (value instanceof ScalarAggregateCell ||\n value instanceof TransientScalarAggregateCell);\n}\n/** Internal bulk-build primitive; deliberately omitted from the package index. */\nexport function createDeferredMeasureTransientAggregateTree(tree) {\n if (!(tree instanceof PersistentAggregateTree)) {\n throw new TypeError(\"Deferred measure drafts require an aggregate tree created by this module.\");\n }\n return tree[createDeferredMeasureDraft]();\n}\nexport function createAggregateTree(options) {\n const custom = typeof options.aggregator !== \"string\";\n const aggregator = (custom\n ? options.aggregator\n : aggregateTreeBuiltinAggregators[options.aggregator]);\n const context = {\n columnId: options.columnId,\n aggregator,\n lawValidator: DEVELOPMENT && custom\n ? options.lawValidator\n : undefined,\n snapshotAccumulator: custom\n ? (options.snapshotAccumulator ?? aggregator.snapshotAccumulator)\n : undefined,\n custom,\n };\n const tree = createOrderStatisticTree({\n getId: (leaf) => leaf.id,\n compare: options.compare ?? (() => 0),\n measure: {\n empty: aggregator.init(),\n fromEntry: (leaf) => aggregator.accumulate(aggregator.init(), leaf.value, leaf.row),\n combine: aggregator.merge,\n },\n });\n return new PersistentAggregateTree(tree, context);\n}\nexport function instrumentAggregateTree(tree, instrumentation) {\n if (instrumentation === undefined)\n return tree;\n // Scalar cells do no tree merges — nothing to instrument.\n if (tree instanceof ScalarAggregateCell)\n return tree;\n if (!(tree instanceof PersistentAggregateTree)) {\n throw new TypeError(\"Instrumentation requires an aggregate tree created by this module.\");\n }\n return tree[attachInstrumentation](instrumentation);\n}\n","import { compareWithSortKeys, filterVerdict, } from \"./compiled-query\";\nimport { PretableInvalidGroupKeyError, PretableRowModelError, } from \"./errors\";\nimport { orderedRowEntry } from \"./ordered-row-entry\";\nimport { createAggregateTree, createDeferredMeasureTransientAggregateTree, createScalarAggregateCell, instrumentAggregateTree, isScalarBuiltinAggregator, } from \"./persistent/aggregate-tree\";\nimport { createOrderStatisticTree, instrumentOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { createPersistentMap, instrumentPersistentMap, } from \"./persistent/persistent-map\";\nconst visibleRangeDiagnostics = new WeakMap();\nexport function getVisibleRangeDiagnosticsForTesting(range) {\n const diagnostics = visibleRangeDiagnostics.get(range);\n if (diagnostics === undefined) {\n throw new TypeError(\"Diagnostics require a grouped visible range.\");\n }\n return diagnostics;\n}\nconst EMPTY_COUNTS = Object.freeze({\n collapsed: 0,\n expanded: 0,\n throughDepth: Object.freeze([]),\n data: 0,\n dataCollapsed: 0,\n dataExpanded: 0,\n dataThroughDepth: Object.freeze([]),\n});\nconst groupIndexInstrumentation = new WeakMap();\nconst groupedIndex = Symbol(\"pretable.grouped-index\");\n/**\n * The grouped half of the filter-verdict seam (see `./filter-membership`,\n * which owns the seam's documentation and re-exports this). It lives here\n * because it reads this module's internal invariant: EVERY inserted row gets\n * a `rowParents` entry, but only a PASSING row is inserted into its leaf\n * group's `leaves` tree — so leaf membership is the stored verdict, and a row\n * this index never saw is simply not a member.\n */\nexport function rowPassesFilterInGroupIndex(grouped, rowId) {\n const parentGroupId = grouped.rowParents.get(rowId);\n if (parentGroupId === undefined)\n return false;\n return grouped.groups.get(parentGroupId)?.leaves.get(rowId) !== undefined;\n}\nexport function getGroupIndex(visible) {\n return visible[groupedIndex];\n}\nexport function attachGroupIndex(rows, groups) {\n return Object.freeze({ rows, [groupedIndex]: groups });\n}\nfunction escape(raw) {\n return raw.replace(/%/g, \"%25\").replace(/\\//g, \"%2F\").replace(/=/g, \"%3D\");\n}\n/** Canonical equality/identity key. Null and undefined intentionally share the legacy blank group. */\nexport function encodeGroupValue(value, context) {\n if (value === null || value === undefined)\n return \"~\";\n if (typeof value === \"string\")\n return `s:${value}`;\n if (typeof value === \"number\") {\n if (Number.isNaN(value))\n return \"n:NaN\";\n if (Object.is(value, -0))\n return \"n:-0\";\n return `n:${String(value)}`;\n }\n if (typeof value === \"boolean\")\n return `b:${String(value)}`;\n if (typeof value === \"bigint\")\n return `i:${String(value)}`;\n throw new PretableInvalidGroupKeyError(context?.operation ?? \"set-query\", context?.rowId, context?.columnId ?? \"<unknown>\", value);\n}\nexport function makeGroupId(path) {\n return `__group__:${path\n .map((entry) => `${escape(entry.columnId)}=${escape(encodeGroupValue(entry.value))}`)\n .join(\"/\")}`;\n}\nfunction combineCounts(left, right) {\n const length = Math.max(left.throughDepth.length, right.throughDepth.length);\n const throughDepth = Array.from({ length }, (_, index) => (left.throughDepth[index] ?? 0) + (right.throughDepth[index] ?? 0));\n const dataLength = Math.max(left.dataThroughDepth.length, right.dataThroughDepth.length);\n return Object.freeze({\n collapsed: left.collapsed + right.collapsed,\n expanded: left.expanded + right.expanded,\n throughDepth: Object.freeze(throughDepth),\n data: left.data + right.data,\n dataCollapsed: left.dataCollapsed + right.dataCollapsed,\n dataExpanded: left.dataExpanded + right.dataExpanded,\n dataThroughDepth: Object.freeze(Array.from({ length: dataLength }, (_, index) => (left.dataThroughDepth[index] ?? 0) +\n (right.dataThroughDepth[index] ?? 0))),\n });\n}\nfunction groupCounts(depth, levelCount, override, descendants) {\n const count = (expanded, descendant) => (override ?? expanded) ? 1 + descendant : 1;\n return Object.freeze({\n collapsed: count(false, descendants.collapsed),\n expanded: count(true, descendants.expanded),\n throughDepth: Object.freeze(Array.from({ length: levelCount }, (_, policyDepth) => count(depth <= policyDepth, descendants.throughDepth[policyDepth] ?? 0))),\n data: descendants.data,\n dataCollapsed: (override ?? false) ? descendants.dataCollapsed : 0,\n dataExpanded: (override ?? true) ? descendants.dataExpanded : 0,\n dataThroughDepth: Object.freeze(Array.from({ length: levelCount }, (_, policyDepth) => (override ?? depth <= policyDepth)\n ? (descendants.dataThroughDepth[policyDepth] ?? 0)\n : 0)),\n });\n}\nfunction dataCountForPolicy(counts, policy) {\n if (policy.kind === \"expanded\")\n return counts.dataExpanded;\n if (policy.kind === \"collapsed\")\n return counts.dataCollapsed;\n if (policy.depth < 0)\n return counts.dataCollapsed;\n return (counts.dataThroughDepth[Math.min(policy.depth, counts.dataThroughDepth.length - 1)] ?? counts.dataExpanded);\n}\nfunction countForPolicy(counts, policy) {\n if (policy.kind === \"expanded\")\n return counts.expanded;\n if (policy.kind === \"collapsed\")\n return counts.collapsed;\n if (policy.depth < 0)\n return counts.collapsed;\n return (counts.throughDepth[Math.min(policy.depth, counts.throughDepth.length - 1)] ?? counts.expanded);\n}\nfunction measuredHeight(node) {\n return node?.height ?? 0;\n}\nfunction measuredNode(entry, left, right, instrumentation) {\n if (instrumentation !== undefined)\n instrumentation.work.groupNodesCopied += 1;\n return Object.freeze({\n entry,\n left,\n right,\n height: 1 + Math.max(measuredHeight(left), measuredHeight(right)),\n size: (left?.size ?? 0) + 1 + (right?.size ?? 0),\n measure: combineCounts(combineCounts(left?.measure ?? EMPTY_COUNTS, entry.counts), right?.measure ?? EMPTY_COUNTS),\n });\n}\nfunction measuredBalance(node, instrumentation) {\n const factor = measuredHeight(node.left) - measuredHeight(node.right);\n if (factor > 1) {\n let left = node.left;\n if (measuredHeight(left.left) < measuredHeight(left.right)) {\n const pivot = left.right;\n left = measuredNode(pivot.entry, measuredNode(left.entry, left.left, pivot.left, instrumentation), pivot.right, instrumentation);\n }\n return measuredNode(left.entry, left.left, measuredNode(node.entry, left.right, node.right, instrumentation), instrumentation);\n }\n if (factor < -1) {\n let right = node.right;\n if (measuredHeight(right.right) < measuredHeight(right.left)) {\n const pivot = right.left;\n right = measuredNode(pivot.entry, pivot.left, measuredNode(right.entry, pivot.right, right.right, instrumentation), instrumentation);\n }\n return measuredNode(right.entry, measuredNode(node.entry, node.left, right.left, instrumentation), right.right, instrumentation);\n }\n return measuredNode(node.entry, node.left, node.right, instrumentation);\n}\nfunction compareGroupIds(left, right) {\n return left === right ? 0 : left < right ? -1 : 1;\n}\nclass PersistentMeasuredGroupTree {\n #root;\n #byId;\n #compare;\n #instrumentation;\n constructor(root, byId, compare, instrumentation) {\n this.#root = root;\n this.#byId = byId;\n this.#compare = compare;\n this.#instrumentation = instrumentation;\n }\n get size() {\n return this.#root?.size ?? 0;\n }\n get measure() {\n return this.#root?.measure ?? EMPTY_COUNTS;\n }\n withInstrumentation(instrumentation) {\n if (instrumentation === this.#instrumentation)\n return this;\n return new PersistentMeasuredGroupTree(this.#root, instrumentPersistentMap(this.#byId, instrumentation), this.#compare, instrumentation);\n }\n get(groupId) {\n return this.#byId.get(groupId);\n }\n #compareEntries(left, right) {\n const result = this.#compare(left, right);\n return result < 0\n ? -1\n : result > 0\n ? 1\n : compareGroupIds(left.groupId, right.groupId);\n }\n #insert(root, entry) {\n if (root === null)\n return measuredNode(entry, null, null, this.#instrumentation);\n const comparison = this.#compareEntries(entry, root.entry);\n return comparison < 0\n ? measuredBalance(measuredNode(root.entry, this.#insert(root.left, entry), root.right, this.#instrumentation), this.#instrumentation)\n : measuredBalance(measuredNode(root.entry, root.left, this.#insert(root.right, entry), this.#instrumentation), this.#instrumentation);\n }\n #extractMinimum(root) {\n if (root.left === null)\n return [root, root.right];\n const [minimum, left] = this.#extractMinimum(root.left);\n return [\n minimum,\n measuredBalance(measuredNode(root.entry, left, root.right, this.#instrumentation), this.#instrumentation),\n ];\n }\n #remove(root, entry) {\n if (root === null)\n return null;\n const comparison = this.#compareEntries(entry, root.entry);\n if (comparison < 0)\n return measuredBalance(measuredNode(root.entry, this.#remove(root.left, entry), root.right, this.#instrumentation), this.#instrumentation);\n if (comparison > 0)\n return measuredBalance(measuredNode(root.entry, root.left, this.#remove(root.right, entry), this.#instrumentation), this.#instrumentation);\n if (root.left === null)\n return root.right;\n if (root.right === null)\n return root.left;\n const [minimum, right] = this.#extractMinimum(root.right);\n return measuredBalance(measuredNode(minimum.entry, root.left, right, this.#instrumentation), this.#instrumentation);\n }\n insertOrReplace(entry) {\n const previous = this.#byId.get(entry.groupId);\n if (previous === entry)\n return this;\n const without = previous === undefined ? this.#root : this.#remove(this.#root, previous);\n return new PersistentMeasuredGroupTree(this.#insert(without, entry), this.#byId.set(entry.groupId, entry), this.#compare, this.#instrumentation);\n }\n remove(groupId) {\n const previous = this.#byId.get(groupId);\n if (previous === undefined)\n return this;\n return new PersistentMeasuredGroupTree(this.#remove(this.#root, previous), this.#byId.delete(groupId), this.#compare, this.#instrumentation);\n }\n *entries() {\n function* walk(node) {\n if (node === null)\n return;\n yield* walk(node.left);\n yield node.entry;\n yield* walk(node.right);\n }\n yield* walk(this.#root);\n }\n select(index, policy) {\n if (!Number.isInteger(index) ||\n index < 0 ||\n index >= countForPolicy(this.measure, policy))\n return undefined;\n let node = this.#root;\n let remaining = index;\n while (node !== null) {\n const left = countForPolicy(node.left?.measure ?? EMPTY_COUNTS, policy);\n const own = countForPolicy(node.entry.counts, policy);\n if (remaining < left)\n node = node.left;\n else if (remaining < left + own)\n return { entry: node.entry, offset: remaining - left };\n else {\n remaining -= left + own;\n node = node.right;\n }\n }\n return undefined;\n }\n measureBefore(groupId, policy) {\n const entry = this.#byId.get(groupId);\n if (entry === undefined)\n return undefined;\n let node = this.#root;\n let result = 0;\n while (node !== null) {\n const comparison = this.#compareEntries(entry, node.entry);\n if (comparison < 0)\n node = node.left;\n else {\n result += countForPolicy(node.left?.measure ?? EMPTY_COUNTS, policy);\n if (comparison === 0)\n return result;\n result += countForPolicy(node.entry.counts, policy);\n node = node.right;\n }\n }\n return undefined;\n }\n selectData(index, policy) {\n if (!Number.isInteger(index) ||\n index < 0 ||\n index >= dataCountForPolicy(this.measure, policy))\n return undefined;\n let node = this.#root;\n let remaining = index;\n while (node !== null) {\n const left = dataCountForPolicy(node.left?.measure ?? EMPTY_COUNTS, policy);\n const own = dataCountForPolicy(node.entry.counts, policy);\n if (remaining < left)\n node = node.left;\n else if (remaining < left + own)\n return { entry: node.entry, offset: remaining - left };\n else {\n remaining -= left + own;\n node = node.right;\n }\n }\n return undefined;\n }\n dataBefore(groupId, policy) {\n const entry = this.#byId.get(groupId);\n if (entry === undefined)\n return undefined;\n let node = this.#root;\n let result = 0;\n while (node !== null) {\n const comparison = this.#compareEntries(entry, node.entry);\n if (comparison < 0)\n node = node.left;\n else {\n result += dataCountForPolicy(node.left?.measure ?? EMPTY_COUNTS, policy);\n if (comparison === 0)\n return result;\n result += dataCountForPolicy(node.entry.counts, policy);\n node = node.right;\n }\n }\n return undefined;\n }\n visitRange(start, end, policy, visitor, diagnostics) {\n const size = countForPolicy(this.measure, policy);\n const from = Math.max(0, Math.min(size, start));\n const to = Math.max(0, Math.min(size, end));\n const walk = (node, offset) => {\n if (node === null || from >= to)\n return;\n const subtreeCount = countForPolicy(node.measure, policy);\n if (to <= offset || from >= offset + subtreeCount)\n return;\n diagnostics.measuredNodeVisits += 1;\n const leftCount = countForPolicy(node.left?.measure ?? EMPTY_COUNTS, policy);\n const ownStart = offset + leftCount;\n const ownCount = countForPolicy(node.entry.counts, policy);\n const ownEnd = ownStart + ownCount;\n if (from < ownStart)\n walk(node.left, offset);\n if (from < ownEnd && to > ownStart) {\n visitor(node.entry, Math.max(0, from - ownStart), Math.min(ownCount, to - ownStart));\n }\n if (to > ownEnd)\n walk(node.right, ownEnd);\n };\n walk(this.#root, 0);\n }\n}\nfunction instrumentMeasuredGroupTree(tree, instrumentation) {\n return tree instanceof PersistentMeasuredGroupTree\n ? tree.withInstrumentation(instrumentation)\n : tree;\n}\nfunction effectiveExpanded(node, policy) {\n if (node.override !== undefined)\n return node.override;\n if (policy.kind === \"expanded\")\n return true;\n if (policy.kind === \"collapsed\")\n return false;\n return node.depth <= policy.depth;\n}\nfunction createLeafTree(queryPlan) {\n return createOrderStatisticTree({\n getId: (entry) => entry.record.rowId,\n // Entries carry their resolved keys, so a comparison is property reads\n // only — no store gets on this slice-hot path (the measured grouped-gate\n // regression was per-comparison WeakMap resolution).\n compare: (left, right) => compareWithSortKeys(queryPlan, left.record, left.keys, right.record, right.keys),\n measure: {\n empty: 0,\n fromEntry: () => 1,\n combine: (left, right) => left + right,\n },\n });\n}\nfunction createChildTree(queryPlan, level, instrumentation) {\n return new PersistentMeasuredGroupTree(null, instrumentPersistentMap(createPersistentMap(), instrumentation), (left, right) => queryPlan.compareGroupKeys(level, left.path[level], right.path[level]), instrumentation);\n}\nfunction compareAggregateLeaves(queryPlan, left, right) {\n const leftDependency = left.dependency;\n const rightDependency = right.dependency;\n // The dependency carries the row's sort keys (resolved at evaluation), so\n // a comparison is property reads only — no store gets on this slice-hot\n // path (the measured grouped-gate regression was per-comparison WeakMap\n // resolution).\n return compareWithSortKeys(queryPlan, {\n rowId: left.id,\n row: left.row,\n sourceOrder: leftDependency.sourceOrder,\n }, leftDependency.sortKeys, {\n rowId: right.id,\n row: right.row,\n sourceOrder: rightDependency.sourceOrder,\n }, rightDependency.sortKeys);\n}\n/**\n * Kind-aware aggregate root construction (#500 cycle 2 decision A):\n * `sum`/`avg`/`count` get an O(1) scalar accumulator cell; `min`/`max` (no\n * inverse) and custom aggregators (fold order is observable — associativity\n * is the only validated law) keep the ordered tree.\n */\nfunction emptyAggregateRoot(queryPlan, leaf) {\n if (isScalarBuiltinAggregator(leaf.aggregate)) {\n return createScalarAggregateCell({\n columnId: leaf.columnId,\n aggregator: leaf.aggregate,\n });\n }\n const factory = createAggregateTree;\n return factory({\n columnId: leaf.columnId,\n aggregator: leaf.aggregate,\n compare: (left, right) => compareAggregateLeaves(queryPlan, left, right),\n });\n}\nfunction updateAggregateRoots(roots, queryPlan, record, operation, \n/**\n * The row's filter verdict, supplied by the caller. Filtered aggregation is\n * membership in the `filtered` tree — there is no per-leaf flag — so this is\n * the single bit that decides insert vs remove there.\n */\nfilterPasses, \n/** The model-lifetime population choice; true selects the all-row root. */\naggregateFilteredRows, modelOperation, instrumentation) {\n // C1 (#500 cycle 2): only the population `aggregateRecord` reads is built.\n // The other root was write-only — constructed on every insert, finalized\n // never. Membership in the post-filter population is `filterPasses`: on\n // insert the row's verdict under this index's plan, on remove the verdict\n // it was INSERTED under (see `mutatePath`), so the inverse unwinds exactly\n // what was accumulated.\n const member = aggregateFilteredRows || filterPasses;\n if (!member)\n return roots;\n const selected = new Map(aggregateFilteredRows ? roots.all : roots.filtered);\n for (const leaf of record.metadata\n .aggregateLeaves) {\n try {\n const root = instrumentAggregateTree(selected.get(leaf.columnId) ?? emptyAggregateRoot(queryPlan, leaf), instrumentation);\n selected.set(leaf.columnId, operation === \"insert\"\n ? root.insertOrReplace(leaf.allLeaf)\n : // The removal record carries the originally-inserted value on\n // `allLeaf` — the exact operand a scalar cell's inverse needs.\n root.remove(record.rowId, leaf.allLeaf));\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw new PretableRowModelError(\"aggregator-failed\", `The aggregate for column ${leaf.columnId} failed.`, {\n operation: modelOperation,\n rowId: record.rowId,\n columnId: leaf.columnId,\n cause,\n });\n }\n }\n return Object.freeze(aggregateFilteredRows\n ? { all: selected, filtered: EMPTY_AGGREGATE_ROOT_MAP }\n : { all: EMPTY_AGGREGATE_ROOT_MAP, filtered: selected });\n}\nconst EMPTY_AGGREGATE_ROOT_MAP = new Map();\nfunction structurallyEqual(left, right, seen = new WeakMap()) {\n if (Object.is(left, right))\n return true;\n if (left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\") {\n return false;\n }\n let rights = seen.get(left);\n if (rights?.has(right))\n return true;\n if (rights === undefined) {\n rights = new WeakSet();\n seen.set(left, rights);\n }\n rights.add(right);\n if (left instanceof Date || right instanceof Date) {\n return (left instanceof Date &&\n right instanceof Date &&\n Object.is(left.getTime(), right.getTime()));\n }\n if (Array.isArray(left) || Array.isArray(right)) {\n return (Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => structurallyEqual(value, right[index], seen)));\n }\n if (left instanceof Map || right instanceof Map) {\n if (!(left instanceof Map) || !(right instanceof Map))\n return false;\n if (left.size !== right.size)\n return false;\n const unmatched = Array.from(right.entries());\n return Array.from(left.entries()).every(([leftKey, leftValue]) => {\n const index = unmatched.findIndex(([rightKey, rightValue]) => structurallyEqual(leftKey, rightKey, seen) &&\n structurallyEqual(leftValue, rightValue, seen));\n if (index < 0)\n return false;\n unmatched.splice(index, 1);\n return true;\n });\n }\n if (left instanceof Set || right instanceof Set) {\n if (!(left instanceof Set) || !(right instanceof Set))\n return false;\n if (left.size !== right.size)\n return false;\n const unmatched = Array.from(right.values());\n return Array.from(left.values()).every((leftValue) => {\n const index = unmatched.findIndex((rightValue) => structurallyEqual(leftValue, rightValue, seen));\n if (index < 0)\n return false;\n unmatched.splice(index, 1);\n return true;\n });\n }\n if (Object.getPrototypeOf(left) !== Object.getPrototypeOf(right) ||\n (Object.getPrototypeOf(left) !== Object.prototype &&\n Object.getPrototypeOf(left) !== null)) {\n return false;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n return (leftKeys.length === rightKeys.length &&\n leftKeys.every((key) => Object.hasOwn(right, key) &&\n structurallyEqual(Reflect.get(left, key), Reflect.get(right, key), seen)));\n}\nclass GroupAggregatorError extends PretableRowModelError {\n name = \"GroupAggregatorError\";\n groupId;\n groupValues;\n constructor(operation, rowId, columnId, groupId, groupValues, cause) {\n super(\"aggregator-failed\", `Finalizing the aggregate for column ${columnId} failed in group ${groupId}.`, { operation, rowId, columnId, cause });\n this.groupId = groupId;\n this.groupValues = Object.freeze([...groupValues]);\n }\n}\nfunction aggregateRecord(roots, allPopulation, previous, operation, rowId, groupId, groupValues) {\n const selected = allPopulation ? roots.all : roots.filtered;\n const values = {};\n let same = previous !== undefined;\n for (const [columnId, tree] of selected) {\n let finalized;\n try {\n finalized = tree.finalize();\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw new GroupAggregatorError(operation, rowId, columnId, groupId, groupValues, cause);\n }\n const value = structurallyEqual(previous?.[columnId], finalized)\n ? previous?.[columnId]\n : finalized;\n values[columnId] = value;\n if (!Object.is(previous?.[columnId], value))\n same = false;\n }\n if (previous !== undefined && Object.keys(previous).length !== selected.size)\n same = false;\n return same ? previous : Object.freeze(values);\n}\nfunction makePublicGroup(source, expanded, previous) {\n if (previous !== undefined &&\n previous.expanded === expanded &&\n previous.childCount === source.childCount &&\n previous.aggregates === source.aggregates &&\n Object.is(previous.value, source.value))\n return previous;\n return Object.freeze({ ...source, expanded });\n}\nfunction finishNode(node, context, triggerRowId) {\n const previous = context.reusable.get(node.groupId);\n if (previous !== undefined && context.instrumentation !== undefined)\n context.instrumentation.work.groupNodesCopied += 1;\n const aggregates = aggregateRecord(node.aggregateRoots, context.aggregateFilteredRows, previous?.aggregates, context.operation, triggerRowId, node.groupId, node.path.map((entry) => entry.value));\n const descendants = node.depth === context.levelCount - 1\n ? Object.freeze({\n collapsed: node.leaves.size,\n expanded: node.leaves.size,\n throughDepth: Object.freeze(Array(context.levelCount).fill(node.leaves.size)),\n data: node.leaves.size,\n dataCollapsed: node.leaves.size,\n dataExpanded: node.leaves.size,\n dataThroughDepth: Object.freeze(Array(context.levelCount).fill(node.leaves.size)),\n })\n : node.children.measure;\n const counts = groupCounts(node.depth, context.levelCount, node.override, descendants);\n const source = {\n kind: \"group\",\n groupId: node.groupId,\n depth: node.depth,\n columnId: node.columnId,\n value: node.value,\n childCount: node.filteredCount,\n aggregates,\n };\n const publicCollapsed = makePublicGroup(source, false, previous?.publicCollapsed);\n const publicExpanded = makePublicGroup(source, true, previous?.publicExpanded);\n return Object.freeze({\n ...node,\n aggregates,\n publicCollapsed,\n publicExpanded,\n counts,\n });\n}\nconst EMPTY_AGGREGATE_ROOTS = Object.freeze({\n all: EMPTY_AGGREGATE_ROOT_MAP,\n filtered: EMPTY_AGGREGATE_ROOT_MAP,\n});\nfunction mutatePath(state, record, operation, context, \n/**\n * On `\"insert\"` the row's verdict under the index's plan; on `\"remove\"` the\n * verdict the row was INSERTED under (its membership in the previous\n * index), so `filteredCount` unwinds exactly what it counted.\n */\nfilterPasses) {\n const metadata = record.metadata;\n const path = metadata.groupPath;\n if (path.length === 0)\n return;\n const pathKeys = path.map((entry) => encodeGroupValue(entry.value, {\n operation: context.operation,\n rowId: record.rowId,\n columnId: entry.columnId,\n }));\n const visit = (depth, parentGroupId, previous) => {\n const entry = path[depth];\n const groupPath = Object.freeze(path.slice(0, depth + 1));\n const groupId = makeGroupId(groupPath);\n const leafLevel = depth === path.length - 1;\n let childrenByKey = instrumentPersistentMap(previous?.childrenByKey ??\n createPersistentMap(), context.instrumentation);\n let children = instrumentMeasuredGroupTree(previous?.children ??\n createChildTree(context.queryPlan, depth + 1, context.instrumentation), context.instrumentation);\n let leaves = instrumentOrderStatisticTree(previous?.leaves ??\n createLeafTree(context.queryPlan), context.instrumentation);\n if (leafLevel) {\n leaves =\n operation === \"insert\" && filterPasses\n ? leaves.insertOrReplace(orderedRowEntry(context.queryPlan, record))\n : leaves.remove(record.rowId);\n }\n else {\n const childKey = pathKeys[depth + 1];\n const oldChild = childrenByKey.get(childKey);\n const nextChild = visit(depth + 1, groupId, oldChild);\n childrenByKey =\n nextChild === undefined\n ? childrenByKey.delete(childKey)\n : childrenByKey.set(childKey, nextChild);\n children = oldChild?.filteredCount\n ? children.remove(oldChild.groupId)\n : children;\n if (nextChild?.filteredCount)\n children = children.insertOrReplace(nextChild);\n }\n const filteredCount = (previous?.filteredCount ?? 0) +\n (filterPasses ? (operation === \"insert\" ? 1 : -1) : 0);\n const allCount = (previous?.allCount ?? 0) + (operation === \"insert\" ? 1 : -1);\n if (allCount === 0) {\n state.groups = state.groups.delete(groupId);\n return undefined;\n }\n const aggregateRoots = updateAggregateRoots(previous?.aggregateRoots ?? EMPTY_AGGREGATE_ROOTS, context.queryPlan, record, operation, filterPasses, context.aggregateFilteredRows, context.operation, context.instrumentation);\n const override = previous?.override;\n const next = finishNode({\n groupId,\n path: groupPath,\n pathKeys: Object.freeze(pathKeys.slice(0, depth + 1)),\n depth,\n columnId: entry.columnId,\n value: previous === undefined ? entry.value : previous.value,\n key: pathKeys[depth],\n parentGroupId,\n override,\n childrenByKey,\n children,\n leaves,\n filteredCount,\n allCount,\n aggregateRoots,\n }, context, record.rowId);\n state.groups = state.groups.set(groupId, next);\n return next;\n };\n const rootKey = pathKeys[0];\n const oldRoot = state.rootsByKey.get(rootKey);\n const nextRoot = visit(0, undefined, oldRoot);\n state.rootsByKey =\n nextRoot === undefined\n ? state.rootsByKey.delete(rootKey)\n : state.rootsByKey.set(rootKey, nextRoot);\n if (oldRoot?.filteredCount)\n state.roots = state.roots.remove(oldRoot.groupId);\n if (nextRoot?.filteredCount)\n state.roots = state.roots.insertOrReplace(nextRoot);\n state.rowParents =\n operation === \"insert\"\n ? state.rowParents.set(record.rowId, makeGroupId(path))\n : state.rowParents.delete(record.rowId);\n}\nfunction rootFromState(state, context) {\n const root = Object.freeze({\n levelCount: context.levelCount,\n queryPlan: context.queryPlan,\n aggregateFilteredRows: context.aggregateFilteredRows,\n ...state,\n counts: state.roots.measure,\n });\n if (context.instrumentation !== undefined)\n groupIndexInstrumentation.set(root, context.instrumentation);\n return root;\n}\n/**\n * Candidate-only grouped index builder. It owns transient leaves, aggregate\n * trees, and membership maps for the unpublished initial rebuild, then seals\n * group nodes bottom-up one cooperative unit at a time. Published revisions\n * continue to use the persistent changed-path updater below.\n */\nexport function createGroupIndexBuildDraft(options) {\n const { queryPlan, aggregateFilteredRows, operation, instrumentation } = options;\n const levelCount = queryPlan.query.rowGroups.length;\n const rootsByKey = new Map();\n const nodes = [];\n const rowParents = instrumentPersistentMap(createPersistentMap(), instrumentation).asTransient();\n const groups = instrumentPersistentMap(createPersistentMap(), instrumentation).asTransient();\n const context = {\n queryPlan,\n levelCount,\n aggregateFilteredRows,\n reusable: options.reusable?.groups ?? createPersistentMap(),\n operation,\n instrumentation,\n };\n let root;\n let released = false;\n let sealingStarted = false;\n let pendingUnits = 0;\n let activeNode;\n let activeChildIterator;\n let activeChildrenByKey;\n let activeMeasuredChildren;\n let rootIterator;\n let persistentRootsByKey;\n let measuredRoots;\n const assertActive = () => {\n if (released)\n throw new Error(\"Released grouped index build draft.\");\n };\n const createMutableNode = (path, pathKeys, parentGroupId) => {\n const entry = path[path.length - 1];\n const node = {\n groupId: makeGroupId(path),\n path,\n pathKeys,\n depth: path.length - 1,\n columnId: entry.columnId,\n value: entry.value,\n key: pathKeys[pathKeys.length - 1],\n parentGroupId,\n override: options.overrides.get(makeGroupId(path)),\n childrenByKey: new Map(),\n leaves: instrumentOrderStatisticTree(createLeafTree(queryPlan), instrumentation).asTransient(),\n aggregateRoots: { all: new Map(), filtered: new Map() },\n filteredCount: 0,\n allCount: 0,\n triggerRowId: undefined,\n finished: undefined,\n };\n nodes.push(node);\n // One unit seals this node and one installs its parent/root edge.\n pendingUnits += 2;\n return node;\n };\n const createRootDraft = (leaf) => {\n const root = emptyAggregateRoot(queryPlan, leaf);\n // Scalar cells never defer measures, so they skip the deferred-measure\n // draft machinery entirely (their transient satisfies its surface with a\n // permanently-empty queue).\n return isScalarBuiltinAggregator(leaf.aggregate)\n ? root.asTransient()\n : createDeferredMeasureTransientAggregateTree(instrumentAggregateTree(root, instrumentation));\n };\n const updateMutableAggregates = (node, record, filterPasses) => {\n // C1 (#500 cycle 2): only the SELECTED population root is built — the\n // other was write-only. A row outside the selected population\n // contributes nothing at all.\n if (!aggregateFilteredRows && !filterPasses)\n return;\n const selected = aggregateFilteredRows\n ? node.aggregateRoots.all\n : node.aggregateRoots.filtered;\n let grewAnyTree = false;\n for (const leaf of record.metadata\n .aggregateLeaves) {\n try {\n let root = selected.get(leaf.columnId);\n if (root === undefined) {\n root = createRootDraft(leaf);\n selected.set(leaf.columnId, root);\n }\n const sizeBefore = root.size;\n root.insertOrReplace(leaf.allLeaf);\n // A scalar cell accumulates inline and holds NO deferred measures\n // (pendingMeasureCount stays 0), so it must charge no seal units —\n // only a grown ordered tree leaves work for the seal phase.\n if (root.size > sizeBefore && root.pendingMeasureCount > 0) {\n grewAnyTree = true;\n }\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw new PretableRowModelError(\"aggregator-failed\", `The aggregate for column ${leaf.columnId} failed.`, {\n operation,\n rowId: record.rowId,\n columnId: leaf.columnId,\n cause,\n });\n }\n }\n // One seal unit per (row, node), NOT per (row × column): sealing\n // advances every still-pending tree of the node by one measure, so a\n // row's deferred measures across ALL its tree-backed aggregated columns\n // drain together under a single charged unit (#500). Scalar-only rows\n // charge nothing (#500 cycle 2).\n if (grewAnyTree)\n pendingUnits += 1;\n };\n const finishRoot = () => rootFromState({\n rootsByKey: persistentRootsByKey.freeze(),\n roots: measuredRoots,\n groups: groups.freeze(),\n rowParents: rowParents.freeze(),\n }, context);\n const finalizeActiveNode = () => {\n const mutable = activeNode;\n const aggregateRoots = Object.freeze({\n all: new Map([...mutable.aggregateRoots.all].map(([columnId, tree]) => [\n columnId,\n tree.freeze(),\n ])),\n filtered: new Map([...mutable.aggregateRoots.filtered].map(([columnId, tree]) => [\n columnId,\n tree.freeze(),\n ])),\n });\n const finished = finishNode({\n groupId: mutable.groupId,\n path: mutable.path,\n pathKeys: mutable.pathKeys,\n depth: mutable.depth,\n columnId: mutable.columnId,\n value: mutable.value,\n key: mutable.key,\n parentGroupId: mutable.parentGroupId,\n override: mutable.override,\n childrenByKey: activeChildrenByKey.freeze(),\n children: activeMeasuredChildren,\n leaves: mutable.leaves.freeze(),\n filteredCount: mutable.filteredCount,\n allCount: mutable.allCount,\n aggregateRoots,\n }, context, mutable.triggerRowId);\n mutable.finished = finished;\n groups.set(finished.groupId, finished);\n activeNode = undefined;\n activeChildIterator = undefined;\n activeChildrenByKey = undefined;\n activeMeasuredChildren = undefined;\n };\n /**\n * One seal unit = one ROW of deferred measures: every still-pending\n * aggregate tree of the active node — all tree-backed aggregated columns\n * of the selected population root — advances by exactly one measure per\n * call. The trees drain in lockstep, so a node consumes max(tree size)\n * units, which is the one-unit-per-(row, node) charge\n * `updateMutableAggregates` recorded. Scalar cells report zero pending\n * measures and are skipped (#500 cycle 2).\n * Resumability is preserved at row granularity: each call is one atomic\n * unit and the pending counts on the trees are the resume cursor (#500).\n */\n const sealActiveAggregate = () => {\n const mutable = activeNode;\n let sealedAnyMeasure = false;\n for (const roots of [\n mutable.aggregateRoots.all,\n mutable.aggregateRoots.filtered,\n ]) {\n for (const [columnId, tree] of roots) {\n if (tree.pendingMeasureCount === 0)\n continue;\n try {\n tree.sealMeasureStep();\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw new GroupAggregatorError(operation, mutable.triggerRowId, columnId, mutable.groupId, mutable.path.map((entry) => entry.value), cause);\n }\n sealedAnyMeasure = true;\n }\n }\n if (!sealedAnyMeasure)\n return false;\n pendingUnits -= 1;\n return true;\n };\n const draft = {\n get pendingFinalizationCount() {\n return pendingUnits;\n },\n insert(record) {\n assertActive();\n if (sealingStarted)\n throw new Error(\"Cannot insert after grouped index sealing started.\");\n const path = record.metadata.groupPath;\n if (path.length === 0)\n return;\n // Computed once per record and spent locally on the three membership\n // decisions below (filteredCount, the filtered aggregate tree, and the\n // leaf tree) — which together ARE this index's record of the verdict.\n const filterPasses = filterVerdict(queryPlan, record);\n const pathKeys = path.map((entry) => encodeGroupValue(entry.value, {\n operation,\n rowId: record.rowId,\n columnId: entry.columnId,\n }));\n let children = rootsByKey;\n let parentGroupId;\n let current;\n for (let depth = 0; depth < path.length; depth += 1) {\n const key = pathKeys[depth];\n current = children.get(key);\n if (current === undefined) {\n current = createMutableNode(Object.freeze(path.slice(0, depth + 1)), Object.freeze(pathKeys.slice(0, depth + 1)), parentGroupId);\n children.set(key, current);\n }\n current.allCount += 1;\n if (filterPasses)\n current.filteredCount += 1;\n updateMutableAggregates(current, record, filterPasses);\n current.triggerRowId = record.rowId;\n parentGroupId = current.groupId;\n children = current.childrenByKey;\n }\n if (filterPasses) {\n current.leaves.insertOrReplace(orderedRowEntry(queryPlan, record));\n }\n rowParents.set(record.rowId, current.groupId);\n },\n sealStep() {\n assertActive();\n sealingStarted = true;\n if (root !== undefined)\n return true;\n if (activeNode !== undefined) {\n if (sealActiveAggregate())\n return false;\n const next = activeChildIterator.next();\n if (!next.done) {\n const [key, child] = next.value;\n const finished = child.finished;\n if (finished === undefined)\n throw new Error(\"Grouped index children must seal before parents.\");\n activeChildrenByKey.set(key, finished);\n if (finished.filteredCount > 0) {\n activeMeasuredChildren =\n activeMeasuredChildren.insertOrReplace(finished);\n }\n pendingUnits -= 1;\n return false;\n }\n finalizeActiveNode();\n pendingUnits -= 1;\n return false;\n }\n const mutable = nodes.pop();\n if (mutable !== undefined) {\n activeNode = mutable;\n activeChildIterator = mutable.childrenByKey.entries();\n activeMeasuredChildren = createChildTree(queryPlan, mutable.depth + 1, instrumentation);\n activeChildrenByKey = instrumentPersistentMap(createPersistentMap(), instrumentation).asTransient();\n return draft.sealStep();\n }\n if (rootIterator === undefined) {\n rootIterator = rootsByKey.entries();\n measuredRoots = createChildTree(queryPlan, 0, instrumentation);\n persistentRootsByKey = instrumentPersistentMap(createPersistentMap(), instrumentation).asTransient();\n }\n const next = rootIterator.next();\n if (!next.done) {\n const [key, mutableRoot] = next.value;\n const finished = mutableRoot.finished;\n persistentRootsByKey.set(key, finished);\n if (finished.filteredCount > 0)\n measuredRoots = measuredRoots.insertOrReplace(finished);\n pendingUnits -= 1;\n return false;\n }\n root = finishRoot();\n return true;\n },\n finish() {\n assertActive();\n if (root === undefined)\n throw new Error(\"Grouped index build draft is not sealed.\");\n return root;\n },\n release() {\n released = true;\n rootsByKey.clear();\n nodes.length = 0;\n activeNode = undefined;\n activeChildIterator = undefined;\n activeChildrenByKey = undefined;\n activeMeasuredChildren = undefined;\n rootIterator = undefined;\n persistentRootsByKey = undefined;\n measuredRoots = undefined;\n root = undefined;\n },\n };\n return draft;\n}\nexport function createGroupIndex(records, queryPlan, aggregateFilteredRows, overrides, operation = \"set-rows\", reusable, instrumentation) {\n const levelCount = queryPlan.query.rowGroups.length;\n const rootsByKey = createPersistentMap();\n const state = {\n rootsByKey,\n roots: createChildTree(queryPlan, 0, instrumentation),\n groups: createPersistentMap(),\n rowParents: createPersistentMap(),\n };\n const context = {\n queryPlan,\n levelCount,\n aggregateFilteredRows,\n reusable: reusable?.groups ?? state.groups,\n operation,\n instrumentation,\n };\n for (const record of records) {\n mutatePath(state, record, \"insert\", context, filterVerdict(queryPlan, record));\n }\n // Apply retained overrides after all future/current groups have been materialized.\n let root = rootFromState(state, context);\n for (const [groupId, expanded] of overrides.entries()) {\n if (root.groups.has(groupId))\n root = setGroupOverride(root, groupId, expanded, operation);\n }\n return root;\n}\nexport function updateGroupIndex(previous, removals, insertions, overrides, operation = \"apply-transaction\", instrumentation = groupIndexInstrumentation.get(previous)) {\n const state = {\n rootsByKey: instrumentPersistentMap(previous.rootsByKey, instrumentation),\n roots: instrumentMeasuredGroupTree(previous.roots, instrumentation),\n groups: instrumentPersistentMap(previous.groups, instrumentation),\n rowParents: instrumentPersistentMap(previous.rowParents, instrumentation),\n };\n const context = {\n queryPlan: previous.queryPlan,\n levelCount: previous.levelCount,\n aggregateFilteredRows: previous.aggregateFilteredRows,\n reusable: previous.groups,\n operation,\n instrumentation,\n };\n // A removal must unwind the verdict the row was counted under, which is\n // exactly its membership in the PREVIOUS index — read before any mutation\n // touches `state`.\n //\n // An insertion's verdict comes from the index's OWN plan, the same authority\n // this function already trusts for leaf order (`orderedRowEntry` resolves\n // keys from that plan's store) and for its comparators. That binds the\n // verdict to the same standing precondition as the rest: records handed to\n // an existing index must be coherent with the plan the index was built\n // under. A same-reference mutation breaks that precondition for every\n // derived value, not just this one, and its caller answers by rebuilding\n // the index outright under the fresh plan.\n for (const record of removals) {\n mutatePath(state, record, \"remove\", context, rowPassesFilterInGroupIndex(previous, record.rowId));\n }\n for (const record of insertions) {\n mutatePath(state, record, \"insert\", context, filterVerdict(previous.queryPlan, record));\n }\n let root = rootFromState(state, context);\n if (overrides !== undefined) {\n for (const [groupId, expanded] of overrides.entries()) {\n const group = root.groups.get(groupId);\n if (group !== undefined && group.override !== expanded) {\n root = setGroupOverride(root, groupId, expanded, operation);\n }\n }\n }\n return root;\n}\nexport function setGroupOverride(root, groupId, override, operation = \"set-group-expanded\") {\n const target = root.groups.get(groupId);\n if (target === undefined || target.override === override)\n return root;\n const context = {\n queryPlan: root.queryPlan,\n levelCount: root.levelCount,\n aggregateFilteredRows: root.aggregateFilteredRows,\n reusable: root.groups,\n operation,\n instrumentation: groupIndexInstrumentation.get(root),\n };\n let groups = instrumentPersistentMap(root.groups, context.instrumentation);\n const representativeRowId = (node) => {\n const child = node.childrenByKey.entries().next().value?.[1];\n if (child !== undefined)\n return representativeRowId(child);\n // C1 (#500 cycle 2): only the selected population root exists, so read\n // whichever one holds trees. Builtin-scalar-only groups yield undefined\n // — the sole consumer is custom-finalizer error context, and customs\n // always ride a tree with a firstId.\n for (const roots of [\n node.aggregateRoots.all,\n node.aggregateRoots.filtered,\n ]) {\n for (const tree of roots.values()) {\n const rowId = tree.firstId();\n if (rowId !== undefined)\n return rowId;\n }\n }\n return undefined;\n };\n const replace = (depth, node) => {\n let childrenByKey = instrumentPersistentMap(node.childrenByKey, context.instrumentation);\n let children = instrumentMeasuredGroupTree(node.children, context.instrumentation);\n if (depth < target.depth) {\n const key = target.pathKeys[depth + 1];\n const oldChild = childrenByKey.get(key);\n const nextChild = replace(depth + 1, oldChild);\n childrenByKey = childrenByKey.set(key, nextChild);\n if (oldChild.filteredCount)\n children = children.remove(oldChild.groupId).insertOrReplace(nextChild);\n }\n const next = finishNode({\n ...node,\n override: depth === target.depth ? override : node.override,\n childrenByKey,\n children,\n }, context, \n // Expansion does not change aggregate roots. If a custom lazy finalizer\n // is nevertheless invoked, use the first ordered descendant as the\n // deterministic representative for complete error context.\n representativeRowId(node));\n groups = groups.set(next.groupId, next);\n return next;\n };\n const rootKey = target.pathKeys[0];\n const oldTop = root.rootsByKey.get(rootKey);\n const nextTop = replace(0, oldTop);\n let roots = instrumentMeasuredGroupTree(root.roots, context.instrumentation);\n if (oldTop.filteredCount)\n roots = roots.remove(oldTop.groupId);\n if (nextTop.filteredCount)\n roots = roots.insertOrReplace(nextTop);\n const nextRoot = Object.freeze({\n ...root,\n rootsByKey: instrumentPersistentMap(root.rootsByKey, context.instrumentation).set(rootKey, nextTop),\n roots,\n groups,\n counts: roots.measure,\n });\n if (context.instrumentation !== undefined)\n groupIndexInstrumentation.set(nextRoot, context.instrumentation);\n return nextRoot;\n}\nfunction publicGroup(node, policy) {\n return effectiveExpanded(node, policy)\n ? node.publicExpanded\n : node.publicCollapsed;\n}\nfunction publicData(record, depth) {\n if (record.publicRow.depth === depth)\n return record.publicRow;\n let byDepth = groupedPublicData.get(record);\n const cached = byDepth?.get(depth);\n if (cached !== undefined)\n return cached;\n const created = Object.freeze({ ...record.publicRow, depth });\n if (byDepth === undefined) {\n byDepth = new Map();\n groupedPublicData.set(record, byDepth);\n }\n byDepth.set(depth, created);\n return created;\n}\nconst groupedPublicData = new WeakMap();\nexport function visibleCount(root, policy) {\n return countForPolicy(root.counts, policy);\n}\nfunction visibleAtNode(node, policy, offset) {\n if (offset === 0)\n return publicGroup(node, policy);\n if (!effectiveExpanded(node, policy))\n return undefined;\n const descendantOffset = offset - 1;\n if (node.children.size > 0) {\n const selected = node.children.select(descendantOffset, policy);\n return selected === undefined\n ? undefined\n : visibleAtNode(selected.entry, policy, selected.offset);\n }\n const entry = node.leaves.entryAt(descendantOffset);\n return entry === undefined\n ? undefined\n : publicData(entry.record, node.depth + 1);\n}\nexport function visibleAt(root, policy, index) {\n const selected = root.roots.select(index, policy);\n return selected === undefined\n ? undefined\n : visibleAtNode(selected.entry, policy, selected.offset);\n}\nexport function visibleRange(root, policy, start, end, resolveRecord = (record) => record) {\n const size = visibleCount(root, policy);\n const from = Math.max(0, Math.min(size, Math.trunc(Number.isNaN(start) ? 0 : start)));\n const to = Math.max(0, Math.min(size, Math.trunc(Number.isNaN(end) ? 0 : end)));\n const diagnostics = {\n measuredNodeVisits: 0,\n };\n const result = [];\n const appendNodeRange = (node, nodeStart, nodeEnd) => {\n if (nodeStart >= nodeEnd)\n return;\n if (nodeStart === 0)\n result.push(publicGroup(node, policy));\n if (!effectiveExpanded(node, policy) || nodeEnd <= 1)\n return;\n const descendantsStart = Math.max(0, nodeStart - 1);\n const descendantsEnd = nodeEnd - 1;\n if (node.children.size > 0) {\n node.children.visitRange(descendantsStart, descendantsEnd, policy, appendNodeRange, diagnostics);\n return;\n }\n for (const entry of node.leaves.range(descendantsStart, descendantsEnd)) {\n result.push(publicData(resolveRecord(entry.record), node.depth + 1));\n }\n };\n if (from < to) {\n root.roots.visitRange(from, to, policy, appendNodeRange, diagnostics);\n }\n const frozen = Object.freeze(result);\n visibleRangeDiagnostics.set(frozen, Object.freeze({ measuredNodeVisits: diagnostics.measuredNodeVisits }));\n return frozen;\n}\nexport function isExpanded(root, groupId, policy) {\n const node = root.groups.get(groupId);\n return node === undefined ? false : effectiveExpanded(node, policy);\n}\nexport function visibleIndexOf(root, policy, ref) {\n const targetId = ref.kind === \"data\" ? root.rowParents.get(ref.rowId) : ref.groupId;\n if (targetId === undefined)\n return -1;\n const target = root.groups.get(targetId);\n if (target === undefined || target.filteredCount === 0)\n return -1;\n const chain = [];\n let cursor = target;\n while (cursor !== undefined) {\n chain.push(cursor);\n cursor =\n cursor.parentGroupId === undefined\n ? undefined\n : root.groups.get(cursor.parentGroupId);\n }\n chain.reverse();\n let index = root.roots.measureBefore(chain[0].groupId, policy);\n if (index === undefined)\n return -1;\n for (let depth = 1; depth < chain.length; depth += 1) {\n const parent = chain[depth - 1];\n if (!effectiveExpanded(parent, policy))\n return -1;\n const before = parent.children.measureBefore(chain[depth].groupId, policy);\n if (before === undefined)\n return -1;\n index += 1 + before;\n }\n if (ref.kind === \"group\")\n return index;\n if (!effectiveExpanded(target, policy))\n return -1;\n const rank = target.leaves.rankOf(ref.rowId);\n return rank === undefined ? -1 : index + 1 + rank;\n}\nfunction dataAtNode(node, policy, index, resolveRecord) {\n if (!effectiveExpanded(node, policy))\n return undefined;\n if (node.children.size > 0) {\n const selected = node.children.selectData(index, policy);\n return selected === undefined\n ? undefined\n : dataAtNode(selected.entry, policy, selected.offset, resolveRecord);\n }\n const entry = node.leaves.entryAt(index);\n return entry === undefined\n ? undefined\n : publicData(resolveRecord(entry.record), node.depth + 1);\n}\nexport function visibleDataCount(root, policy) {\n return dataCountForPolicy(root.counts, policy);\n}\nexport function dataAt(root, policy, index, resolveRecord = (record) => record) {\n const selected = root.roots.selectData(index, policy);\n return selected === undefined\n ? undefined\n : dataAtNode(selected.entry, policy, selected.offset, resolveRecord);\n}\n/** Returns the visible data rank of a data ref, or the count before a group ref. */\nexport function dataRankAtRef(root, policy, ref) {\n const targetId = ref.kind === \"data\" ? root.rowParents.get(ref.rowId) : ref.groupId;\n if (targetId === undefined)\n return undefined;\n const target = root.groups.get(targetId);\n if (target === undefined || target.filteredCount === 0)\n return undefined;\n const chain = [];\n let cursor = target;\n while (cursor !== undefined) {\n chain.push(cursor);\n cursor =\n cursor.parentGroupId === undefined\n ? undefined\n : root.groups.get(cursor.parentGroupId);\n }\n chain.reverse();\n let rank = root.roots.dataBefore(chain[0].groupId, policy);\n if (rank === undefined)\n return undefined;\n for (let depth = 1; depth < chain.length; depth += 1) {\n const parent = chain[depth - 1];\n if (!effectiveExpanded(parent, policy))\n return undefined;\n const before = parent.children.dataBefore(chain[depth].groupId, policy);\n if (before === undefined)\n return undefined;\n rank += before;\n }\n if (ref.kind === \"group\")\n return rank;\n if (!effectiveExpanded(target, policy))\n return undefined;\n const leafRank = target.leaves.rankOf(ref.rowId);\n return leafRank === undefined ? undefined : rank + leafRank;\n}\nexport function parentGroup(root, ref, policy) {\n const parentId = ref.kind === \"data\"\n ? root.rowParents.get(ref.rowId)\n : root.groups.get(ref.groupId)?.parentGroupId;\n const node = parentId === undefined ? undefined : root.groups.get(parentId);\n return node === undefined ? undefined : publicGroup(node, policy);\n}\nexport function nearestVisible(root, ref, policy) {\n if (visibleIndexOf(root, policy, ref) >= 0)\n return Object.freeze({ ...ref });\n let groupId = ref.kind === \"data\" ? root.rowParents.get(ref.rowId) : ref.groupId;\n while (groupId !== undefined) {\n const groupRef = Object.freeze({ kind: \"group\", groupId });\n if (visibleIndexOf(root, policy, groupRef) >= 0)\n return groupRef;\n groupId = root.groups.get(groupId)?.parentGroupId;\n }\n return undefined;\n}\n","import { compareWithSortKeys, filterVerdict, } from \"./compiled-query\";\nimport { orderedRowEntry } from \"./ordered-row-entry\";\nimport { attachGroupIndex, createGroupIndex, dataAt, dataRankAtRef, getGroupIndex, isExpanded, nearestVisible, parentGroup, visibleCount, visibleDataCount, visibleIndexOf, visibleRange, } from \"./group-index\";\nimport { createMembership, setMembershipBit, } from \"./membership-bitset\";\nimport { createOrderStatisticTree } from \"./persistent/order-statistic-tree\";\nexport function createFlatVisibleIndex(records, queryPlan) {\n const draft = createFlatVisibleTree(queryPlan).asTransient();\n for (const record of records) {\n // The verdict is COMPUTED here and stays local: the tree this loop fills\n // IS where the answer is recorded, so storing it on the record would only\n // duplicate what membership already says.\n if (filterVerdict(queryPlan, record)) {\n draft.insertOrReplace(orderedRowEntry(queryPlan, record));\n }\n }\n return Object.freeze({ rows: draft.freeze() });\n}\nexport function createVisibleIndex(records, queryPlan, aggregateFilteredRows, overrides, operation = \"set-rows\", reusable) {\n if (queryPlan.query.rowGroups.length === 0) {\n return createFlatVisibleIndex(records, queryPlan);\n }\n return attachGroupIndex(createFlatVisibleTree(queryPlan), createGroupIndex(records, queryPlan, aggregateFilteredRows, overrides, operation, reusable));\n}\n/**\n * Membership bitset of a FLAT visible tree: one pass, `entry.record.slot`.\n * `capacity` must be the owning root's self-described `slotCapacity` (or the\n * value that will become it), never the live allocator's.\n */\nexport function membershipFromFlatTree(rows, capacity) {\n const bits = createMembership(capacity);\n // `range(0, size)` rather than `entries()`: a full walk, and the tree's\n // materialized non-generator walk is the cheaper way to make one — ~1ms\n // against ~30ms at 50,000 rows (see `iterateEntries`).\n for (const entry of rows.range(0, rows.size)) {\n setMembershipBit(bits, entry.record.slot);\n }\n return bits;\n}\nexport function createFlatVisibleTree(queryPlan) {\n return createOrderStatisticTree({\n getId: (entry) => entry.record.rowId,\n // Entries carry their resolved keys, so a comparison is property reads\n // only — no store gets on this slice-hot path (the measured grouped-gate\n // regression was per-comparison WeakMap resolution).\n compare: (left, right) => compareWithSortKeys(queryPlan, left.record, left.keys, right.record, right.keys),\n measure: {\n empty: 0,\n fromEntry: () => 1,\n combine: (left, right) => left + right,\n },\n });\n}\nfunction dataRef(rowId) {\n return Object.freeze({ kind: \"data\", rowId });\n}\n/** Creates an immutable indexed facade that closes over exactly one root. */\nexport function createFlatSnapshot(root) {\n const grouped = getGroupIndex(root.visible);\n if (grouped !== undefined) {\n const policy = root.expansion.default;\n const resolveCurrentRecord = (record) => root.rows.get(record.rowId) ?? record;\n const publicRowAt = (index) => visibleRange(grouped, policy, index, index + 1, resolveCurrentRecord)[0];\n const refAtDataRank = (index) => dataAt(grouped, policy, index, resolveCurrentRecord);\n const neighbor = (ref, delta) => {\n const rank = dataRankAtRef(grouped, policy, ref);\n if (rank === undefined)\n return undefined;\n return dataAt(grouped, policy, ref.kind === \"data\" ? rank + delta : rank + (delta < 0 ? -1 : 0), resolveCurrentRecord);\n };\n const count = visibleCount(grouped, policy);\n const dataCount = visibleDataCount(grouped, policy);\n return Object.freeze({\n revision: root.revision,\n sourceRowCount: root.rows.size,\n visibleRowCount: count,\n visibleDataRowCount: dataCount,\n rowAt: publicRowAt,\n range: (start, end) => visibleRange(grouped, policy, start, end, resolveCurrentRecord),\n indexOf: (ref) => visibleIndexOf(grouped, policy, ref),\n dataIndexOf: (ref) => dataRankAtRef(grouped, policy, ref) ?? -1,\n dataRowAt: refAtDataRank,\n firstDataRow: () => refAtDataRank(0),\n lastDataRow: () => refAtDataRank(dataCount - 1),\n nextDataRow: (ref) => neighbor(ref, 1),\n previousDataRow: (ref) => neighbor(ref, -1),\n parentGroupOf: (ref) => parentGroup(grouped, ref, policy),\n nearestVisibleRef: (ref) => nearestVisible(grouped, ref, policy),\n isGroupExpanded: (groupId) => isExpanded(grouped, groupId, policy),\n // Dense reads answer `undefined` wholesale on grouped roots: group rows\n // carry no slot, and the seam's contract is all-or-nothing — the caller\n // falls back to string identities.\n ɵvisibleSlotRange: () => undefined,\n ɵslotOfRowId: () => undefined,\n ɵslotCapacity: () => undefined,\n query: root.queryPlan.query,\n expansion: root.expansion.state,\n });\n }\n const visible = root.visible.rows;\n const publicRowAt = (index) => {\n const ordered = visible.entryAt(index);\n return ordered === undefined\n ? undefined\n : root.rows.get(ordered.record.rowId)?.publicRow;\n };\n const lookupRank = (ref) => ref.kind === \"data\" ? visible.rankOf(ref.rowId) : undefined;\n return Object.freeze({\n revision: root.revision,\n sourceRowCount: root.rows.size,\n visibleRowCount: visible.size,\n visibleDataRowCount: visible.size,\n rowAt: publicRowAt,\n range: (start, end) => Object.freeze(visible\n .range(start, end)\n .map((entry) => root.rows.get(entry.record.rowId)?.publicRow)\n .filter((row) => row !== undefined)),\n indexOf: (ref) => lookupRank(ref) ?? -1,\n dataIndexOf: (ref) => lookupRank(ref) ?? -1,\n dataRowAt: publicRowAt,\n firstDataRow: () => publicRowAt(0),\n lastDataRow: () => publicRowAt(visible.size - 1),\n nextDataRow: (ref) => {\n const rank = lookupRank(ref);\n return rank === undefined ? undefined : publicRowAt(rank + 1);\n },\n previousDataRow: (ref) => {\n const rank = lookupRank(ref);\n return rank === undefined ? undefined : publicRowAt(rank - 1);\n },\n parentGroupOf: () => undefined,\n nearestVisibleRef: (ref) => {\n if (ref.kind !== \"data\" || visible.rankOf(ref.rowId) === undefined)\n return undefined;\n return dataRef(ref.rowId);\n },\n isGroupExpanded: () => false,\n // The tree's materialized `range` walk, slots only: on a flat root every\n // entry is a data row, and a record's slot is carried across updates, so\n // `entry.record.slot` IS the current binding — no row-store resolution\n // per row (see `membershipFromFlatTree` for the same read).\n ɵvisibleSlotRange: (start, end) => Object.freeze(visible.range(start, end).map((entry) => entry.record.slot)),\n ɵslotOfRowId: (rowId) => root.rows.get(rowId)?.slot,\n ɵslotCapacity: () => root.slotCapacity,\n query: root.queryPlan.query,\n expansion: root.expansion.state,\n });\n}\n","/**\n * Synchronous subset rebuild for a filter-only plan change on an ungrouped\n * query. Runs to completion on the caller's stack, like `sort-rebuild` — a\n * filter-only change is a membership change over an already-sorted set:\n * values, sort keys, group paths, and relative order are all unchanged. No\n * record is reconstructed — not even a flipped one, because no record holds a\n * verdict any more — so the rows HAMT carries by identity exactly as\n * sort-rebuild's does, and the only new structure is the visible tree: a\n * linear merge of the surviving old order with the sorted flipped-in subset,\n * with no comparator sort of the full set, ever.\n */\nimport { adoptEvaluationCache, compareWithSortKeys, filterVerdict, isFilterOnlyChange, sortKeysOf, } from \"./compiled-query\";\nimport { createMembership, setMembershipBit, testMembershipBit, } from \"./membership-bitset\";\nimport { compareOrderStatisticTreeIds, createOrderStatisticTreeFromSortedEntries, instrumentOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { forEachSlotEntry } from \"./slot-vector\";\nimport { createFlatVisibleTree } from \"./visible-index\";\nexport function rebuildRootForFilterOnlyChange(options) {\n const { captured, nextPlan, revision, now, instrumentation } = options;\n if (!isFilterOnlyChange(captured.queryPlan, nextPlan)) {\n throw new TypeError(\"Synchronous filter rebuild requires a filter-only plan change.\");\n }\n if (nextPlan.query.rowGroups.length > 0) {\n throw new TypeError(\"Synchronous filter rebuild requires an ungrouped query.\");\n }\n const startedAt = now();\n // The next plan ADOPTS the captured plan's evaluation cache by reference:\n // one assignment for the whole store instead of a per-row refill. A\n // filter-only change leaves every cached field valid (the field-by-field\n // argument lives on the seam), and the one filter-dependent field — the\n // verdict memo — is tagged with the plan that wrote it, so the loop below\n // still runs the NEW filters over every row.\n adoptEvaluationCache(nextPlan, captured.queryPlan);\n // One hole-skipping pass over ALL records via the slot vector: run the new\n // plan's verdict, record it as a bit in the next root's membership bitset,\n // and diff it against the captured root's bit. Every record carries by\n // identity — flipped or not — so the pass collects nothing but the two flip\n // sets, and only a flipped-IN row needs its keys resolved (survivors keep\n // their existing entry objects, leavers need nothing). The bitset is sized\n // by `captured.slotCapacity` — roots are self-describing, and reading the\n // live allocator instead would let later growth leak into this snapshot's\n // domain. This path throws on grouped plans above, so\n // `captured.visibleSlots` is always the REAL flat bitset, never the\n // grouped sentinel.\n const nextVisibleSlots = createMembership(captured.slotCapacity);\n const flippedIn = [];\n const flippedOut = new Set();\n // Slot order, not source order — sound because nothing downstream reads\n // this walk's order: flippedIn is comparator-sorted below, flippedOut is a\n // set, and the merge consumes the OLD TREE's walk. recordsBySlot replaces\n // the rows-HAMT get; visibleSlots replaces the old-verdict membership get.\n forEachSlotEntry(captured.recordsBySlot, (previous) => {\n const passes = filterVerdict(nextPlan, previous);\n if (passes)\n setMembershipBit(nextVisibleSlots, previous.slot);\n // The OLD verdict is the captured root's membership bit — the flip diff\n // is a set difference between two structures, not a comparison of two\n // stored flags. And since no record stores a verdict, a FLIPPED row needs\n // no new record either: it carries by identity exactly like an unflipped\n // one, and the flip is expressed entirely by where it sits in the new\n // visible tree.\n if (passes === testMembershipBit(captured.visibleSlots, previous.slot)) {\n return;\n }\n if (passes) {\n // Resolved from the adopted store — the same array the captured plan\n // handed out, since a filter-only change leaves the keys untouched.\n const keys = sortKeysOf(nextPlan, previous);\n flippedIn.push(Object.freeze({ record: previous, keys }));\n }\n else {\n flippedOut.add(previous.rowId);\n }\n });\n const flipped = flippedIn.length + flippedOut.size;\n // Identity, unconditionally: a filter-only change reconstructs NO record,\n // so the rows HAMT is carried whole and the transient is never opened.\n const rows = captured.rows;\n let visible = captured.visible;\n // Zero flips carry the captured bitset by identity — same member set —\n // and the freshly-computed (bit-identical) `nextVisibleSlots` is dropped.\n let visibleSlots = captured.visibleSlots;\n if (flipped === 0) {\n // Zero flips (decided here, pinned by tests): still a NEW root at the\n // requested revision under the next plan, with the rows map AND the\n // visible tree object carried wholesale. Reusing the tree is sound even\n // though its entries' keys resolved under the OLD plan and its comparator\n // closure captured it: a filter-only change keeps sort columns and\n // comparators identical, and the next plan now READS THE SAME STORE, so\n // future inserts decorate entries with the very arrays the carried ones\n // hold — ordering stays coherent.\n }\n else {\n // Both sequences below are strictly sorted by the same composite order\n // the tree maintains (comparator, then id): the old tree's in-order walk\n // by construction, the flipped-in subset by this k log k sort — the only\n // sort in the rebuild, and it never sees an unflipped row.\n const compareEntries = (left, right) => compareWithSortKeys(nextPlan, left.record, left.keys, right.record, right.keys) || compareOrderStatisticTreeIds(left.record.rowId, right.record.rowId);\n flippedIn.sort(compareEntries);\n // Single linear merge: surviving entries keep their ENTRY objects (a\n // still-passing row is by definition unflipped — record and keys are both\n // unchanged), flipped-out rows are skipped, flipped-in entries interleave\n // where the composite order puts them.\n const merged = [];\n let next = 0;\n // `range(0, size)` rather than `entries()`: this walk always runs to\n // completion, and the tree's non-generator walk is the cheaper way to\n // get one — ~1ms against ~30ms at 50,000 rows (see `iterateEntries`).\n for (const entry of captured.visible.rows.range(0, captured.visible.rows.size)) {\n if (flippedOut.has(entry.record.rowId))\n continue;\n while (next < flippedIn.length &&\n compareEntries(flippedIn[next], entry) < 0) {\n merged.push(flippedIn[next]);\n next += 1;\n }\n merged.push(entry);\n }\n while (next < flippedIn.length) {\n merged.push(flippedIn[next]);\n next += 1;\n }\n visible = Object.freeze({\n rows: createOrderStatisticTreeFromSortedEntries(instrumentOrderStatisticTree(createFlatVisibleTree(nextPlan), instrumentation), merged, \n // Both proofs are earned by the merge directly above, and neither\n // would be available to a caller that re-sorted the full set.\n // Order: a merge of two strictly-increasing, id-disjoint sequences\n // under one total order is strictly increasing — so the n−1\n // verification would re-derive what the loop just guaranteed.\n // byId: the visible set changes by exactly `flippedOut` leaving and\n // `flippedIn` arriving; every survivor is pushed into `merged` as the\n // base tree's OWN entry object (unflipped ⇒ record and keys\n // unchanged), which is the identity precondition derived mode\n // requires. Cost drops from n inserts to `flipped` edits.\n {\n orderIsProven: true,\n derivedById: {\n base: captured.visible.rows,\n removedIds: flippedOut,\n addedEntries: flippedIn,\n },\n }),\n });\n // The verdict pass above already set a bit for every member, so the new\n // root takes its bitset directly — no second walk over the tree.\n visibleSlots = nextVisibleSlots;\n }\n const root = Object.freeze({\n revision,\n parentRevision: revision - 1,\n rows,\n sourceOrder: captured.sourceOrder,\n // A filter-only change reconstructs no record and touches no slot, so\n // the slot vector and its domain carry by identity with the rows HAMT.\n recordsBySlot: captured.recordsBySlot,\n slotCapacity: captured.slotCapacity,\n visibleSlots,\n visible,\n queryPlan: nextPlan,\n expansion: captured.expansion,\n cause: Object.freeze({ kind: \"set-query\" }),\n });\n if (instrumentation !== undefined) {\n instrumentation.work.filterRebuilds += 1;\n instrumentation.work.evaluationCacheAdoptions += 1;\n instrumentation.work.filterRowsFlipped += flipped;\n instrumentation.work.filterMergeSortedInsertions += flippedIn.length;\n instrumentation.work.filterRebuildMs += Math.max(0, now() - startedAt);\n }\n return root;\n}\n","/**\n * Filter verdicts are not stored. A committed root already carries the answer\n * structurally: a row passes this root's filters exactly when it is a MEMBER\n * of the root's visible structure. This module is the one place that knows\n * which structure answers for which root shape.\n *\n * - **Flat root** (`query.rowGroups.length === 0`): `root.visible.rows` holds\n * one entry per passing row and nothing else, so membership is a lookup.\n * This is the same predicate `nearestVisibleRef` has always used.\n * - **Grouped root**: `root.visible.rows` is deliberately EMPTY (a grouped\n * visible index attaches the group index to an empty flat tree), so the\n * answer lives in the group index: every inserted row — passing or not —\n * gets a `rowParents` entry, and only passing rows are inserted into their\n * leaf group's `leaves` tree. So `rowParents` locates the leaf group and\n * `leaves` holds the verdict.\n *\n * Absence is the answer, not a fault: a row this root never saw, or one its\n * filters reject, is simply not a member. Nothing here fails loud.\n *\n * These read a COMMITTED root, so they answer \"did this row pass under the\n * plan that built this root\" — the OLD verdict at every site that compares\n * against a new one. A NEW verdict is computed, never resolved: producers\n * call `filterVerdict(plan, record)` and use it locally to decide where the\n * row goes.\n */\nimport { getGroupIndex, rowPassesFilterInGroupIndex } from \"./group-index\";\n/**\n * The grouped half of the seam, re-exported for callers that hold a group\n * index rather than a root (a transaction rebuilds the index, so those\n * callers must read the PREVIOUS one explicitly). Its body lives in\n * `./group-index` because it reads that module's own invariant, and because\n * importing it back from here would cycle.\n */\nexport { rowPassesFilterInGroupIndex };\n/** Did `rowId` pass the filters of the plan that built `root`? */\nexport function rowPassesFilter(root, rowId) {\n const grouped = getGroupIndex(root.visible);\n return grouped === undefined\n ? root.visible.rows.get(rowId) !== undefined\n : rowPassesFilterInGroupIndex(grouped, rowId);\n}\n","/**\n * Synchronous whole-root rebuild for a sort-only plan change on an ungrouped\n * query. Runs to completion on the caller's stack — the deliberate trade\n * measured in #457: scheduler hops cost frames in the browser, and identity\n * carry makes the total work small enough to spend inline. No record is\n * rebuilt and no rows transient is opened: the committed root reuses the\n * captured `rows` map BY IDENTITY, and only the next plan's sort-key store\n * and the visible tree are produced fresh.\n */\nimport { compareWithSortKeys, fillSortKeysFromPrevious, isSortOnlyChange, } from \"./compiled-query\";\nimport { rowPassesFilter } from \"./filter-membership\";\nimport { compareOrderStatisticTreeIds, createOrderStatisticTreeFromSortedEntries, instrumentOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { createFlatVisibleTree } from \"./visible-index\";\nexport function rebuildRootForSortOnlyChange(options) {\n const { captured, nextPlan, revision, now, instrumentation } = options;\n if (!isSortOnlyChange(captured.queryPlan, nextPlan)) {\n throw new TypeError(\"Synchronous rebuild requires a sort-only plan change.\");\n }\n if (nextPlan.query.rowGroups.length > 0) {\n throw new TypeError(\"Synchronous rebuild requires an ungrouped query.\");\n }\n const startedAt = now();\n // Decorated sort: keys resolve ONCE per row here (the fill already returns\n // them) and travel with the record, so the O(n log n) comparison loop does\n // no WeakMap lookups — measured at 50k, per-comparison resolution costs\n // ~4x the decorated form. The pairs ARE the tree's entry type, so the\n // sorted array feeds the bulk constructor directly.\n const visible = [];\n // `range(0, size)` rather than `entries()`: this walk always runs to\n // completion into an array, and the tree's non-generator walk is the\n // cheaper way to get one (see `iterateEntries`).\n for (const source of captured.sourceOrder.range(0, captured.sourceOrder.size)) {\n const previous = captured.rows.get(source.rowId);\n if (previous === undefined)\n continue;\n // Seed the NEXT plan's store for every carried record — the one part of\n // a record's derived state that is plan-scoped. Everything else\n // (metadata, publicRow, integrity) carries with the record itself.\n const keys = fillSortKeysFromPrevious(nextPlan, captured.queryPlan, previous, instrumentation);\n // A sort-only change cannot move a row across the filter, so the CAPTURED\n // root's membership is this row's verdict under the next plan too.\n if (rowPassesFilter(captured, source.rowId)) {\n visible.push(Object.freeze({ record: previous, keys }));\n }\n }\n // The key comparator already totalizes distinct rows via its final\n // sourceOrder comparison, so the id clause is unreachable today. It stays\n // because the composite mirrors the tree's own order (comparator, then id)\n // exactly, so this sort can never diverge from the bulk constructor's\n // strict-order verification even if the comparator ever stopped being\n // total. Every record's keys were seeded into nextPlan's store by the\n // carry loop above, so later insert sites can decorate their entries from\n // the store; the tree's own comparator reads only entry-carried keys.\n visible.sort((left, right) => compareWithSortKeys(nextPlan, left.record, left.keys, right.record, right.keys) || compareOrderStatisticTreeIds(left.record.rowId, right.record.rowId));\n const tree = createOrderStatisticTreeFromSortedEntries(instrumentOrderStatisticTree(createFlatVisibleTree(nextPlan), instrumentation), visible, \n // Order only. The `visible.sort` above is under the tree's own composite\n // order (comparator, then id) over ids drawn from a HAMT, so it is\n // strictly increasing by construction and the n−1 verification can only\n // re-confirm it. Derived byId is deliberately NOT taken: a sort-only\n // change keeps the same entry SET but allocates a fresh entry object per\n // row to carry the next plan's keys, so every \"survivor\" is a new object\n // and a derived map would keep pointing at the previous plan's entries.\n { orderIsProven: true });\n const root = Object.freeze({\n revision,\n parentRevision: revision - 1,\n // Identity — the entire point: records, publicRow, integrity, and the\n // rows HAMT all survive a sort-only change untouched.\n rows: captured.rows,\n sourceOrder: captured.sourceOrder,\n // Same identity carry: a sort-only change touches no record and no slot.\n recordsBySlot: captured.recordsBySlot,\n slotCapacity: captured.slotCapacity,\n // A sort-only change reorders the members but keeps the member SET\n // identical (the loop above pushed exactly the captured membership), so\n // the bitset carries by identity too.\n visibleSlots: captured.visibleSlots,\n visible: Object.freeze({ rows: tree }),\n queryPlan: nextPlan,\n expansion: captured.expansion,\n cause: Object.freeze({ kind: \"set-query\" }),\n });\n if (instrumentation !== undefined) {\n instrumentation.work.synchronousRebuilds += 1;\n instrumentation.work.synchronousRebuildMs += Math.max(0, now() - startedAt);\n }\n return root;\n}\n","import { adoptEvaluationCache, fillSortKeysFromPrevious, sortKeysIfPasses, filterVerdict, isFilterOnlyChange, } from \"./compiled-query\";\nimport { createPersistentMap, instrumentPersistentMap, } from \"./persistent/persistent-map\";\nimport { instrumentOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { forEachSlotEntry, slotVectorFromEntries } from \"./slot-vector\";\nimport { orderedRowEntry } from \"./ordered-row-entry\";\nimport { createFlatVisibleTree } from \"./visible-index\";\nimport { clearMembershipBit, cloneMembership, createMembership, setMembershipBit, } from \"./membership-bitset\";\nimport { registerCooperativeTransitionCandidateDiagnostics, } from \"./cooperative-transition\";\n/**\n * The flat (ungrouped) cooperative transition candidate. Builds against an\n * immutable source root and replays exact live-row deltas; nothing reachable\n * here is published before `finish` returns the swap root.\n *\n * A flat candidate has no group index, no bulk builder, no seal phase, and no\n * expansion-override reconciliation: it completes when the source sweep and\n * the delta queue drain.\n *\n * Two lanes (#490):\n *\n * - **Identity-carry** (flat `set-query` over a flat captured root): records,\n * the rows HAMT and the slot vector all carry BY IDENTITY from the captured\n * root — the sweep only re-runs the filter verdict, decorates survivors\n * with next-plan sort keys, and sets membership bits. Zero evaluations,\n * zero HAMT writes, zero record allocations.\n * - **Evaluate** (`set-derivations`, or a grouped captured root): metadata\n * genuinely changes, so every row is re-evaluated into a fresh record — but\n * the containers are the identity lane's UPGRADED forms from construction:\n * a transient rows map (started EMPTY, not from the captured map — the\n * records are re-evaluated, so nothing captured can carry), the transient\n * visible tree, the mutable slot array and the membership bitset, all\n * frozen/chunked once at `finish`.\n */\nexport function createFlatCooperativeCandidate(options) {\n const operation = options.operation;\n const instrumentation = options.instrumentation;\n /**\n * Lane eligibility (spec amendment): identity-carry requires the CAPTURED\n * plan to be ungrouped too — a grouped→flat `set-query` captures records\n * whose metadata still holds the grouped `groupPath`/`aggregateLeaves`, so\n * those transitions re-evaluate. The NEXT plan is already known flat: the\n * shared constructor dispatches here only when\n * `queryPlan.query.rowGroups.length === 0`.\n */\n const identityCarry = options.operation === \"set-query\" &&\n options.captured.queryPlan.query.rowGroups.length === 0;\n /**\n * Whole-store evaluation-cache handoff, gated on the SAME precondition the\n * synchronous filter rebuild owns (`adoptEvaluationCache`'s documented\n * contract): only a filter-only change leaves every cached field —\n * including the sort-key arrays, which are index-aligned to the plan that\n * wrote them — valid under the next plan. On a sort-changed set-query the\n * per-row `fillSortKeysFromPrevious` below carries what it can instead.\n * Pure perf lever either way: nothing below depends on the adoption.\n */\n const adopted = isFilterOnlyChange(options.captured.queryPlan, options.queryPlan);\n if (adopted) {\n adoptEvaluationCache(options.queryPlan, options.captured.queryPlan);\n if (instrumentation !== undefined) {\n instrumentation.work.evaluationCacheAdoptions += 1;\n }\n }\n let retained = {\n captured: options.captured,\n queryPlan: options.queryPlan,\n sourceOrder: options.captured.sourceOrder,\n expansion: options.captured.expansion,\n transientFlatRows: instrumentOrderStatisticTree(createFlatVisibleTree(options.queryPlan), instrumentation).asTransient(),\n recordsBySlot: [],\n slotCapacity: options.captured.slotCapacity,\n membership: createMembership(options.captured.slotCapacity),\n sweep: identityCarry ? { chunkIndex: 0 } : null,\n transientRows: identityCarry\n ? null\n : instrumentPersistentMap(createPersistentMap(), instrumentation).asTransient(),\n iterator: identityCarry ? null : options.captured.sourceOrder.entries(),\n deltas: [],\n reconciledExpansion: undefined,\n };\n // Candidate methods retain only the nullable state binding below. Clear the\n // input container so it cannot independently keep the captured root alive.\n options = undefined;\n let deltaIndex = 0;\n let deltaRowIndex = 0;\n let deltaRowPhase = \"remove\";\n let completedRows = 0;\n let totalRows = retained.captured.rows.size;\n let released = false;\n const resetOverrideReconciliation = (state) => {\n // A flat candidate never starts an override reconciliation pass, so the\n // grouped module's `totalRows -= reconciliation.remaining` shrink can\n // never apply here; the only effect this reset has on the flat path is\n // clearing the reconciled-expansion marker.\n state.reconciledExpansion = undefined;\n };\n /**\n * Identity-carry unit: the record carries WHOLE — metadata included —\n * because on an ungrouped `set-query` no metadata field can change:\n * `groupPath` is `[]` under both plans (both are flat — the lane predicate\n * above pins the captured side), and `aggregateLeaves` derive from\n * derivations, which `set-query` does not touch. Leaves DO embed sortKeys\n * in their `dependency`, and they have flat-path readers: the group index\n * consumes them wholesale (`group-index.ts`), and `transaction-draft.ts`\n * reads them on flat commits too — but only plan-stable fields (`columnId`\n * and the column definition's own `aggregate` object in its leaf compare,\n * and `rebaseSourceOrder` rewrites `dependency.sourceOrder` while carrying\n * the embedded sort keys along unchanged). So stale embedded sortKeys can\n * PROPAGATE through later flat transactions without ever being read as\n * sort authority; a future grouped-leaves reader must re-derive before\n * consuming a root produced here. Sort keys proper are the one\n * plan-scoped piece, resolved via the per-row carry fill exactly as\n * `sort-rebuild.ts` does.\n */\n const carryRecord = (record) => {\n const state = retained;\n if (state === undefined)\n return;\n if (instrumentation !== undefined) {\n // `rowsEvaluated` deliberately NOT incremented: nothing is evaluated\n // on this lane — that zero is the dense claim `work.test.ts` pins.\n instrumentation.work.transitionRows += 1;\n }\n if (adopted) {\n // Fused: the adopted cache answers verdict AND keys from ONE read —\n // `work.test.ts` pins the one-lookup-per-swept-row budget, and the\n // un-fused arm below stays pinned as the counter's control.\n const keys = sortKeysIfPasses(state.queryPlan, record, instrumentation);\n if (keys !== undefined) {\n state.transientFlatRows.insertOrReplace(Object.freeze({ record, keys }));\n setMembershipBit(state.membership, record.slot);\n }\n return;\n }\n if (filterVerdict(state.queryPlan, record, instrumentation)) {\n const keys = fillSortKeysFromPrevious(state.queryPlan, state.captured.queryPlan, record, instrumentation);\n state.transientFlatRows.insertOrReplace(Object.freeze({ record, keys }));\n setMembershipBit(state.membership, record.slot);\n }\n };\n /**\n * Converts the identity-carry candidate to replayable form on the FIRST\n * delta: keyed mutation via the transient, per-slot mutation via a whole\n * copy of the carried vector. From here `finish` builds fresh structures\n * (the upgraded arm) — the carried ones are no longer the truth.\n */\n const upgradeForReplay = (state) => {\n state.transientRows = state.captured.rows.asTransient();\n forEachSlotEntry(state.captured.recordsBySlot, (record, slot) => {\n state.recordsBySlot[slot] = record;\n });\n };\n const removeRecord = (record) => {\n const state = retained;\n if (state === undefined)\n return;\n // `transientRows` is non-null whenever a remove can run: the evaluate\n // lane arms it at construction, and the identity lane's `append` (which\n // precedes every replay unit) upgrades before the first one.\n state.transientRows.delete(record.rowId);\n clearMembershipBit(state.membership, record.slot);\n state.recordsBySlot[record.slot] = undefined;\n state.transientFlatRows.remove(record.rowId);\n };\n const insertRecord = (source) => {\n const state = retained;\n if (state === undefined)\n return;\n if (identityCarry) {\n // Identity-lane replay insert (build routes through `sweepChunk`, so\n // `transientRows` is already armed here): the delta TARGET root's\n // record carries by identity too — it was evaluated under the model's\n // still-committed plan (the captured plan's lineage), and the\n // candidate plan differs only in filter/sort, which cannot change\n // metadata (see `carryRecord`). Only the verdict is re-run, under the\n // candidate's plan.\n state.transientRows.set(source.rowId, source);\n state.recordsBySlot[source.slot] = source;\n carryRecord(source);\n return;\n }\n // Evaluate lane, build AND replay: metadata genuinely depends on the\n // next plan's derivations (or the captured root was grouped), so the\n // record is rebuilt — but into the transient containers, so the per-row\n // cost is the evaluation itself, not a HAMT path copy.\n if (instrumentation !== undefined) {\n instrumentation.work.transitionRows += 1;\n instrumentation.work.rowsEvaluated += 1;\n }\n const metadata = state.queryPlan.evaluate({\n rowId: source.rowId,\n row: source.row,\n sourceOrder: source.sourceOrder,\n slot: source.slot,\n });\n const record = Object.freeze({ ...source, metadata });\n state.transientRows.set(record.rowId, record);\n state.recordsBySlot[record.slot] = record;\n // Computed here, used here: the flat tree this inserts into is where\n // the verdict is recorded, and the membership bit rides along.\n if (filterVerdict(state.queryPlan, record)) {\n state.transientFlatRows.insertOrReplace(orderedRowEntry(state.queryPlan, record));\n setMembershipBit(state.membership, record.slot);\n }\n };\n const removeReplayRow = (rowId) => {\n const state = retained;\n if (state === undefined)\n return;\n const previous = state.transientRows.get(rowId);\n if (previous !== undefined)\n removeRecord(previous);\n };\n const insertReplayRow = (target, rowId) => {\n if (retained === undefined)\n return;\n const next = target.rows.get(rowId);\n if (next !== undefined)\n insertRecord(next);\n };\n /**\n * Identity lane's build unit: the next ALLOCATED slot-vector chunk, whole\n * (M2 amendment, #490). Under #518's slice runner the budget clock is\n * consulted after the first completed unit and then once per 32-unit\n * stride, so a ~1ms chunk unit means slices carry one or two chunks and\n * the 50k sweep pays ~50 scheduler hops instead of ~196 — the per-row\n * unit's slice overhead was the remaining fit-estimate gap, and\n * `maxUnitsPerSlice` becomes a non-binding backstop for this lane.\n *\n * `completedRows` stays ROW-denominated per the status contract: it\n * advances by the POPULATED slots processed, so holes skip for free and\n * the terminal accounting (`completedRows === totalRows` at settle) stays\n * exact. An absent chunk is all holes — zero rows — so it is skipped\n * without spending the unit; a present chunk bounds the unit's work at\n * one `SLOT_VECTOR_CHUNK` scan regardless of how many slots survive.\n */\n const sweepChunk = (state) => {\n const cursor = state.sweep;\n if (cursor === null)\n return false;\n const chunks = state.captured.recordsBySlot.chunks;\n while (cursor.chunkIndex < chunks.length) {\n const chunk = chunks[cursor.chunkIndex];\n cursor.chunkIndex += 1;\n if (chunk === undefined)\n continue;\n for (let offset = 0; offset < chunk.length; offset += 1) {\n const record = chunk[offset];\n if (record !== undefined) {\n carryRecord(record);\n completedRows += 1;\n }\n }\n return true;\n }\n state.sweep = null;\n return false;\n };\n const candidate = {\n get completedRows() {\n return completedRows;\n },\n get totalRows() {\n return totalRows;\n },\n append(delta) {\n const state = retained;\n if (state === undefined)\n return;\n resetOverrideReconciliation(state);\n if (identityCarry && state.transientRows === null) {\n upgradeForReplay(state);\n }\n state.deltas.push(delta);\n // Capacity is monotone across commits, so the widest replayed target\n // bounds every slot this candidate can ever bind (still a captured\n // root's value — the live allocator is never consulted).\n state.slotCapacity = Math.max(state.slotCapacity, delta.target.slotCapacity);\n // Bitset capacity decision: the bitset is maintained incrementally, so\n // widening reallocates it here — a whole copy into the wider word\n // array. Provably correct because slots are stable (a bit's index\n // never changes) and setting a bit beyond a Uint32Array's length is a\n // silent no-op, so the copy MUST precede any replayed write to a\n // grown slot; `append` runs before every such write.\n // `membership` is non-null on every live candidate (both lanes arm it\n // at construction; only `release` nulls it, and the `retained` guard\n // above covers that).\n if ((state.slotCapacity + 31) >>> 5 > state.membership.length) {\n state.membership = cloneMembership(state.membership, state.slotCapacity);\n }\n totalRows += delta.affectedRowIds.length * 2 + 1;\n },\n step() {\n const state = retained;\n if (state === undefined)\n return true;\n if (identityCarry) {\n if (sweepChunk(state))\n return false;\n }\n else if (state.iterator !== null) {\n const source = state.iterator.next();\n if (!source.done) {\n const previous = state.captured.rows.get(source.value.rowId);\n if (previous !== undefined)\n insertRecord(previous);\n completedRows += 1;\n return false;\n }\n state.iterator = null;\n }\n while (deltaIndex < state.deltas.length) {\n const delta = state.deltas[deltaIndex];\n if (delta === null) {\n deltaIndex += 1;\n deltaRowIndex = 0;\n deltaRowPhase = \"remove\";\n continue;\n }\n const rowId = delta.affectedRowIds[deltaRowIndex];\n if (rowId !== undefined) {\n if (deltaRowPhase === \"remove\") {\n removeReplayRow(rowId);\n deltaRowPhase = \"insert\";\n }\n else {\n insertReplayRow(delta.target, rowId);\n deltaRowPhase = \"remove\";\n deltaRowIndex += 1;\n }\n completedRows += 1;\n return false;\n }\n state.sourceOrder = delta.target.sourceOrder;\n state.expansion = delta.target.expansion;\n resetOverrideReconciliation(state);\n state.deltas[deltaIndex] = null;\n deltaIndex += 1;\n deltaRowIndex = 0;\n deltaRowPhase = \"remove\";\n completedRows += 1;\n return false;\n }\n // Terminal condition: the flat candidate is complete once the source\n // sweep and the delta queue drain. This mirrors the grouped module's\n // `reconcileOneOverride` short-circuit for a groupless state byte for\n // byte — it marks the expansion reconciled and reports completion in\n // the same step, without counting a unit against `completedRows`.\n state.reconciledExpansion = state.expansion;\n return true;\n },\n finish(revision) {\n const state = retained;\n if (state === undefined)\n throw new Error(\"Released transition candidate.\");\n const visible = Object.freeze({\n rows: state.transientFlatRows.freeze(),\n });\n if (identityCarry && state.transientRows === null) {\n // Delta-free identity carry: rows, the slot vector and its domain\n // all carry from the captured root's own objects, and membership is\n // the bitset the sweep already filled — no `membershipFromFlatTree`\n // walk, no slot sweep, on the finish stack.\n return Object.freeze({\n revision,\n parentRevision: revision - 1,\n rows: state.captured.rows,\n sourceOrder: state.sourceOrder,\n recordsBySlot: state.captured.recordsBySlot,\n slotCapacity: state.slotCapacity,\n visibleSlots: state.membership,\n visible,\n queryPlan: state.queryPlan,\n expansion: state.expansion,\n cause: Object.freeze({ kind: operation }),\n });\n }\n const slotEntries = [];\n for (let slot = 0; slot < state.recordsBySlot.length; slot += 1) {\n const record = state.recordsBySlot[slot];\n if (record !== undefined)\n slotEntries.push([slot, record]);\n }\n // Upgraded identity lane and evaluate lane share this arm: freeze the\n // transient rows map, chunk the mutable slot array, and publish the\n // membership bitset exactly as maintained by the sweep and replay —\n // no lane in this module walks the visible tree for membership.\n return Object.freeze({\n revision,\n parentRevision: revision - 1,\n rows: state.transientRows.freeze(),\n sourceOrder: state.sourceOrder,\n recordsBySlot: slotVectorFromEntries(slotEntries, state.slotCapacity),\n slotCapacity: state.slotCapacity,\n visibleSlots: state.membership,\n visible,\n queryPlan: state.queryPlan,\n expansion: state.expansion,\n cause: Object.freeze({ kind: operation }),\n });\n },\n release() {\n const state = retained;\n if (state === undefined)\n return;\n released = true;\n state.iterator = null;\n state.sweep = null;\n state.transientRows = null;\n state.transientFlatRows = null;\n state.membership = null;\n state.deltas.fill(null);\n state.deltas.length = 0;\n state.recordsBySlot.length = 0;\n state.reconciledExpansion = undefined;\n retained = undefined;\n },\n };\n registerCooperativeTransitionCandidateDiagnostics(candidate, () => Object.freeze({\n released,\n hasCapturedRoot: retained !== undefined,\n hasQueryPlan: retained !== undefined,\n hasIterator: retained !== undefined &&\n (identityCarry ? retained.sweep !== null : retained.iterator !== null),\n deltaCount: retained?.deltas.reduce((count, delta) => count + (delta === null ? 0 : 1), 0) ?? 0,\n hasRows: retained !== undefined,\n hasSourceOrder: retained !== undefined,\n hasExpansion: retained !== undefined,\n hasFlatRows: retained !== undefined,\n // The flat lane never holds a group index or a bulk builder; the shape\n // matches the grouped module's registration with the grouped-only\n // fields pinned to their groupless values.\n hasGroups: false,\n deltaSlotCount: retained?.deltas.length ?? 0,\n processedDeltaCount: retained === undefined ? 0 : deltaIndex,\n retainedDeltaRootCount: retained?.deltas.reduce((count, delta) => count + (delta === null ? 0 : 1), 0) ?? 0,\n overrideReconciliationRemaining: 0,\n }));\n return candidate;\n}\n","import { attachGroupIndex, createGroupIndex, createGroupIndexBuildDraft, getGroupIndex, setGroupOverride, updateGroupIndex, } from \"./group-index\";\nimport { createPersistentMap, instrumentPersistentMap, } from \"./persistent/persistent-map\";\nimport { instrumentOrderStatisticTree } from \"./persistent/order-statistic-tree\";\nimport { slotVectorFromEntries } from \"./slot-vector\";\nimport { EMPTY_MEMBERSHIP } from \"./membership-bitset\";\nimport { createFlatVisibleTree } from \"./visible-index\";\nimport { createFlatCooperativeCandidate } from \"./flat-cooperative-candidate\";\nconst candidateDiagnostics = new WeakMap();\n/**\n * Registers a candidate's diagnostics reader in the shared WeakMap so\n * `getCooperativeTransitionCandidateDiagnosticsForTesting` serves every lane\n * (the grouped lanes here and the flat lane in its own module) uniformly.\n */\nexport function registerCooperativeTransitionCandidateDiagnostics(candidate, read) {\n candidateDiagnostics.set(candidate, read);\n}\nexport function getCooperativeTransitionCandidateDiagnosticsForTesting(candidate) {\n const read = candidateDiagnostics.get(candidate);\n if (read === undefined) {\n throw new TypeError(\"Diagnostics require a cooperative transition candidate.\");\n }\n return read();\n}\nconst DEFAULT_BUDGET_MS = 0.25;\n// A clock may be coarse, mocked, or stalled. This cap guarantees a yield while\n// keeping enough per-slice work to amortize scheduler overhead.\nconst DEFAULT_MAX_UNITS_PER_SLICE = 256;\n/**\n * The budget clock is consulted after the FIRST completed unit and then once\n * per this many completed units — not once per unit (#500): reading `now()`\n * every unit was itself a measurable share of slice time once seal units\n * became row-sized (~1-2µs each). Worst-case budget overshoot is\n * stride × per-unit cost ≈ 32 × 2µs ≈ 64µs (a full stride of units runs\n * between two consecutive checks) — noise against a 16.7ms\n * frame. The first-unit check keeps a slice honest when individual units are\n * expensive (custom aggregators and accessors run arbitrary consumer code):\n * one over-budget unit ends the slice immediately instead of running a full\n * stride of them. The stride divides DEFAULT_MAX_UNITS_PER_SLICE\n * (32 × 8 = 256), so the hard cap still lands exactly on a stride boundary.\n */\nexport const TRANSITION_CLOCK_CHECK_STRIDE = 32;\nfunction bestEffortCancel(cancel) {\n try {\n cancel?.();\n }\n catch {\n // Scheduler cancellation is advisory infrastructure cleanup. It must not\n // interrupt the model-owned release and settlement that follows.\n }\n}\nfunction postTaskScheduler(postTask, fallback) {\n return {\n schedule(task) {\n const controller = typeof AbortController === \"function\" ? new AbortController() : null;\n let cancelled = false;\n let ran = false;\n let cancelFallback;\n const run = () => {\n if (cancelled || ran)\n return;\n ran = true;\n task();\n };\n const recover = () => {\n if (cancelled || ran || cancelFallback !== undefined)\n return;\n cancelFallback = fallback.schedule(run);\n };\n try {\n void Promise.resolve(postTask(run, controller ? { signal: controller.signal } : undefined)).catch(recover);\n }\n catch {\n recover();\n }\n return () => {\n if (cancelled)\n return;\n cancelled = true;\n const cancel = cancelFallback;\n cancelFallback = undefined;\n try {\n controller?.abort();\n }\n catch {\n // A hostile AbortController is no more authoritative than the task.\n }\n bestEffortCancel(cancel);\n };\n },\n };\n}\nfunction messageChannelScheduler() {\n if (typeof MessageChannel !== \"function\")\n return null;\n return {\n schedule(task) {\n const channel = new MessageChannel();\n let cancelled = false;\n const close = () => {\n try {\n channel.port1.close();\n }\n catch {\n // Closing a host channel is best-effort cleanup.\n }\n try {\n channel.port2.close();\n }\n catch {\n // Closing a host channel is best-effort cleanup.\n }\n };\n channel.port1.onmessage = () => {\n close();\n if (!cancelled)\n task();\n };\n try {\n channel.port2.postMessage(undefined);\n }\n catch (error) {\n close();\n throw error;\n }\n return () => {\n if (cancelled)\n return;\n cancelled = true;\n close();\n };\n },\n };\n}\nfunction timeoutScheduler() {\n return {\n schedule(task) {\n const handle = setTimeout(task, 0);\n return () => clearTimeout(handle);\n },\n };\n}\nfunction fallbackScheduler() {\n const messageChannel = messageChannelScheduler();\n const timeout = timeoutScheduler();\n return {\n schedule(task) {\n if (messageChannel !== null) {\n try {\n return messageChannel.schedule(task);\n }\n catch {\n // A present but unusable MessageChannel must not strand the task.\n }\n }\n return timeout.schedule(task);\n },\n };\n}\n/** Resolves browser-preferred scheduling with a safe server/runtime fallback. */\nexport function createDefaultCooperativeTransitionScheduler() {\n const fallback = fallbackScheduler();\n try {\n const candidate = Reflect.get(globalThis, \"scheduler\");\n if (candidate && typeof candidate.postTask === \"function\") {\n return postTaskScheduler(candidate.postTask.bind(candidate), fallback);\n }\n }\n catch {\n // Host globals are not trusted; continue to the capability fallbacks.\n }\n return fallback;\n}\nexport function createCooperativeTransitionRuntime(options) {\n const budgetMs = options.budgetMs ?? DEFAULT_BUDGET_MS;\n const maxUnitsPerSlice = options.maxUnitsPerSlice ?? DEFAULT_MAX_UNITS_PER_SLICE;\n if (!Number.isFinite(budgetMs) || budgetMs <= 0) {\n throw new RangeError(\"The cooperative transition budget must be positive.\");\n }\n if (!Number.isSafeInteger(maxUnitsPerSlice) || maxUnitsPerSlice <= 0) {\n throw new RangeError(\"The cooperative transition unit cap must be a positive safe integer.\");\n }\n const scheduler = options.scheduler ?? createDefaultCooperativeTransitionScheduler();\n const instrumentedScheduler = options.instrumentation === undefined\n ? undefined\n : {\n schedule(task) {\n const token = {};\n options.instrumentation.scheduledCallbacks.add(token);\n let cancel;\n try {\n cancel = scheduler.schedule(() => {\n options.instrumentation.scheduledCallbacks.delete(token);\n task();\n });\n }\n catch (error) {\n options.instrumentation.scheduledCallbacks.delete(token);\n throw error;\n }\n return () => {\n options.instrumentation.scheduledCallbacks.delete(token);\n bestEffortCancel(cancel);\n };\n },\n };\n return Object.freeze({\n scheduler: instrumentedScheduler ?? scheduler,\n now: options.now ??\n (() => typeof performance === \"object\" &&\n performance !== null &&\n typeof performance.now === \"function\"\n ? performance.now()\n : Date.now()),\n budgetMs,\n maxUnitsPerSlice,\n instrumentation: options.instrumentation,\n });\n}\n/**\n * Runs at least one unit; the budget clock is consulted after the first\n * completed unit and then once per TRANSITION_CLOCK_CHECK_STRIDE completed\n * units (the hard unit cap is checked every unit and is a whole number of\n * strides).\n */\nexport function runCooperativeTransitionSlice(runtime, step) {\n const startedAt = runtime.now();\n let completedUnits = 0;\n do {\n if (step()) {\n if (runtime.instrumentation !== undefined) {\n runtime.instrumentation.work.schedulerSliceDurations.push(Math.max(0, runtime.now() - startedAt));\n }\n return true;\n }\n completedUnits += 1;\n } while (completedUnits < runtime.maxUnitsPerSlice &&\n ((completedUnits !== 1 &&\n completedUnits % TRANSITION_CLOCK_CHECK_STRIDE !== 0) ||\n runtime.now() - startedAt < runtime.budgetMs));\n if (runtime.instrumentation !== undefined) {\n runtime.instrumentation.work.schedulerSliceDurations.push(Math.max(0, runtime.now() - startedAt));\n }\n return false;\n}\n/**\n * Builds against an immutable source root and replays exact live-row deltas.\n * Nothing reachable here is published before `finish` returns the swap root.\n *\n * Ungrouped transitions dispatch to the flat module; the candidate built here\n * serves the two GROUPED lanes (bulk builder and incremental group index).\n */\nexport function createCooperativeTransitionCandidate(options) {\n if (options.queryPlan.query.rowGroups.length === 0) {\n return createFlatCooperativeCandidate(options);\n }\n const operation = options.operation;\n const instrumentation = options.instrumentation;\n const builtinAggregatesOnly = options.queryPlan.derivations.every((derivation) => derivation.aggregate === undefined ||\n typeof derivation.aggregate === \"string\");\n const useBulkGroupBuilder = builtinAggregatesOnly;\n const initialRows = instrumentPersistentMap(createPersistentMap(), instrumentation);\n let retained = {\n captured: options.captured,\n queryPlan: options.queryPlan,\n rows: initialRows,\n rowBuilder: useBulkGroupBuilder ? initialRows.asTransient() : undefined,\n sourceOrder: options.captured.sourceOrder,\n expansion: options.captured.expansion,\n flatRows: instrumentOrderStatisticTree(createFlatVisibleTree(options.queryPlan), instrumentation),\n recordsBySlot: [],\n slotCapacity: options.captured.slotCapacity,\n groups: !useBulkGroupBuilder\n ? createGroupIndex([], options.queryPlan, options.aggregateFilteredRows, createPersistentMap(), operation, getGroupIndex(options.captured.visible), instrumentation)\n : undefined,\n groupBuilder: !useBulkGroupBuilder\n ? undefined\n : createGroupIndexBuildDraft({\n queryPlan: options.queryPlan,\n aggregateFilteredRows: options.aggregateFilteredRows,\n operation,\n reusable: getGroupIndex(options.captured.visible),\n overrides: options.captured.expansion.overrides,\n instrumentation,\n }),\n groupSealRemaining: 0,\n iterator: options.captured.sourceOrder.entries(),\n deltas: [],\n appliedOverrides: createPersistentMap(),\n reconciledExpansion: undefined,\n overrideReconciliation: undefined,\n };\n // Candidate methods retain only the nullable state binding below. Clear the\n // input container so it cannot independently keep the captured root alive.\n options = undefined;\n let deltaIndex = 0;\n let deltaRowIndex = 0;\n let deltaRowPhase = \"remove\";\n let completedRows = 0;\n let totalRows = retained.captured.rows.size;\n let released = false;\n const resetOverrideReconciliation = (state) => {\n if (state.overrideReconciliation !== undefined) {\n totalRows -= state.overrideReconciliation.remaining;\n state.overrideReconciliation = undefined;\n }\n state.reconciledExpansion = undefined;\n };\n const reconcileGroupOverride = (state, groupId, desired) => {\n const group = state.groups?.groups.get(groupId);\n if (group === undefined) {\n state.appliedOverrides = state.appliedOverrides.delete(groupId);\n return;\n }\n if (group.override !== desired) {\n state.groups = setGroupOverride(state.groups, groupId, desired, operation);\n }\n state.appliedOverrides =\n desired === undefined\n ? state.appliedOverrides.delete(groupId)\n : state.appliedOverrides.set(groupId, desired);\n };\n const reconcileOneOverride = (state) => {\n if (state.reconciledExpansion === state.expansion)\n return true;\n let reconciliation = state.overrideReconciliation;\n if (reconciliation === undefined) {\n const remaining = state.appliedOverrides.size + state.expansion.overrides.size;\n reconciliation = {\n phase: \"remove\",\n removalIterator: state.appliedOverrides.entries(),\n desiredIterator: state.expansion.overrides.entries(),\n remaining,\n };\n state.overrideReconciliation = reconciliation;\n totalRows += remaining;\n }\n while (reconciliation.phase === \"remove\") {\n const next = reconciliation.removalIterator.next();\n if (next.done) {\n reconciliation.phase = \"apply\";\n break;\n }\n const [groupId] = next.value;\n reconcileGroupOverride(state, groupId, state.expansion.overrides.get(groupId));\n reconciliation.remaining -= 1;\n completedRows += 1;\n return false;\n }\n const next = reconciliation.desiredIterator.next();\n if (!next.done) {\n const [groupId, expanded] = next.value;\n reconcileGroupOverride(state, groupId, expanded);\n reconciliation.remaining -= 1;\n completedRows += 1;\n return false;\n }\n state.overrideReconciliation = undefined;\n state.reconciledExpansion = state.expansion;\n return true;\n };\n const removeRecord = (record) => {\n const state = retained;\n if (state === undefined)\n return;\n state.rows = state.rows.delete(record.rowId);\n state.recordsBySlot[record.slot] = undefined;\n // Replay only runs after the bulk builder (if any) sealed and published\n // its index, so a grouped candidate always has `groups` here.\n state.groups = updateGroupIndex(state.groups, [record], [], undefined, operation, instrumentation);\n };\n const insertRecord = (source) => {\n const state = retained;\n if (state === undefined)\n return;\n if (instrumentation !== undefined) {\n instrumentation.work.transitionRows += 1;\n instrumentation.work.rowsEvaluated += 1;\n }\n const metadata = state.queryPlan.evaluate({\n rowId: source.rowId,\n row: source.row,\n sourceOrder: source.sourceOrder,\n slot: source.slot,\n });\n const record = Object.freeze({ ...source, metadata });\n if (state.rowBuilder !== undefined)\n state.rowBuilder.set(record.rowId, record);\n else\n state.rows = state.rows.set(record.rowId, record);\n state.recordsBySlot[record.slot] = record;\n if (state.groupBuilder !== undefined) {\n state.groupBuilder.insert(record);\n }\n else {\n state.groups = updateGroupIndex(state.groups, [], [record], undefined, operation, instrumentation);\n }\n };\n const removeReplayRow = (rowId) => {\n const state = retained;\n if (state === undefined)\n return;\n const previous = state.rows.get(rowId);\n if (previous !== undefined)\n removeRecord(previous);\n };\n const insertReplayRow = (target, rowId) => {\n if (retained === undefined)\n return;\n const next = target.rows.get(rowId);\n if (next !== undefined)\n insertRecord(next);\n };\n const candidate = {\n get completedRows() {\n return completedRows;\n },\n get totalRows() {\n return totalRows;\n },\n append(delta) {\n const state = retained;\n if (state === undefined)\n return;\n resetOverrideReconciliation(state);\n state.deltas.push(delta);\n // Capacity is monotone across commits, so the widest replayed target\n // bounds every slot this candidate can ever bind (still a captured\n // root's value — the live allocator is never consulted).\n state.slotCapacity = Math.max(state.slotCapacity, delta.target.slotCapacity);\n totalRows += delta.affectedRowIds.length * 2 + 1;\n },\n step() {\n const state = retained;\n if (state === undefined)\n return true;\n if (state.iterator !== null) {\n const source = state.iterator.next();\n if (!source.done) {\n const previous = state.captured.rows.get(source.value.rowId);\n if (previous !== undefined)\n insertRecord(previous);\n completedRows += 1;\n return false;\n }\n state.iterator = null;\n if (state.groupBuilder !== undefined) {\n // Seal units are ROWS, not cells: the builder charges one unit per\n // (row, group node) — a unit seals that row's measures across all\n // its aggregated columns and both population roots — plus two\n // bookkeeping units per group node (finalize + edge). O(R) total,\n // not R × aggregated columns × 2 roots (#500).\n state.groupSealRemaining =\n state.groupBuilder.pendingFinalizationCount;\n totalRows += state.groupSealRemaining;\n }\n }\n if (state.groupBuilder !== undefined) {\n const builder = state.groupBuilder;\n const complete = builder.sealStep();\n if (state.groupSealRemaining > 0) {\n state.groupSealRemaining -= 1;\n completedRows += 1;\n }\n if (complete) {\n state.groups = builder.finish();\n builder.release();\n state.groupBuilder = undefined;\n state.rows = state.rowBuilder.freeze();\n state.rowBuilder = undefined;\n state.appliedOverrides = state.captured.expansion.overrides;\n state.reconciledExpansion = state.captured.expansion;\n }\n return false;\n }\n while (deltaIndex < state.deltas.length) {\n const delta = state.deltas[deltaIndex];\n if (delta === null) {\n deltaIndex += 1;\n deltaRowIndex = 0;\n deltaRowPhase = \"remove\";\n continue;\n }\n const rowId = delta.affectedRowIds[deltaRowIndex];\n if (rowId !== undefined) {\n if (deltaRowPhase === \"remove\") {\n removeReplayRow(rowId);\n deltaRowPhase = \"insert\";\n }\n else {\n insertReplayRow(delta.target, rowId);\n deltaRowPhase = \"remove\";\n deltaRowIndex += 1;\n }\n completedRows += 1;\n return false;\n }\n state.sourceOrder = delta.target.sourceOrder;\n state.expansion = delta.target.expansion;\n resetOverrideReconciliation(state);\n state.deltas[deltaIndex] = null;\n deltaIndex += 1;\n deltaRowIndex = 0;\n deltaRowPhase = \"remove\";\n completedRows += 1;\n return false;\n }\n return reconcileOneOverride(state);\n },\n finish(revision) {\n const state = retained;\n if (state === undefined)\n throw new Error(\"Released transition candidate.\");\n if (state.groupBuilder !== undefined ||\n state.groups === undefined ||\n state.reconciledExpansion !== state.expansion) {\n throw new Error(\"Transition expansion overrides are not reconciled.\");\n }\n const visible = attachGroupIndex(state.flatRows, state.groups);\n const slotEntries = [];\n for (let slot = 0; slot < state.recordsBySlot.length; slot += 1) {\n const record = state.recordsBySlot[slot];\n if (record !== undefined)\n slotEntries.push([slot, record]);\n }\n return Object.freeze({\n revision,\n parentRevision: revision - 1,\n rows: state.rows,\n sourceOrder: state.sourceOrder,\n recordsBySlot: slotVectorFromEntries(slotEntries, state.slotCapacity),\n slotCapacity: state.slotCapacity,\n // Grouped transitions keep answering visibility from the group\n // index — sentinel. (Flat transitions live in their own module and\n // publish real membership.)\n visibleSlots: EMPTY_MEMBERSHIP,\n visible,\n queryPlan: state.queryPlan,\n expansion: state.expansion,\n cause: Object.freeze({ kind: operation }),\n });\n },\n release() {\n const state = retained;\n if (state === undefined)\n return;\n released = true;\n state.iterator = null;\n state.groupBuilder?.release();\n state.groupBuilder = undefined;\n state.rowBuilder = undefined;\n state.groupSealRemaining = 0;\n state.deltas.fill(null);\n state.deltas.length = 0;\n state.recordsBySlot.length = 0;\n state.overrideReconciliation = undefined;\n state.reconciledExpansion = undefined;\n retained = undefined;\n },\n };\n candidateDiagnostics.set(candidate, () => Object.freeze({\n released,\n hasCapturedRoot: retained !== undefined,\n hasQueryPlan: retained !== undefined,\n hasIterator: retained?.iterator !== null && retained !== undefined,\n deltaCount: retained?.deltas.reduce((count, delta) => count + (delta === null ? 0 : 1), 0) ?? 0,\n hasRows: retained !== undefined,\n hasSourceOrder: retained !== undefined,\n hasExpansion: retained !== undefined,\n hasFlatRows: retained !== undefined,\n hasGroups: retained?.groups !== undefined || retained?.groupBuilder !== undefined,\n deltaSlotCount: retained?.deltas.length ?? 0,\n processedDeltaCount: retained === undefined ? 0 : deltaIndex,\n retainedDeltaRootCount: retained?.deltas.reduce((count, delta) => count + (delta === null ? 0 : 1), 0) ?? 0,\n overrideReconciliationRemaining: retained?.overrideReconciliation?.remaining ?? 0,\n }));\n return candidate;\n}\n","import { isPretableFilterGroup } from \"./column-types\";\nimport { runCooperativeTransitionSlice, } from \"./cooperative-transition\";\nimport { PretableRowModelError, } from \"./errors\";\nimport { rowPassesFilter } from \"./filter-membership\";\nimport { createOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { createPersistentMap, } from \"./persistent/persistent-map\";\nconst DEFAULT_RESULT_LIMIT = 100;\nconst MAX_RESULT_LIMIT = 1_000;\nconst DEFAULT_CACHE_CAPACITY = 8;\nexport class PretableDistinctValueCancelledError extends Error {\n reason;\n name = \"PretableDistinctValueCancelledError\";\n constructor(reason) {\n super(`The distinct-value query was ${reason}.`);\n this.reason = reason;\n }\n}\nconst modelManagers = new WeakMap();\n/** Direct internal test seam; intentionally not exported from the barrel. */\nexport function getDistinctValueDiagnosticsForTesting(model) {\n const manager = modelManagers.get(model);\n if (manager === undefined) {\n throw new TypeError(\"Diagnostics require a local Pretable row model.\");\n }\n return manager.diagnostics();\n}\nconst identityIds = new WeakMap();\nlet nextIdentityId = 1;\nfunction identityId(value) {\n if (value === undefined)\n return 0;\n const existing = identityIds.get(value);\n if (existing !== undefined)\n return existing;\n const id = nextIdentityId++;\n identityIds.set(value, id);\n return id;\n}\nfunction captureQueryOptions(options) {\n if (options !== undefined &&\n (options === null || typeof options !== \"object\")) {\n throw new TypeError(\"Distinct-value options must be an object.\");\n }\n const search = options?.search;\n const start = options?.start ?? 0;\n const limit = options?.limit ?? DEFAULT_RESULT_LIMIT;\n const population = options?.population ?? \"all\";\n const includeBlanks = options?.includeBlanks ?? false;\n const blankOrder = options?.blankOrder ?? \"last\";\n if (search !== undefined && typeof search !== \"string\") {\n throw new TypeError(\"Distinct-value search must be a string.\");\n }\n if (!Number.isSafeInteger(start) || start < 0) {\n throw new RangeError(\"Distinct-value start must be a non-negative safe integer.\");\n }\n if (!Number.isSafeInteger(limit) || limit <= 0 || limit > MAX_RESULT_LIMIT) {\n throw new RangeError(`Distinct-value limit must be a positive safe integer no greater than ${MAX_RESULT_LIMIT}.`);\n }\n if (population !== \"all\" && population !== \"filtered\") {\n throw new TypeError('Distinct-value population must be \"all\" or \"filtered\".');\n }\n if (typeof includeBlanks !== \"boolean\") {\n throw new TypeError(\"Distinct-value includeBlanks must be boolean.\");\n }\n if (blankOrder !== \"first\" && blankOrder !== \"last\") {\n throw new TypeError('Distinct-value blankOrder must be \"first\" or \"last\".');\n }\n return Object.freeze({\n search,\n start,\n limit,\n population,\n includeBlanks,\n blankOrder,\n });\n}\nfunction describeValue(value) {\n if (value === null) {\n return { id: \"null\", blank: true, blankRank: 0 };\n }\n if (value === undefined) {\n return { id: \"undefined\", blank: true, blankRank: 1 };\n }\n if (typeof value === \"string\") {\n return {\n id: `string:${value.length}:${value}`,\n blank: value.trim() === \"\",\n blankRank: 3,\n };\n }\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) {\n return { id: \"number:nan\", blank: true, blankRank: 2 };\n }\n return {\n id: `number:${Object.is(value, -0) ? \"0\" : String(value)}`,\n blank: false,\n blankRank: 0,\n };\n }\n if (typeof value === \"bigint\") {\n return { id: `bigint:${String(value)}`, blank: false, blankRank: 0 };\n }\n if (typeof value === \"boolean\") {\n return { id: `boolean:${value ? \"1\" : \"0\"}`, blank: false, blankRank: 0 };\n }\n throw new TypeError(\"Distinct values must be strings, numbers, bigints, booleans, null, or undefined.\");\n}\nfunction snapshotDistinctValue(value) {\n // Number keys use SameValueZero identity. Canonicalizing their representative\n // prevents insertion and removal history from leaking through as negative zero.\n if (typeof value === \"number\" && value === 0)\n return 0;\n return value;\n}\nconst collator = new Intl.Collator(undefined, {\n numeric: true,\n sensitivity: \"base\",\n});\nfunction defaultCompare(left, right) {\n if (typeof left === \"number\" && typeof right === \"number\") {\n return left === right ? 0 : left < right ? -1 : 1;\n }\n if (typeof left === \"bigint\" && typeof right === \"bigint\") {\n return left === right ? 0 : left < right ? -1 : 1;\n }\n if (typeof left === \"boolean\" && typeof right === \"boolean\") {\n return left === right ? 0 : left ? 1 : -1;\n }\n return collator.compare(String(left), String(right));\n}\nfunction createValueTree(column, options) {\n return createOrderStatisticTree({\n getId: (entry) => entry.id,\n compare: (left, right) => {\n if (left.blank || right.blank) {\n if (left.blank && right.blank) {\n if (left.blankRank !== right.blankRank) {\n return left.blankRank - right.blankRank;\n }\n return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;\n }\n const blankResult = options.blankOrder === \"first\" ? -1 : 1;\n return left.blank ? blankResult : -blankResult;\n }\n const compared = column.compare\n ? column.compare(left.value, right.value)\n : defaultCompare(left.value, right.value);\n if (typeof compared !== \"number\" || Number.isNaN(compared)) {\n throw new TypeError(\"Custom distinct-value comparators must return a number other than NaN.\");\n }\n return compared < 0 ? -1 : compared > 0 ? 1 : 0;\n },\n measure: {\n empty: 0,\n fromEntry: () => 1,\n combine: (left, right) => left + right,\n },\n });\n}\nfunction frame(tag, payload = \"\") {\n return `${tag}${payload.length}:${payload}`;\n}\nfunction semanticValueKey(value) {\n if (Array.isArray(value)) {\n return frame(\"a\", value.map(semanticValueKey).join(\"\"));\n }\n if (value && typeof value === \"object\") {\n const keys = Object.keys(value).sort();\n return frame(\"o\", keys\n .map((key) => frame(\"k\", key) +\n frame(\"v\", semanticValueKey(value[key])))\n .join(\"\"));\n }\n if (value === null)\n return frame(\"l\");\n if (value === undefined)\n return frame(\"u\");\n if (typeof value === \"string\")\n return frame(\"s\", value);\n if (typeof value === \"number\") {\n if (Number.isNaN(value))\n return frame(\"nN\");\n if (Object.is(value, -0))\n return frame(\"nZ\");\n return frame(\"n\", String(value));\n }\n if (typeof value === \"bigint\")\n return frame(\"i\", String(value));\n if (typeof value === \"boolean\")\n return frame(value ? \"t\" : \"f\");\n return frame(typeof value, String(value));\n}\nfunction filterSemanticKey(root) {\n const derivations = root.queryPlan\n .derivations;\n const byId = new Map(derivations.map((column) => [column.id, column]));\n const nodeKey = (node) => {\n if (isPretableFilterGroup(node)) {\n const group = node;\n /*\n * Children are keyed then sorted for the same reason the roots are:\n * and/or are commutative, so reordering a group is not a new question.\n *\n * Belt and braces today — deleting the sort breaks no test, because a\n * reordered group is matched structurally by `filterNodesEqual` and so\n * reuses its plan, and this cache never sees a root whose tree differs\n * only in child order. It stops being redundant the moment plan reuse\n * stops absorbing that case.\n */\n return frame(\"g\", frame(\"p\", group.op) +\n frame(\"k\", group.children.map(nodeKey).sort().join(\"\")));\n }\n const runtime = node;\n return frame(\"f\", frame(\"c\", runtime.columnId) +\n frame(\"t\", byId.get(runtime.columnId)?.type ?? \"\") +\n frame(\"i\", String(identityId(byId.get(runtime.columnId)?.accessor))) +\n frame(\"p\", runtime.operator) +\n frame(\"v\", semanticValueKey(runtime.value)));\n };\n return [...root.queryPlan.query.filters].map(nodeKey).sort().join(\"\");\n}\nfunction columnForDerivations(derivations, columnId) {\n const column = derivations.find((candidate) => candidate.id === columnId);\n if (column === undefined) {\n throw new PretableRowModelError(\"derivation-failed\", `Unknown distinct-value column ${columnId}.`, { operation: \"distinct-values\", columnId });\n }\n return column;\n}\nfunction cacheKey(root, column, options) {\n const filterKey = options.population === \"filtered\" ? filterSemanticKey(root) : \"\";\n return frame(\"K\", frame(\"c\", column.id) +\n frame(\"t\", column.type) +\n frame(\"p\", options.population) +\n frame(\"a\", String(identityId(column.accessor))) +\n frame(\"o\", String(identityId(column.compare))) +\n frame(options.includeBlanks ? \"b1\" : \"b0\") +\n frame(\"n\", options.blankOrder) +\n frame(\"f\", filterKey));\n}\nfunction callbackError(code, operation, columnId, rowId, cause) {\n return new PretableRowModelError(code, `Distinct-value ${code === \"accessor-failed\" ? \"accessor\" : \"comparator\"} failed for column ${columnId}.`, { operation, columnId, rowId, cause });\n}\nfunction readValue(record, column, options, operation, \n/** The row's verdict under the root being replayed; see the caller. */\nfilterPasses) {\n if (options.population === \"filtered\" && !filterPasses) {\n return undefined;\n }\n let value;\n try {\n value = column.accessor(record.row);\n }\n catch (cause) {\n throw callbackError(\"accessor-failed\", operation, column.id, record.rowId, cause);\n }\n let description;\n try {\n description = describeValue(value);\n }\n catch (cause) {\n throw callbackError(\"accessor-failed\", operation, column.id, record.rowId, cause);\n }\n if (description.blank && !options.includeBlanks)\n return undefined;\n return { description, value };\n}\nfunction removeValue(state, rowId) {\n const valueId = state.rowValues.get(rowId);\n if (valueId === undefined && !state.rowValues.has(rowId))\n return state;\n const previous = state.values.get(valueId);\n if (previous === undefined) {\n return { values: state.values, rowValues: state.rowValues.delete(rowId) };\n }\n const values = previous.count === 1\n ? state.values.remove(previous.id)\n : state.values.insertOrReplace(Object.freeze({ ...previous, count: previous.count - 1 }));\n return { values, rowValues: state.rowValues.delete(rowId) };\n}\nfunction insertValue(state, rowId, selected) {\n const previous = state.values.get(selected.description.id);\n const entry = Object.freeze({\n id: selected.description.id,\n value: previous?.value ?? snapshotDistinctValue(selected.value),\n count: (previous?.count ?? 0) + 1,\n blank: selected.description.blank,\n blankRank: selected.description.blankRank,\n });\n return {\n values: state.values.insertOrReplace(entry),\n rowValues: state.rowValues.set(rowId, entry.id),\n };\n}\nfunction replayRecord(state, target, rowId, column, options, operation) {\n let next;\n try {\n next = removeValue(state, rowId);\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw callbackError(\"comparator-failed\", operation, column.id, rowId, cause);\n }\n const record = target.rows.get(rowId);\n if (record === undefined)\n return next;\n // The \"filtered\" population is exactly the target root's visible\n // membership, so the root the replay already holds answers it — no stored\n // per-row verdict, and no accessor re-run for the \"all\" population.\n const selected = readValue(record, column, options, operation, options.population === \"filtered\" ? rowPassesFilter(target, rowId) : true);\n if (selected === undefined)\n return next;\n try {\n next = insertValue(next, rowId, selected);\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw callbackError(\"comparator-failed\", operation, column.id, rowId, cause);\n }\n return next;\n}\nfunction createDictionaryCandidate(input) {\n const column = input.column;\n const queryOptions = input.options;\n let retained = {\n captured: input.captured,\n iterator: input.captured.sourceOrder.entries(),\n state: {\n values: createValueTree(column, queryOptions),\n rowValues: createPersistentMap(),\n },\n deltas: [],\n };\n // Candidate methods retain only the nullable state and immutable callback\n // configuration. Clear the input container so release truly drops the\n // captured row root rather than keeping it through the parameter closure.\n input = undefined;\n let deltaIndex = 0;\n let deltaRowIndex = 0;\n let processedRows = 0;\n let released = false;\n return {\n get processedRows() {\n return processedRows;\n },\n get deltaCount() {\n return (retained?.deltas.reduce((count, delta) => count + (delta === null ? 0 : 1), 0) ?? 0);\n },\n get released() {\n return released;\n },\n append(delta) {\n retained?.deltas.push(delta);\n },\n step() {\n const state = retained;\n if (state === undefined)\n return true;\n if (state.iterator !== null) {\n const next = state.iterator.next();\n if (!next.done) {\n state.state = replayRecord(state.state, state.captured, next.value.rowId, column, queryOptions, \"distinct-values\");\n processedRows += 1;\n return false;\n }\n state.iterator = null;\n }\n if (deltaIndex < state.deltas.length) {\n const delta = state.deltas[deltaIndex];\n if (delta === null) {\n deltaIndex += 1;\n deltaRowIndex = 0;\n return false;\n }\n const rowId = delta.affectedRowIds[deltaRowIndex];\n if (rowId !== undefined) {\n state.state = replayRecord(state.state, delta.target, rowId, column, queryOptions, \"distinct-values\");\n deltaRowIndex += 1;\n processedRows += 1;\n return false;\n }\n state.deltas[deltaIndex] = null;\n deltaIndex += 1;\n deltaRowIndex = 0;\n return false;\n }\n return true;\n },\n finish() {\n if (retained === undefined)\n throw new Error(\"Released dictionary candidate.\");\n return retained.state;\n },\n release() {\n if (retained === undefined)\n return;\n retained.iterator = null;\n retained.deltas.fill(null);\n retained.deltas.length = 0;\n retained = undefined;\n released = true;\n },\n };\n}\nfunction projectIndexedResult(state, options, revision) {\n const end = Math.min(state.values.size, options.start + options.limit);\n const values = state.values.range(options.start, end).map((entry) => Object.freeze({\n value: snapshotDistinctValue(entry.value),\n count: entry.count,\n }));\n return Object.freeze({\n values: Object.freeze(values),\n totalDistinct: state.values.size,\n population: options.population,\n rowModelRevision: revision,\n });\n}\nexport function createDistinctValueManager(options) {\n const capacity = options.cacheCapacity ?? DEFAULT_CACHE_CAPACITY;\n if (!Number.isSafeInteger(capacity) || capacity <= 0) {\n throw new RangeError(\"The distinct-value cache capacity must be a positive safe integer.\");\n }\n const cache = new Map();\n let clock = 0;\n let disposed = false;\n let rowsEvaluated = 0;\n let releasedCandidateCount = 0;\n let projectionEntriesExamined = 0;\n const projectionRuntime = Object.freeze({\n ...options.runtime,\n maxUnitsPerSlice: Math.min(options.runtime.maxUnitsPerSlice, 256),\n });\n const activeProjections = new Set();\n const bestEffortCancel = (cancel) => {\n try {\n cancel?.();\n }\n catch {\n // Scheduler hooks are advisory and never own dictionary/projection state.\n }\n };\n const releaseProjection = (projection) => {\n const cancelScheduled = projection.cancelScheduled;\n projection.cancelScheduled = undefined;\n bestEffortCancel(cancelScheduled);\n projection.iterator = undefined;\n projection.tree = undefined;\n projection.values.length = 0;\n projection.waiter.cancelActive = undefined;\n activeProjections.delete(projection);\n };\n const finishProjection = (projection) => {\n const waiter = projection.waiter;\n const values = Object.freeze([...projection.values]);\n const result = Object.freeze({\n values,\n totalDistinct: projection.matchingCount,\n population: waiter.options.population,\n rowModelRevision: projection.revision,\n });\n releaseProjection(projection);\n waiter.status = \"ready\";\n waiter.resolve(result);\n };\n const failProjection = (projection, error) => {\n const waiter = projection.waiter;\n releaseProjection(projection);\n waiter.status = \"error\";\n waiter.reject(error);\n };\n const runProjectionSlice = (projection) => {\n if (disposed || !activeProjections.has(projection))\n return;\n try {\n const complete = runCooperativeTransitionSlice(projectionRuntime, () => {\n const next = projection.iterator?.next();\n if (next === undefined || next.done)\n return true;\n projectionEntriesExamined += 1;\n if (String(next.value.value)\n .toLocaleLowerCase()\n .includes(projection.search)) {\n if (projection.matchingCount >= projection.waiter.options.start &&\n projection.values.length < projection.waiter.options.limit) {\n projection.values.push(Object.freeze({\n value: snapshotDistinctValue(next.value.value),\n count: next.value.count,\n }));\n }\n projection.matchingCount += 1;\n }\n return false;\n });\n if (disposed || !activeProjections.has(projection))\n return;\n if (complete) {\n finishProjection(projection);\n return;\n }\n projection.cancelScheduled = options.runtime.scheduler.schedule(() => {\n projection.cancelScheduled = undefined;\n runProjectionSlice(projection);\n });\n }\n catch (error) {\n failProjection(projection, error);\n }\n };\n const startProjection = (state, waiter, revision) => {\n const projection = {\n tree: state.values,\n iterator: state.values.entries(),\n waiter,\n revision,\n search: waiter.options.search.toLocaleLowerCase(),\n values: [],\n matchingCount: 0,\n cancelScheduled: undefined,\n };\n const opaque = projection;\n activeProjections.add(opaque);\n waiter.cancelActive = () => releaseProjection(opaque);\n try {\n projection.cancelScheduled = options.runtime.scheduler.schedule(() => {\n projection.cancelScheduled = undefined;\n runProjectionSlice(opaque);\n });\n }\n catch (error) {\n failProjection(opaque, error);\n }\n };\n const releaseBuilding = (entry) => {\n const cancelScheduled = entry.cancelScheduled;\n entry.cancelScheduled = undefined;\n bestEffortCancel(cancelScheduled);\n if (!entry.candidate.released) {\n rowsEvaluated += entry.candidate.processedRows;\n entry.candidate.release();\n releasedCandidateCount += 1;\n }\n };\n const cancelBuilding = (entry, reason) => {\n releaseBuilding(entry);\n for (const waiter of entry.waiters) {\n waiter.cancelActive = undefined;\n waiter.status = \"cancelled\";\n waiter.reject(new PretableDistinctValueCancelledError(reason));\n }\n entry.waiters.clear();\n cache.delete(entry.key);\n };\n const evictEntry = (entry) => {\n if (entry.kind === \"building\") {\n cancelBuilding(entry, \"evicted\");\n return;\n }\n entry.state = undefined;\n cache.delete(entry.key);\n };\n const makeRoomForEntry = () => {\n while (cache.size >= capacity) {\n const oldest = [...cache.values()].sort((left, right) => left.lastUsed - right.lastUsed)[0];\n if (oldest === undefined)\n return;\n evictEntry(oldest);\n }\n };\n const evictReady = () => {\n const ready = [...cache.values()].filter((entry) => entry.kind === \"ready\" && entry.state !== undefined);\n while (ready.length > capacity) {\n ready.sort((left, right) => left.lastUsed - right.lastUsed);\n const evicted = ready.shift();\n evicted.state = undefined;\n cache.delete(evicted.key);\n }\n };\n const resolveReady = (entry) => {\n const dictionary = entry.candidate.finish();\n rowsEvaluated += entry.candidate.processedRows;\n entry.candidate.release();\n releasedCandidateCount += 1;\n const ready = {\n kind: \"ready\",\n key: entry.key,\n column: entry.column,\n options: entry.options,\n state: dictionary,\n lastUsed: ++clock,\n };\n cache.set(entry.key, ready);\n for (const waiter of entry.waiters) {\n if (waiter.status !== \"pending\")\n continue;\n try {\n const revision = options.getRoot().revision;\n if ((waiter.options.search?.length ?? 0) === 0) {\n const result = projectIndexedResult(dictionary, waiter.options, revision);\n waiter.cancelActive = undefined;\n waiter.status = \"ready\";\n waiter.resolve(result);\n }\n else {\n startProjection(dictionary, waiter, revision);\n }\n }\n catch (error) {\n waiter.cancelActive = undefined;\n waiter.status = \"error\";\n waiter.reject(error);\n }\n }\n entry.waiters.clear();\n evictReady();\n };\n const failBuilding = (entry, error) => {\n releaseBuilding(entry);\n cache.delete(entry.key);\n for (const waiter of entry.waiters) {\n waiter.cancelActive = undefined;\n waiter.status = \"error\";\n waiter.reject(error);\n }\n entry.waiters.clear();\n };\n const runBuildSlice = (entry) => {\n if (disposed || cache.get(entry.key) !== entry)\n return;\n try {\n const complete = runCooperativeTransitionSlice(options.runtime, () => entry.candidate.step());\n if (disposed || cache.get(entry.key) !== entry)\n return;\n if (complete) {\n resolveReady(entry);\n return;\n }\n entry.cancelScheduled = options.runtime.scheduler.schedule(() => {\n entry.cancelScheduled = undefined;\n runBuildSlice(entry);\n });\n }\n catch (error) {\n failBuilding(entry, error);\n }\n };\n const manager = {\n query(columnId, rawOptions) {\n const captured = captureQueryOptions(rawOptions);\n const root = options.getRoot();\n const column = columnForDerivations(options.getDerivations(), columnId);\n const key = cacheKey(root, column, captured);\n const existing = cache.get(key);\n if (existing?.kind === \"ready\" &&\n existing.state !== undefined &&\n (captured.search?.length ?? 0) === 0) {\n existing.lastUsed = ++clock;\n let status = \"ready\";\n const finished = Promise.resolve(projectIndexedResult(existing.state, captured, root.revision));\n return Object.freeze({\n get status() {\n return status;\n },\n finished,\n cancel() {\n status = \"ready\";\n },\n });\n }\n let resolve;\n let reject;\n const finished = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n void finished.catch(() => undefined);\n const waiter = {\n status: \"pending\",\n options: captured,\n resolve,\n reject,\n cancelActive: undefined,\n };\n const query = Object.freeze({\n get status() {\n return waiter.status;\n },\n finished,\n cancel() {\n if (waiter.status !== \"pending\")\n return;\n waiter.status = \"cancelled\";\n const cancelActive = waiter.cancelActive;\n waiter.cancelActive = undefined;\n cancelActive?.();\n waiter.reject(new PretableDistinctValueCancelledError(\"cancelled\"));\n },\n });\n if (existing?.kind === \"ready\" && existing.state !== undefined) {\n existing.lastUsed = ++clock;\n startProjection(existing.state, waiter, root.revision);\n return query;\n }\n let entry;\n if (existing?.kind === \"building\") {\n entry = existing;\n entry.lastUsed = ++clock;\n }\n else {\n makeRoomForEntry();\n entry = {\n kind: \"building\",\n key,\n column,\n options: captured,\n candidate: createDictionaryCandidate({\n captured: root,\n column,\n options: captured,\n }),\n waiters: new Set(),\n lastUsed: ++clock,\n cancelScheduled: undefined,\n };\n cache.set(key, entry);\n }\n entry.waiters.add(waiter);\n waiter.cancelActive = () => {\n if (entry.waiters.delete(waiter)) {\n if (entry.waiters.size === 0 && cache.get(entry.key) === entry) {\n releaseBuilding(entry);\n cache.delete(entry.key);\n }\n }\n };\n if (existing?.kind !== \"building\")\n runBuildSlice(entry);\n return query;\n },\n prepareCommit(target, affectedRowIds, operation) {\n const updates = [];\n for (const entry of cache.values()) {\n if (entry.kind !== \"ready\" || entry.state === undefined)\n continue;\n let state = entry.state;\n for (const rowId of affectedRowIds) {\n state = replayRecord(state, target, rowId, entry.column, entry.options, operation);\n }\n updates.push({\n entry: entry,\n state,\n });\n }\n return Object.freeze({ updates: Object.freeze(updates) });\n },\n publishCommit(prepared, target, affectedRowIds) {\n for (const update of prepared.updates)\n update.entry.state = update.state;\n const delta = Object.freeze({\n target,\n affectedRowIds: Object.freeze([...affectedRowIds]),\n });\n for (const entry of cache.values()) {\n if (entry.kind === \"building\")\n entry.candidate.append(delta);\n }\n },\n publishTransitionRoot(target) {\n for (const entry of [...cache.values()]) {\n const currentColumn = columnForDerivations(options.getDerivations(), entry.column.id);\n if (cacheKey(target, currentColumn, entry.options) === entry.key) {\n continue;\n }\n if (entry.kind === \"building\")\n cancelBuilding(entry, \"superseded\");\n else {\n entry.state = undefined;\n cache.delete(entry.key);\n }\n }\n },\n dispose(error) {\n if (disposed)\n return;\n disposed = true;\n for (const entry of cache.values()) {\n if (entry.kind === \"building\") {\n releaseBuilding(entry);\n for (const waiter of entry.waiters) {\n waiter.cancelActive = undefined;\n waiter.status = \"cancelled\";\n waiter.reject(error);\n }\n entry.waiters.clear();\n }\n else\n entry.state = undefined;\n }\n cache.clear();\n for (const projection of [...activeProjections]) {\n const waiter = projection.waiter;\n releaseProjection(projection);\n waiter.status = \"cancelled\";\n waiter.reject(error);\n }\n },\n attachModel(model) {\n modelManagers.set(model, {\n diagnostics: () => {\n let retainedDictionaryCount = 0;\n let buildingDictionaryCount = 0;\n let retainedRowValueCount = 0;\n let retainedDistinctValueCount = 0;\n let candidateDeltaCount = 0;\n let capturedRootCount = 0;\n for (const entry of cache.values()) {\n if (entry.kind === \"ready\" && entry.state !== undefined) {\n retainedDictionaryCount += 1;\n retainedRowValueCount += entry.state.rowValues.size;\n retainedDistinctValueCount += entry.state.values.size;\n }\n else if (entry.kind === \"building\") {\n buildingDictionaryCount += 1;\n candidateDeltaCount += entry.candidate.deltaCount;\n capturedRootCount += entry.candidate.released ? 0 : 1;\n }\n }\n return Object.freeze({\n cacheEntryCount: cache.size,\n retainedDictionaryCount,\n buildingDictionaryCount,\n retainedRowValueCount,\n retainedDistinctValueCount,\n candidateDeltaCount,\n rowsEvaluated: rowsEvaluated +\n [...cache.values()].reduce((count, entry) => count +\n (entry.kind === \"building\"\n ? entry.candidate.processedRows\n : 0), 0),\n releasedCandidateCount,\n capturedRootCount,\n activeProjectionCount: activeProjections.size,\n projectionEntriesExamined,\n projectionIteratorCount: [...activeProjections].filter((projection) => projection.iterator !== undefined).length,\n projectionScheduledCount: [...activeProjections].filter((projection) => projection.cancelScheduled !== undefined).length,\n disposed,\n });\n },\n });\n },\n };\n return manager;\n}\n","export const DEFAULT_CHANGE_JOURNAL_CAPACITY = 128;\nconst operationDiagnostics = new WeakMap();\nconst journalDiagnostics = new WeakMap();\nexport function attachChangeOperationDiagnosticsForTesting(operations, diagnostics) {\n operationDiagnostics.set(operations, Object.freeze({ ...diagnostics }));\n return operations;\n}\nexport function getChangeOperationDiagnosticsForTesting(operations) {\n const diagnostics = operationDiagnostics.get(operations);\n if (diagnostics === undefined) {\n throw new TypeError(\"Diagnostics require generated transaction operations.\");\n }\n return diagnostics;\n}\nexport function getChangeJournalDiagnosticsForTesting(journal) {\n const diagnostics = journalDiagnostics.get(journal);\n if (diagnostics === undefined) {\n throw new TypeError(\"Diagnostics require a Pretable change journal.\");\n }\n return diagnostics;\n}\nfunction previousRevisionOf(entry) {\n return entry.kind === \"changes\"\n ? entry.changeSet.previousRevision\n : entry.previousRevision;\n}\nfunction freezeRef(ref) {\n return ref.kind === \"data\"\n ? Object.freeze({ kind: \"data\", rowId: ref.rowId })\n : Object.freeze({ kind: \"group\", groupId: ref.groupId });\n}\nfunction freezeOperation(operation) {\n switch (operation.kind) {\n case \"insert\":\n return Object.freeze({\n kind: \"insert\",\n ref: freezeRef(operation.ref),\n index: operation.index,\n });\n case \"remove\":\n return Object.freeze({\n kind: \"remove\",\n ref: freezeRef(operation.ref),\n previousIndex: operation.previousIndex,\n });\n case \"move\":\n return Object.freeze({\n kind: \"move\",\n ref: freezeRef(operation.ref),\n previousIndex: operation.previousIndex,\n index: operation.index,\n });\n case \"update\":\n return Object.freeze({\n kind: \"update\",\n ref: freezeRef(operation.ref),\n index: operation.index,\n fields: Object.freeze(Array.from(operation.fields)),\n });\n }\n}\nfunction changes(fromRevision, toRevision, changeSets) {\n return Object.freeze({\n kind: \"changes\",\n fromRevision,\n toRevision,\n changes: Object.freeze(Array.from(changeSets)),\n });\n}\nfunction reset(toRevision, reason) {\n return Object.freeze({ kind: \"reset\", toRevision, reason });\n}\n/**\n * A root-independent bounded journal. Entries contain only public row refs and\n * frozen scalar metadata, so retaining or evicting them cannot retain or\n * invalidate persistent revision roots.\n */\nexport function createChangeJournal(capacity = DEFAULT_CHANGE_JOURNAL_CAPACITY) {\n if (!Number.isSafeInteger(capacity) || capacity < 0) {\n throw new RangeError(\"Change journal capacity must be a non-negative integer.\");\n }\n let entries = Object.freeze([]);\n let latestRevision = 0;\n function publishDiagnostics() {\n journalDiagnostics.set(journal, Object.freeze({\n capacity,\n entryCount: entries.length,\n latestRevision,\n }));\n }\n const assertContiguous = (previousRevision, revision) => {\n if (!Number.isSafeInteger(previousRevision) ||\n !Number.isSafeInteger(revision) ||\n previousRevision < 0 ||\n revision !== previousRevision + 1 ||\n previousRevision !== latestRevision) {\n throw new RangeError(\"Change journal entries must be safe, non-negative, and contiguous.\");\n }\n };\n const retain = (entry) => {\n if (capacity === 0) {\n entries = Object.freeze([]);\n return;\n }\n const next = [...entries, entry];\n entries = Object.freeze(next.slice(Math.max(0, next.length - capacity)));\n };\n const journal = {\n capacity,\n appendChanges(previousRevision, revision, operations) {\n assertContiguous(previousRevision, revision);\n const diagnostics = operationDiagnostics.get(operations);\n const frozenOperations = Object.freeze(Array.from(operations, (operation) => freezeOperation(operation)));\n if (diagnostics !== undefined) {\n operationDiagnostics.set(frozenOperations, diagnostics);\n }\n const changeSet = Object.freeze({\n previousRevision,\n revision,\n operations: frozenOperations,\n });\n retain(Object.freeze({ kind: \"changes\", changeSet }));\n latestRevision = revision;\n publishDiagnostics();\n },\n appendBarrier(previousRevision, revision, reason = \"bulk-replace\") {\n assertContiguous(previousRevision, revision);\n retain(Object.freeze({\n kind: \"barrier\",\n previousRevision,\n revision,\n reason,\n }));\n latestRevision = revision;\n publishDiagnostics();\n },\n clear() {\n entries = Object.freeze([]);\n publishDiagnostics();\n },\n changesSince(fromRevision, currentRevision) {\n if (currentRevision !== latestRevision) {\n throw new RangeError(\"The supplied current revision does not match the journal.\");\n }\n if (!Number.isSafeInteger(fromRevision) ||\n fromRevision < 0 ||\n fromRevision > currentRevision) {\n return reset(currentRevision, \"unknown-revision\");\n }\n if (fromRevision === currentRevision) {\n return changes(fromRevision, currentRevision, []);\n }\n const first = entries[0];\n if (first === undefined || fromRevision < previousRevisionOf(first)) {\n return reset(currentRevision, \"journal-evicted\");\n }\n const start = entries.findIndex((entry) => previousRevisionOf(entry) === fromRevision);\n if (start < 0)\n return reset(currentRevision, \"unknown-revision\");\n const retained = entries.slice(start);\n // \"reorder\" (order moved, nothing else) and \"refilter\" (membership\n // changed, surviving order and identities intact) are PROMISES, so a\n // promised reason only survives aggregation when every entry in the\n // range is a barrier with that SAME reason. Any other entry — changes,\n // a plain barrier, or the OTHER promise (order + membership both\n // changed delivers neither) — voids it and the whole range degrades\n // to a plain bulk reset.\n const firstReason = retained[0]?.kind === \"barrier\" ? retained[0].reason : undefined;\n if (firstReason === \"reorder\" || firstReason === \"refilter\") {\n let allPromised = true;\n let promisedExpected = fromRevision;\n for (const entry of retained) {\n if (entry.kind !== \"barrier\" ||\n entry.reason !== firstReason ||\n entry.previousRevision !== promisedExpected) {\n allPromised = false;\n break;\n }\n promisedExpected = entry.revision;\n }\n if (allPromised && promisedExpected === currentRevision) {\n return reset(currentRevision, firstReason);\n }\n }\n let expected = fromRevision;\n const changeSets = [];\n for (const entry of retained) {\n if (previousRevisionOf(entry) !== expected) {\n return reset(currentRevision, \"unknown-revision\");\n }\n if (entry.kind === \"barrier\") {\n return reset(currentRevision, entry.reason === \"reorder\" || entry.reason === \"refilter\"\n ? \"bulk-replace\"\n : entry.reason);\n }\n changeSets.push(entry.changeSet);\n expected = entry.changeSet.revision;\n }\n if (expected !== currentRevision) {\n return reset(currentRevision, \"journal-evicted\");\n }\n return changes(fromRevision, currentRevision, changeSets);\n },\n };\n const frozen = Object.freeze(journal);\n publishDiagnostics();\n return frozen;\n}\n","import { PretableRowModelError } from \"./errors\";\nconst DEVELOPMENT = process.env.NODE_ENV !== \"production\";\nfunction failIntegrity(operation, cause) {\n throw new PretableRowModelError(\"derivation-failed\", \"A row could not be inspected safely before publication.\", { operation, cause });\n}\nfunction fingerprint(row, earlierFailure) {\n try {\n const entries = Reflect.ownKeys(row).map((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(row, key);\n if (descriptor === undefined) {\n throw new TypeError(\"An own row key disappeared during inspection.\");\n }\n if (\"value\" in descriptor) {\n return Object.freeze({\n kind: \"data\",\n key,\n value: descriptor.value,\n enumerable: descriptor.enumerable ?? false,\n configurable: descriptor.configurable ?? false,\n writable: descriptor.writable ?? false,\n });\n }\n return Object.freeze({\n kind: \"accessor\",\n key,\n get: descriptor.get,\n set: descriptor.set,\n enumerable: descriptor.enumerable ?? false,\n configurable: descriptor.configurable ?? false,\n });\n });\n return Object.freeze({ entries: Object.freeze(entries) });\n }\n catch (fingerprintFailure) {\n return failIntegrity(\"set-rows\", earlierFailure === undefined\n ? fingerprintFailure\n : Object.freeze({ earlierFailure, fingerprintFailure }));\n }\n}\nfunction fingerprintsEqual(left, right) {\n if (left === undefined || left.entries.length !== right.entries.length)\n return false;\n return left.entries.every((entry, index) => {\n const other = right.entries[index];\n if (other === undefined ||\n entry.kind !== other.kind ||\n entry.key !== other.key ||\n entry.enumerable !== other.enumerable ||\n entry.configurable !== other.configurable) {\n return false;\n }\n if (entry.kind === \"data\" && other.kind === \"data\") {\n return (entry.writable === other.writable && Object.is(entry.value, other.value));\n }\n return (entry.kind === \"accessor\" &&\n other.kind === \"accessor\" &&\n entry.get === other.get &&\n entry.set === other.set);\n });\n}\n/**\n * Applies the development-only immutable-row guard. Production takes a\n * constant-time path with no reflection, freezing, fingerprinting, or output.\n */\nexport function inspectRowIntegrity(row, rowId, previous, sameReference) {\n if (!DEVELOPMENT) {\n return {\n integrity: { kind: \"unchecked\" },\n sameReferenceMutation: false,\n };\n }\n let extensible;\n try {\n extensible = Object.isExtensible(row);\n }\n catch (cause) {\n const current = fingerprint(row, cause);\n return fingerprintInspection(current, rowId, previous, sameReference);\n }\n if (extensible) {\n try {\n Object.freeze(row);\n if (Object.isFrozen(row)) {\n return {\n integrity: { kind: \"frozen\" },\n sameReferenceMutation: false,\n };\n }\n const current = fingerprint(row);\n return fingerprintInspection(current, rowId, previous, sameReference);\n }\n catch (cause) {\n const current = fingerprint(row, cause);\n return fingerprintInspection(current, rowId, previous, sameReference);\n }\n }\n try {\n if (Object.isFrozen(row)) {\n return {\n integrity: { kind: \"frozen\" },\n sameReferenceMutation: false,\n };\n }\n }\n catch (cause) {\n const current = fingerprint(row, cause);\n return fingerprintInspection(current, rowId, previous, sameReference);\n }\n const current = fingerprint(row);\n return fingerprintInspection(current, rowId, previous, sameReference);\n}\nfunction fingerprintInspection(current, rowId, previous, sameReference) {\n const sameReferenceMutation = sameReference &&\n previous?.kind === \"fingerprinted\" &&\n !fingerprintsEqual(previous.fingerprint, current);\n return {\n integrity: { kind: \"fingerprinted\", fingerprint: current },\n sameReferenceMutation,\n diagnostic: sameReferenceMutation\n ? Object.freeze({\n code: \"same-reference-row-mutation\",\n rowId,\n message: \"A row object changed without changing identity; it was reevaluated. Previously captured snapshots may observe that caller-owned mutation through the shared row reference.\",\n })\n : undefined,\n };\n}\n","import { PretableRowModelError } from \"./errors\";\nimport { createOrderStatisticTree, instrumentOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { createPersistentMap, instrumentPersistentMap, } from \"./persistent/persistent-map\";\nimport { inspectRowIntegrity, } from \"./row-integrity\";\nimport { slotVectorFromEntries } from \"./slot-vector\";\nexport function createSourceOrderTree(instrumentation) {\n return instrumentOrderStatisticTree(createOrderStatisticTree({\n getId: (entry) => entry.rowId,\n compare: (left, right) => left.sourceOrder - right.sourceOrder,\n measure: {\n empty: 0,\n fromEntry: () => 1,\n combine: (left, right) => left + right,\n },\n }), instrumentation);\n}\nfunction captureRows(rows) {\n try {\n return Array.from(rows);\n }\n catch (cause) {\n throw new PretableRowModelError(\"derivation-failed\", \"The rows input could not be read safely.\", { operation: \"set-rows\", cause });\n }\n}\nfunction captureRowId(row, getRowId) {\n try {\n const rowId = getRowId(row);\n if (typeof rowId !== \"string\" && typeof rowId !== \"number\") {\n throw new TypeError(\"Row IDs must be strings or numbers.\");\n }\n return rowId;\n }\n catch (cause) {\n throw new PretableRowModelError(\"derivation-failed\", \"The row ID accessor failed.\", { operation: \"set-rows\", cause });\n }\n}\n/** Builds the canonical persistent store after validating every ID first. */\nexport function buildRowStore(input) {\n const captured = captureRows(input.rows);\n const ids = [];\n const seen = new Set();\n for (const row of captured) {\n const rowId = captureRowId(row, input.getRowId);\n if (seen.has(rowId)) {\n throw new PretableRowModelError(\"duplicate-row-id\", `Duplicate row ID ${String(rowId)}.`, { operation: \"set-rows\", rowId });\n }\n seen.add(rowId);\n ids.push(rowId);\n }\n const inspections = captured.map((row, index) => {\n const rowId = ids[index];\n const previous = input.previous?.get(rowId);\n return inspectRowIntegrity(row, rowId, previous?.integrity, previous !== undefined && Object.is(previous.row, row));\n });\n const sameReferenceMutation = inspections.some((inspection) => inspection.sameReferenceMutation);\n const mapDraft = instrumentPersistentMap(createPersistentMap(), input.instrumentation).asTransient();\n const sourceDraft = createSourceOrderTree(input.instrumentation).asTransient();\n const records = [];\n for (let sourceOrder = 0; sourceOrder < captured.length; sourceOrder += 1) {\n const row = captured[sourceOrder];\n const rowId = ids[sourceOrder];\n const previous = input.previous?.get(rowId);\n if (input.instrumentation !== undefined)\n input.instrumentation.work.rowsEvaluated += 1;\n // `evaluate` needs a slot up front (it's part of `CompiledRowInput` now,\n // unread this task), but the REAL slot for a brand-new row is still\n // resolved after evaluation succeeds, exactly as before this field\n // existed: `input.slots.allocate()` is a real allocator mutation that\n // bumps the high-water mark permanently (capacity never shrinks — see\n // `slot-allocator.ts`), and drawing it before a throwing accessor runs\n // would leak capacity a release can't undo. A carried row's slot has no\n // such hazard (no allocator call), so it is used directly. `-1` is a\n // placeholder for the fresh-slot case only: harmless because nothing\n // reads `CompiledRowInput.slot` yet.\n const metadata = input.queryPlan.evaluate({\n rowId,\n row: row,\n sourceOrder,\n slot: previous !== undefined ? previous.slot : -1,\n });\n const slot = previous !== undefined ? previous.slot : input.slots.allocate();\n const publicRow = previous !== undefined &&\n Object.is(previous.row, row) &&\n previous.sourceOrder === sourceOrder &&\n !inspections[sourceOrder].sameReferenceMutation\n ? previous.publicRow\n : Object.freeze({\n kind: \"data\",\n rowId,\n row,\n sourceIndex: sourceOrder,\n depth: 0,\n });\n const record = Object.freeze({\n rowId,\n row,\n sourceOrder,\n slot,\n metadata,\n publicRow,\n integrity: inspections[sourceOrder].integrity,\n });\n mapDraft.set(rowId, record);\n sourceDraft.insertOrReplace(Object.freeze({ rowId, sourceOrder }));\n records.push(record);\n }\n if (input.previous !== undefined) {\n for (const [rowId, record] of input.previous.entries()) {\n if (!seen.has(rowId))\n input.slots.release(record.slot);\n }\n }\n return {\n rows: mapDraft.freeze(),\n sourceOrder: sourceDraft.freeze(),\n records: Object.freeze(records),\n recordsBySlot: slotVectorFromEntries(records.map((record) => [record.slot, record]), input.slots.capacity),\n sameReferenceMutation,\n sameReferenceMutationCount: inspections.filter((inspection) => inspection.sameReferenceMutation).length,\n diagnostics: Object.freeze(inspections.flatMap((inspection) => inspection.diagnostic === undefined ? [] : [inspection.diagnostic])),\n };\n}\n","/**\n * Per-MODEL slot allocator: every row gets a small dense integer for its\n * lifetime, assigned at ingest and released only on permanent removal.\n * Mutable by design — this is instance state, not revision state; the\n * revision-scoped structures (`slot-vector`, `membership-bitset`) are what\n * keep old snapshots valid when a released slot is reused.\n *\n * Capacity is the high-water mark and never shrinks, so slot-indexed\n * structures never renumber. Release is fail-loud (double release would hand\n * one slot to two live rows, which corrupts every slot-indexed structure\n * from that commit on).\n */\nexport function createSlotAllocator() {\n const free = [];\n let next = 0;\n let live = new Uint8Array(1024);\n const ensure = (slot) => {\n if (slot < live.length)\n return;\n const grown = new Uint8Array(Math.max(live.length * 2, slot + 1));\n grown.set(live);\n live = grown;\n };\n return {\n get capacity() {\n return next;\n },\n allocate() {\n const slot = free.length > 0 ? free.pop() : next++;\n ensure(slot);\n live[slot] = 1;\n return slot;\n },\n release(slot) {\n if (!Number.isInteger(slot) || slot < 0 || slot >= next) {\n throw new RangeError(`Slot ${slot} was never allocated.`);\n }\n if (live[slot] !== 1) {\n throw new RangeError(`Slot ${slot} is not live (double release).`);\n }\n live[slot] = 0;\n free.push(slot);\n },\n };\n}\n","import { filterVerdict, sortKeysOf, } from \"./compiled-query\";\nimport { isCalendarDateAggregate } from \"./calendar-date-aggregates\";\nimport { attachChangeOperationDiagnosticsForTesting, getChangeOperationDiagnosticsForTesting, } from \"./change-journal\";\nimport { rowPassesFilter } from \"./filter-membership\";\nimport { PretableRowIdentityChangeError, PretableRowModelError, PretableUnsupportedRowUpdateError, } from \"./errors\";\nimport { instrumentOrderStatisticTree } from \"./persistent/order-statistic-tree\";\nimport { instrumentPersistentMap } from \"./persistent/persistent-map\";\nimport { attachGroupIndex, getGroupIndex, makeGroupId, updateGroupIndex, visibleIndexOf, visibleRange, } from \"./group-index\";\nimport { inspectRowIntegrity, } from \"./row-integrity\";\nimport { orderedRowEntry } from \"./ordered-row-entry\";\nimport { clearMembershipBit, cloneMembership, setMembershipBit, EMPTY_MEMBERSHIP, } from \"./membership-bitset\";\nimport { slotVectorWithAll } from \"./slot-vector\";\nimport { createFlatVisibleTree, membershipFromFlatTree } from \"./visible-index\";\nexport const getTransactionChangeDiagnosticsForTesting = getChangeOperationDiagnosticsForTesting;\nclass TransactionExecutionError extends PretableRowModelError {\n rowIds;\n groupValues;\n groupId;\n constructor(error) {\n super(error.code, error.message, {\n operation: \"apply-transaction\",\n rowId: error.rowId,\n columnId: error.columnId,\n cause: error.cause,\n });\n const detailed = error;\n this.rowIds = detailed.rowIds;\n this.groupValues = detailed.groupValues;\n this.groupId = detailed.groupId;\n }\n}\nclass TransactionValidationError extends PretableRowModelError {\n path;\n name = \"TransactionValidationError\";\n constructor(path, message, cause) {\n super(\"derivation-failed\", message, {\n operation: \"apply-transaction\",\n cause,\n });\n this.path = path;\n }\n}\nfunction remap(error) {\n if (error instanceof PretableRowModelError &&\n error.code !== \"reentrant-mutation\" &&\n error.operation !== \"apply-transaction\") {\n throw new TransactionExecutionError(error);\n }\n throw error;\n}\nfunction fail(code, message, rowId, cause) {\n throw new PretableRowModelError(code, message, {\n operation: \"apply-transaction\",\n rowId,\n cause,\n });\n}\nfunction invalid(path, message, cause) {\n throw new TransactionValidationError(path, message, cause);\n}\nfunction readProperty(source, key, path) {\n try {\n return Reflect.get(source, key);\n }\n catch (cause) {\n return invalid(path, `The value at ${path} could not be read safely.`, cause);\n }\n}\nfunction captureDenseList(value, path) {\n if (value === undefined)\n return Object.freeze([]);\n try {\n if (!Array.isArray(value))\n return invalid(path, `${path} must be an array.`);\n const length = value.length;\n const captured = [];\n for (let index = 0; index < length; index += 1) {\n const entryPath = `${path}[${index}]`;\n if (!Object.hasOwn(value, index)) {\n return invalid(entryPath, `${path} must be a dense array.`);\n }\n captured.push(readProperty(value, index, entryPath));\n }\n return Object.freeze(captured);\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n return invalid(path, `${path} could not be captured safely.`, cause);\n }\n}\nfunction validRowId(value) {\n return typeof value === \"string\" || typeof value === \"number\";\n}\n/** Patches use enumerable own data properties, including symbol keys. */\nfunction capturePatch(value, path) {\n if (value === null || typeof value !== \"object\") {\n return invalid(path, `${path} must be an object.`);\n }\n try {\n const captured = [];\n for (const key of Reflect.ownKeys(value)) {\n const keyPath = typeof key === \"symbol\" ? `${path}[${String(key)}]` : `${path}.${key}`;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined)\n return invalid(keyPath, `The property at ${keyPath} disappeared.`);\n if (!descriptor.enumerable)\n continue;\n if (!(\"value\" in descriptor)) {\n return invalid(keyPath, `The patch property at ${keyPath} must be a data property.`);\n }\n captured.push(Object.freeze({ key, value: descriptor.value }));\n }\n return Object.freeze(captured);\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n return invalid(path, `${path} could not be captured safely.`, cause);\n }\n}\nfunction mergeChanges(previous, patches, rowId) {\n try {\n const prototype = Object.getPrototypeOf(previous);\n if (Array.isArray(previous) ||\n (prototype !== Object.prototype && prototype !== null)) {\n throw new PretableUnsupportedRowUpdateError(rowId);\n }\n const row = Object.create(prototype);\n for (const key of Reflect.ownKeys(previous)) {\n const descriptor = Object.getOwnPropertyDescriptor(previous, key);\n if (descriptor === undefined)\n throw new TypeError(\"A row property disappeared.\");\n Object.defineProperty(row, key, {\n ...descriptor,\n configurable: true,\n ...(\"value\" in descriptor ? { writable: true } : {}),\n });\n }\n const originals = new Map();\n for (const patch of patches) {\n for (const property of patch) {\n if (!originals.has(property.key)) {\n originals.set(property.key, Object.getOwnPropertyDescriptor(previous, property.key));\n }\n Object.defineProperty(row, property.key, {\n value: property.value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n }\n const changed = Array.from(originals, ([key, descriptor]) => {\n const final = Object.getOwnPropertyDescriptor(row, key);\n return (descriptor === undefined ||\n !(\"value\" in descriptor) ||\n descriptor.enumerable !== true ||\n !Object.is(descriptor.value, final.value));\n }).some(Boolean);\n return { row: changed ? Object.freeze(row) : previous, changed };\n }\n catch (cause) {\n if (cause instanceof PretableUnsupportedRowUpdateError)\n throw cause;\n throw new PretableUnsupportedRowUpdateError(rowId, cause);\n }\n}\nfunction createRecord(row, rowId, sourceOrder, slot, queryPlan, instrumentation) {\n if (instrumentation !== undefined)\n instrumentation.work.rowsEvaluated += 1;\n const metadata = queryPlan.evaluate({\n rowId,\n row: row,\n sourceOrder,\n slot,\n });\n const inspection = inspectRowIntegrity(row, rowId, undefined, false);\n return {\n record: Object.freeze({\n rowId,\n row,\n sourceOrder,\n slot,\n metadata,\n publicRow: Object.freeze({\n kind: \"data\",\n rowId,\n row,\n sourceIndex: sourceOrder,\n depth: 0,\n }),\n integrity: inspection.integrity,\n }),\n diagnostic: inspection.diagnostic,\n };\n}\nfunction sameKeyValues(left, right) {\n return (left.length === right.length &&\n left.every((entry, index) => entry.columnId === right[index]?.columnId &&\n Object.is(entry.value, right[index]?.value)));\n}\nfunction sameFlatOrder(previousPlan, nextPlan, previous, next, \n/** The committed root's membership verdict for this row (the OLD one). */\npreviousPasses, \n/** The drafting plan's verdict for `next`, computed by the caller. */\nnextPasses) {\n // Each record's keys resolve from the plan that evaluated it: `previous`\n // from the committed root's plan, `next` from the drafting plan. Outside\n // the same-reference-mutation recompile these are one and the same object.\n // The two VERDICTS likewise come from two different places, and must: the\n // old one is structural (root membership), the new one is computed. A\n // row-keyed verdict store could not tell them apart when the plan object is\n // shared, which is exactly the same-reference-mutation case.\n return (previous.sourceOrder === next.sourceOrder &&\n previousPasses === nextPasses &&\n sameKeyValues(sortKeysOf(previousPlan, previous), sortKeysOf(nextPlan, next)));\n}\nfunction sameGroupIndexContribution(previousPlan, nextPlan, previous, next, previousPasses, nextPasses) {\n if (!sameFlatOrder(previousPlan, nextPlan, previous, next, previousPasses, nextPasses) ||\n !sameKeyValues(previous.metadata.groupPath, next.metadata.groupPath)) {\n return false;\n }\n const previousLeaves = previous.metadata.aggregateLeaves;\n const nextLeaves = next.metadata.aggregateLeaves;\n return (previousLeaves.length === nextLeaves.length &&\n previousLeaves.every((previousLeaf, index) => {\n const nextLeaf = nextLeaves[index];\n if (nextLeaf === undefined ||\n previousLeaf.columnId !== nextLeaf.columnId ||\n previousLeaf.aggregate !== nextLeaf.aggregate\n // A per-leaf filtered flag is deliberately NOT compared: whether a\n // leaf belongs to the filtered aggregate tree is the row's filter\n // verdict, and `sameFlatOrder` above already compared the old verdict\n // against the new one for this very row. Comparing it again here only\n // restated that check.\n ) {\n return false;\n }\n if (typeof previousLeaf.aggregate !== \"string\" &&\n !isCalendarDateAggregate(previousLeaf.aggregate)) {\n return (Object.is(previousLeaf.allLeaf.row, nextLeaf.allLeaf.row) &&\n Object.is(previousLeaf.allLeaf.value, nextLeaf.allLeaf.value) &&\n Object.is(previousLeaf.allLeaf.dependency, nextLeaf.allLeaf.dependency));\n }\n // The dependency's sortKeys are deliberately NOT compared here:\n // sort-key changes no longer dirty aggregate leaves BY DESIGN\n // (aggregation is order-independent; `sameFlatOrder` above already\n // compared keys through the store).\n return ((previousLeaf.aggregate === \"count\" ||\n Object.is(previousLeaf.allLeaf.value, nextLeaf.allLeaf.value)) &&\n previousLeaf.allLeaf.dependency.sourceOrder ===\n nextLeaf.allLeaf.dependency.sourceOrder);\n }));\n}\nfunction dataRef(rowId) {\n return Object.freeze({ kind: \"data\", rowId });\n}\nfunction groupPathIds(metadata) {\n return Object.freeze(metadata.groupPath.map((_, index) => makeGroupId(metadata.groupPath.slice(0, index + 1))));\n}\nfunction sameVisibleRef(left, right) {\n if (left.kind !== right.kind)\n return false;\n if (left.kind === \"group\") {\n return right.kind === \"group\" && left.groupId === right.groupId;\n }\n return (right.kind === \"data\" &&\n (left.rowId === right.rowId ||\n (left.rowId !== left.rowId && right.rowId !== right.rowId)));\n}\nfunction rankAfterStructuralOperations(ref, previousIndex, operations) {\n let current = previousIndex;\n let present = previousIndex >= 0;\n for (const operation of operations) {\n if (operation.kind === \"remove\") {\n if (sameVisibleRef(ref, operation.ref)) {\n present = false;\n current = -1;\n }\n else if (present && operation.previousIndex < current)\n current -= 1;\n continue;\n }\n if (operation.kind === \"insert\") {\n if (sameVisibleRef(ref, operation.ref)) {\n present = true;\n current = operation.index;\n }\n else if (present && operation.index <= current)\n current += 1;\n continue;\n }\n if (sameVisibleRef(ref, operation.ref)) {\n present = true;\n current = operation.index;\n continue;\n }\n if (present) {\n if (operation.previousIndex < current)\n current -= 1;\n if (operation.index <= current)\n current += 1;\n }\n }\n return present ? current : -1;\n}\nfunction groupedTransactionOperations(input) {\n const oldGroups = getGroupIndex(input.previous.visible);\n const nextGroups = getGroupIndex(input.nextVisible);\n if (oldGroups === undefined || nextGroups === undefined)\n return Object.freeze([]);\n const policy = input.previous.expansion.default;\n const affectedGroupIds = new Set();\n for (const record of [...input.removals, ...input.insertions]) {\n for (const groupId of groupPathIds(record.metadata)) {\n affectedGroupIds.add(groupId);\n }\n }\n const candidates = [];\n const rowCandidates = [];\n const updates = [];\n let visibleRowReads = 0;\n for (const groupId of affectedGroupIds) {\n const ref = Object.freeze({ kind: \"group\", groupId });\n const previousIndex = visibleIndexOf(oldGroups, policy, ref);\n const index = visibleIndexOf(nextGroups, policy, ref);\n const candidate = { ref, previousIndex, index };\n candidates.push(candidate);\n if (previousIndex >= 0 && index >= 0) {\n const previousRow = visibleRange(oldGroups, policy, previousIndex, previousIndex + 1)[0];\n const nextRow = visibleRange(nextGroups, policy, index, index + 1)[0];\n visibleRowReads += 2;\n if (previousRow?.kind === \"group\" && nextRow?.kind === \"group\") {\n const fields = [\n !Object.is(previousRow.aggregates, nextRow.aggregates)\n ? \"aggregates\"\n : undefined,\n previousRow.childCount !== nextRow.childCount\n ? \"childCount\"\n : undefined,\n previousRow.expanded !== nextRow.expanded\n ? \"expanded\"\n : undefined,\n previousRow.depth !== nextRow.depth ? \"depth\" : undefined,\n ].filter((field) => field !== undefined);\n if (fields.length > 0) {\n updates.push(Object.freeze({\n kind: \"update\",\n ref,\n index,\n fields: Object.freeze(fields),\n }));\n }\n }\n }\n }\n const insertedById = new Map(input.insertions.map((record) => [record.rowId, record]));\n const removedById = new Map(input.removals.map((record) => [record.rowId, record]));\n for (const rowId of new Set([\n ...removedById.keys(),\n ...insertedById.keys(),\n ])) {\n const previousRecord = removedById.get(rowId);\n const nextRecord = insertedById.get(rowId);\n const ref = dataRef(rowId);\n const previousIndex = visibleIndexOf(oldGroups, policy, ref);\n const index = visibleIndexOf(nextGroups, policy, ref);\n const candidate = { ref, previousIndex, index };\n candidates.push(candidate);\n rowCandidates.push(candidate);\n if (previousIndex >= 0 &&\n index >= 0 &&\n previousRecord !== undefined &&\n nextRecord !== undefined &&\n !Object.is(previousRecord.row, nextRecord.row)) {\n updates.push(Object.freeze({\n kind: \"update\",\n ref,\n index,\n fields: Object.freeze([\"row\"]),\n }));\n }\n }\n const structural = [];\n const absent = candidates\n .filter(({ previousIndex, index }) => previousIndex >= 0 && index < 0)\n .sort((left, right) => right.previousIndex - left.previousIndex);\n for (const { ref, previousIndex } of absent) {\n structural.push(Object.freeze({ kind: \"remove\", ref, previousIndex }));\n }\n const inserted = candidates\n .filter(({ previousIndex, index }) => previousIndex < 0 && index >= 0)\n .sort((left, right) => left.index - right.index);\n const targets = rowCandidates\n .filter(({ previousIndex, index }) => previousIndex >= 0 && index >= 0)\n .map((candidate) => ({\n ...candidate,\n workingIndex: candidate.index -\n inserted.filter(({ index }) => index <= candidate.index).length,\n }))\n .sort((left, right) => left.workingIndex - right.workingIndex);\n const moveToIndex = ({ ref, previousIndex }, index) => {\n const currentIndex = rankAfterStructuralOperations(ref, previousIndex, structural);\n if (currentIndex !== index) {\n structural.push(Object.freeze({\n kind: \"move\",\n ref,\n previousIndex: currentIndex,\n index,\n }));\n }\n return currentIndex;\n };\n // First place surviving changed rows in the view with future insertions\n // removed from its coordinate space. This preserves untouched rows and\n // groups without enumerating them.\n for (const { ref, previousIndex, workingIndex } of targets) {\n const currentIndex = rankAfterStructuralOperations(ref, previousIndex, structural);\n if (currentIndex > workingIndex) {\n moveToIndex({ ref, previousIndex, index: workingIndex }, workingIndex);\n }\n }\n for (const target of [...targets].reverse()) {\n const currentIndex = rankAfterStructuralOperations(target.ref, target.previousIndex, structural);\n if (currentIndex < target.workingIndex) {\n moveToIndex(target, target.workingIndex);\n }\n }\n for (const target of [...targets].reverse()) {\n moveToIndex(target, target.workingIndex);\n }\n for (const { ref, index } of inserted) {\n structural.push(Object.freeze({ kind: \"insert\", ref, index }));\n }\n const finalRowTargets = rowCandidates\n .filter(({ index }) => index >= 0)\n .sort((left, right) => right.index - left.index);\n for (const target of finalRowTargets) {\n moveToIndex(target, target.index);\n }\n return attachChangeOperationDiagnosticsForTesting(Object.freeze([\n ...structural,\n ...updates.sort((left, right) => {\n const leftIndex = left.kind === \"update\" ? left.index : 0;\n const rightIndex = right.kind === \"update\" ? right.index : 0;\n return leftIndex - rightIndex;\n }),\n ]), {\n touchedRefs: candidates.length,\n visibleRowReads,\n });\n}\nfunction rebaseSourceOrder(metadata, sourceOrder) {\n const aggregateLeaves = metadata.aggregateLeaves.map((leaf) => {\n // A rebase changes only the source order; the entry-carried sort keys\n // ride along unchanged.\n const dependency = Object.freeze({\n ...leaf.allLeaf.dependency,\n sourceOrder,\n });\n return Object.freeze({\n ...leaf,\n allLeaf: Object.freeze({ ...leaf.allLeaf, dependency }),\n });\n });\n return Object.freeze({\n ...metadata,\n sourceOrder,\n aggregateLeaves: Object.freeze(aggregateLeaves),\n });\n}\n/** Validates and prepares a complete transaction before acquiring transient roots. */\nexport function applyFlatTransactionDraft(input) {\n /*\n * Abandon rule: the draft allocates slots while preparing records, but this\n * function can still throw after that (metadata evaluation runs user code);\n * leaked allocations would pin free-list slots forever. Every allocation is\n * recorded here; the tail `catch` releases them on that live invariant. The\n * `effective: false` release just above it is defensive — every prepared\n * candidate implies `effective`, so that branch cannot currently be taken\n * with a non-empty `allocatedSlots`, but a future change to this function's\n * effectiveness check must not silently reopen the leak. The success path\n * releases the REMOVED rows' slots instead — a removed slot must never be\n * released on a failure path, because the committed root still owns it.\n */\n const allocatedSlots = [];\n try {\n const transaction = input.transaction;\n if (transaction === null || typeof transaction !== \"object\") {\n return invalid(\"transaction\", \"The transaction must be an object.\");\n }\n const rawAdds = readProperty(transaction, \"add\", \"transaction.add\");\n const rawUpdates = readProperty(transaction, \"update\", \"transaction.update\");\n const rawRemoves = readProperty(transaction, \"remove\", \"transaction.remove\");\n const adds = captureDenseList(rawAdds, \"transaction.add\");\n const updateEntries = captureDenseList(rawUpdates, \"transaction.update\");\n const removes = captureDenseList(rawRemoves, \"transaction.remove\");\n const capturedUpdates = [];\n for (let index = 0; index < updateEntries.length; index += 1) {\n const entry = updateEntries[index];\n const path = `transaction.update[${index}]`;\n if (entry === null || typeof entry !== \"object\") {\n return invalid(path, `${path} must be an object.`);\n }\n const rawId = readProperty(entry, \"id\", `${path}.id`);\n if (!validRowId(rawId)) {\n return invalid(`${path}.id`, `${path}.id must be a string or number.`);\n }\n const changes = readProperty(entry, \"changes\", `${path}.changes`);\n capturedUpdates.push({\n rowId: rawId,\n patch: capturePatch(changes, `${path}.changes`),\n });\n }\n const capturedRemoves = [];\n for (let index = 0; index < removes.length; index += 1) {\n const rowId = removes[index];\n const path = `transaction.remove[${index}]`;\n if (!validRowId(rowId)) {\n return invalid(path, `${path} must be a string or number.`);\n }\n capturedRemoves.push(rowId);\n }\n const addById = new Map();\n for (let index = 0; index < adds.length; index += 1) {\n const row = adds[index];\n let rowId;\n try {\n rowId = input.getRowId(row);\n }\n catch (cause) {\n return invalid(`transaction.add[${index}]`, \"The row ID accessor failed.\", cause);\n }\n if (!validRowId(rowId)) {\n return invalid(`transaction.add[${index}]`, \"The row ID accessor must return a string or number.\");\n }\n if (addById.has(rowId))\n fail(\"duplicate-row-id\", `Duplicate added row ID ${String(rowId)}.`, rowId);\n addById.set(rowId, row);\n }\n const updateById = new Map();\n for (const update of capturedUpdates) {\n const list = updateById.get(update.rowId);\n if (list === undefined)\n updateById.set(update.rowId, [update.patch]);\n else\n list.push(update.patch);\n }\n const removeIds = new Set();\n for (const rowId of capturedRemoves)\n removeIds.add(rowId);\n for (const rowId of addById.keys()) {\n if (updateById.has(rowId) || removeIds.has(rowId))\n fail(\"transaction-conflict\", `Row ID ${String(rowId)} appears in multiple transaction categories.`, rowId);\n }\n for (const rowId of updateById.keys()) {\n if (removeIds.has(rowId))\n fail(\"transaction-conflict\", `Row ID ${String(rowId)} appears in multiple transaction categories.`, rowId);\n }\n for (const rowId of addById.keys()) {\n if (input.root.rows.has(rowId))\n fail(\"existing-row-id\", `Row ID ${String(rowId)} already exists.`, rowId);\n }\n const issues = [];\n const pending = [];\n const prepared = [];\n const diagnostics = [];\n let unchanged = 0;\n let ignored = 0;\n let nextSourceOrder = input.nextSourceOrder;\n for (const [rowId, changes] of updateById) {\n const previous = input.root.rows.get(rowId);\n if (previous === undefined) {\n issues.push(Object.freeze({ code: \"unknown-update-id\", rowId }));\n ignored += 1;\n continue;\n }\n if (previous.integrity.kind === \"fingerprinted\") {\n throw new PretableUnsupportedRowUpdateError(rowId);\n }\n const merged = mergeChanges(previous.row, changes, rowId);\n if (!merged.changed) {\n unchanged += 1;\n continue;\n }\n pending.push({\n rowId,\n row: merged.row,\n sourceOrder: previous.sourceOrder,\n kind: \"update\",\n previousSlot: previous.slot,\n });\n }\n for (const [rowId, row] of addById) {\n pending.push({\n rowId,\n row,\n sourceOrder: nextSourceOrder,\n kind: \"add\",\n });\n nextSourceOrder += 1;\n }\n const effectiveRemoves = [];\n for (const rowId of removeIds) {\n if (!input.root.rows.has(rowId)) {\n issues.push(Object.freeze({ code: \"unknown-remove-id\", rowId }));\n ignored += 1;\n }\n else\n effectiveRemoves.push(rowId);\n }\n for (const candidate of pending) {\n if (candidate.kind !== \"update\")\n continue;\n let nextRowId;\n try {\n nextRowId = input.getRowId(candidate.row);\n }\n catch (cause) {\n throw new PretableRowIdentityChangeError(candidate.rowId, undefined, cause);\n }\n if (!validRowId(nextRowId) ||\n !(nextRowId === candidate.rowId ||\n (nextRowId !== nextRowId && candidate.rowId !== candidate.rowId))) {\n throw new PretableRowIdentityChangeError(candidate.rowId, nextRowId);\n }\n }\n // All lists, IDs, partial values, and resulting identities are validated\n // before active derivation callbacks are allowed to run.\n // Each prepared record's NEW verdict is computed once, here, and keyed by\n // the record OBJECT (the same row id can appear twice in one transaction,\n // and each occurrence carries its own record). It is never stored on the\n // record: the structures this draft builds are where it lands.\n const nextVerdicts = new Map();\n const passesNext = (record) => nextVerdicts.get(record);\n /** The committed root's membership — the OLD verdict for one row. */\n const passedPreviously = (rowId) => rowPassesFilter(input.root, rowId);\n for (const candidate of pending) {\n let slot;\n if (candidate.previousSlot !== undefined) {\n slot = candidate.previousSlot;\n }\n else {\n slot = input.slots.allocate();\n allocatedSlots.push(slot);\n }\n const made = createRecord(candidate.row, candidate.rowId, candidate.sourceOrder, slot, input.queryPlan, input.instrumentation);\n prepared.push(made.record);\n nextVerdicts.set(made.record, filterVerdict(input.queryPlan, made.record));\n if (made.diagnostic)\n diagnostics.push(made.diagnostic);\n }\n const effective = prepared.length > 0 || effectiveRemoves.length > 0;\n if (!effective) {\n for (const slot of allocatedSlots)\n input.slots.release(slot);\n return {\n rows: input.root.rows,\n sourceOrder: input.root.sourceOrder,\n visible: input.root.visible,\n recordsBySlot: input.root.recordsBySlot,\n visibleSlots: input.root.visibleSlots,\n nextSourceOrder: input.nextSourceOrder,\n added: 0,\n updated: 0,\n removed: 0,\n unchanged,\n ignored,\n issues: Object.freeze(issues),\n diagnostics: Object.freeze([]),\n operations: Object.freeze([]),\n affectedRowIds: Object.freeze([]),\n effective: false,\n };\n }\n const rowDraft = instrumentPersistentMap(input.root.rows, input.instrumentation).asTransient();\n const sourceDraft = instrumentOrderStatisticTree(input.root.sourceOrder, input.instrumentation).asTransient();\n const previousGroups = getGroupIndex(input.root.visible);\n const visibleNeedsChange = previousGroups === undefined &&\n (effectiveRemoves.some((rowId) => passedPreviously(rowId)) ||\n prepared.some((record) => {\n const previous = input.root.rows.get(record.rowId);\n return ((passedPreviously(record.rowId) || passesNext(record)) &&\n (previous === undefined ||\n !sameFlatOrder(input.root.queryPlan, input.queryPlan, previous, record, passedPreviously(record.rowId), passesNext(record))));\n }));\n const visibleDraft = visibleNeedsChange\n ? instrumentOrderStatisticTree(input.root.visible.rows, input.instrumentation).asTransient()\n : undefined;\n const operations = [];\n const ref = (rowId) => Object.freeze({ kind: \"data\", rowId });\n for (const rowId of effectiveRemoves) {\n if (previousGroups === undefined) {\n const previousIndex = visibleDraft?.rankOf(rowId);\n if (previousIndex !== undefined) {\n operations.push(Object.freeze({\n kind: \"remove\",\n ref: ref(rowId),\n previousIndex,\n }));\n }\n }\n rowDraft.delete(rowId);\n sourceDraft.remove(rowId);\n visibleDraft?.remove(rowId);\n }\n for (const record of prepared) {\n const previous = input.root.rows.get(record.rowId);\n // Both verdicts, resolved from their own authorities: the old one from\n // the committed root's membership (immutable while this loop mutates\n // the drafts), the new one computed when the record was prepared.\n const previouslyPassed = passedPreviously(record.rowId);\n const passes = passesNext(record);\n rowDraft.set(record.rowId, record);\n if (previous === undefined)\n sourceDraft.insertOrReplace(Object.freeze({\n rowId: record.rowId,\n sourceOrder: record.sourceOrder,\n }));\n if (previousGroups === undefined) {\n if (previous !== undefined &&\n sameFlatOrder(input.root.queryPlan, input.queryPlan, previous, record, previouslyPassed, passes)) {\n if (passes) {\n const index = visibleDraft?.rankOf(record.rowId) ??\n input.root.visible.rows.rankOf(record.rowId);\n if (index !== undefined) {\n operations.push(Object.freeze({\n kind: \"update\",\n ref: ref(record.rowId),\n index,\n fields: Object.freeze([\"row\"]),\n }));\n }\n }\n continue;\n }\n const previousIndex = previouslyPassed\n ? visibleDraft?.rankOf(record.rowId)\n : undefined;\n if (previouslyPassed)\n visibleDraft?.remove(record.rowId);\n if (passes) {\n visibleDraft?.insertOrReplace(orderedRowEntry(input.queryPlan, record));\n }\n const index = passes ? visibleDraft?.rankOf(record.rowId) : undefined;\n if (previousIndex !== undefined && index !== undefined) {\n operations.push(Object.freeze({\n kind: \"move\",\n ref: ref(record.rowId),\n previousIndex,\n index,\n }), Object.freeze({\n kind: \"update\",\n ref: ref(record.rowId),\n index,\n fields: Object.freeze([\"row\"]),\n }));\n }\n else if (previousIndex !== undefined) {\n operations.push(Object.freeze({\n kind: \"remove\",\n ref: ref(record.rowId),\n previousIndex,\n }));\n }\n else if (index !== undefined) {\n operations.push(Object.freeze({\n kind: \"insert\",\n ref: ref(record.rowId),\n index,\n }));\n }\n continue;\n }\n if (previous !== undefined &&\n sameFlatOrder(input.root.queryPlan, input.queryPlan, previous, record, previouslyPassed, passes))\n continue;\n }\n const frozenRows = rowDraft.freeze();\n const frozenFlatRows = visibleDraft?.freeze();\n const removedRecords = effectiveRemoves.map((rowId) => input.root.rows.get(rowId));\n const groupedRemovals = [\n ...removedRecords,\n ...prepared.flatMap((record) => {\n const previous = input.root.rows.get(record.rowId);\n return previous === undefined ||\n sameGroupIndexContribution(input.root.queryPlan, input.queryPlan, previous, record, passedPreviously(record.rowId), passesNext(record))\n ? []\n : [previous];\n }),\n ];\n const groupedInsertions = prepared.filter((record) => {\n const previous = input.root.rows.get(record.rowId);\n return (previous === undefined ||\n !sameGroupIndexContribution(input.root.queryPlan, input.queryPlan, previous, record, passedPreviously(record.rowId), passesNext(record)));\n });\n const grouped = previousGroups === undefined\n ? undefined\n : groupedRemovals.length === 0 && groupedInsertions.length === 0\n ? previousGroups\n : updateGroupIndex(previousGroups, groupedRemovals, groupedInsertions, input.root.expansion.overrides, \"apply-transaction\", input.instrumentation);\n const visible = grouped !== undefined\n ? attachGroupIndex(frozenFlatRows ?? input.root.visible.rows, grouped)\n : visibleDraft === undefined\n ? input.root.visible\n : Object.freeze({ rows: frozenFlatRows });\n const groupedOperations = grouped === undefined\n ? undefined\n : groupedTransactionOperations({\n previous: input.root,\n nextVisible: visible,\n removals: [\n ...removedRecords,\n ...prepared.flatMap((record) => {\n const old = input.root.rows.get(record.rowId);\n return old === undefined ? [] : [old];\n }),\n ],\n insertions: prepared,\n });\n // Flat roots maintain the membership bitset incrementally: clone the\n // committed root's set, clear every removal, then set/clear each prepared\n // record by its NEW verdict — the clone-and-flip the visible tree just\n // underwent, in bit form. When the flat visible tree was carried\n // unchanged, the member SET is provably unchanged too (no removal passed\n // previously, and every prepared record either failed the verdict on\n // both sides or `sameFlatOrder` held — verdict equality included), so\n // the bitset carries by identity. Grouped\n // roots keep the sentinel: their membership lives in the group index.\n let visibleSlots;\n if (previousGroups !== undefined) {\n visibleSlots = EMPTY_MEMBERSHIP;\n }\n else if (visibleDraft === undefined) {\n visibleSlots = input.root.visibleSlots;\n }\n else {\n const nextVisibleSlots = cloneMembership(input.root.visibleSlots, input.slots.capacity);\n for (const record of removedRecords)\n clearMembershipBit(nextVisibleSlots, record.slot);\n for (const record of prepared) {\n if (passesNext(record))\n setMembershipBit(nextVisibleSlots, record.slot);\n else\n clearMembershipBit(nextVisibleSlots, record.slot);\n }\n visibleSlots = nextVisibleSlots;\n }\n // Success path only (a throwing accessor never reaches here): removals\n // clear their slots, prepared records write theirs. No prepared record\n // can share a slot with a removal in one transaction — adds allocate\n // before the removals release below — so the order is free, but clears\n // are listed first anyway to match `replaceFlatRowsDraft`, where a later\n // write to the same slot must win.\n const slotWrites = [\n ...removedRecords.map((record) => [record.slot, undefined]),\n ...prepared.map((record) => [record.slot, record]),\n ];\n const { next: recordsBySlot, chunksTouched } = slotVectorWithAll(input.root.recordsBySlot, slotWrites, input.slots.capacity);\n if (input.instrumentation !== undefined)\n input.instrumentation.work.slotChunksTouched += chunksTouched;\n // The draft is committed as effective: removed rows are permanently gone,\n // so their slots go back to the free list (see the abandon-rule comment\n // above for why this must not happen any earlier).\n for (const record of removedRecords)\n input.slots.release(record.slot);\n return {\n rows: frozenRows,\n sourceOrder: sourceDraft.freeze(),\n visible,\n recordsBySlot,\n visibleSlots,\n nextSourceOrder,\n added: addById.size,\n updated: prepared.length - addById.size,\n removed: effectiveRemoves.length,\n unchanged,\n ignored,\n issues: Object.freeze(issues),\n diagnostics: Object.freeze(diagnostics),\n operations: groupedOperations ?? Object.freeze(operations),\n affectedRowIds: Object.freeze([\n ...effectiveRemoves,\n ...prepared.map((record) => record.rowId),\n ]),\n effective: true,\n };\n }\n catch (error) {\n // Abandoned draft: give back what it allocated, keep every removed slot.\n for (const slot of allocatedSlots)\n input.slots.release(slot);\n return remap(error);\n }\n}\n/** Applies an authoritative rows-array replacement through one set of drafts. */\nexport function replaceFlatRowsDraft(input) {\n let captured;\n try {\n captured = Array.from(input.rows);\n }\n catch (cause) {\n throw new PretableRowModelError(\"derivation-failed\", \"The rows input could not be read safely.\", { operation: \"set-rows\", cause });\n }\n const ids = [];\n const seen = new Set();\n for (const row of captured) {\n let rowId;\n try {\n rowId = input.getRowId(row);\n if (typeof rowId !== \"string\" && typeof rowId !== \"number\") {\n throw new TypeError(\"Row IDs must be strings or numbers.\");\n }\n }\n catch (cause) {\n throw new PretableRowModelError(\"derivation-failed\", \"The row ID accessor failed.\", { operation: \"set-rows\", cause });\n }\n if (seen.has(rowId)) {\n throw new PretableRowModelError(\"duplicate-row-id\", `Duplicate row ID ${String(rowId)}.`, { operation: \"set-rows\", rowId });\n }\n seen.add(rowId);\n ids.push(rowId);\n }\n const candidates = [];\n const changedRecords = [];\n // The NEW verdict per changed record, computed once beside the record and\n // spent on the drafts below. The OLD verdict never appears here: it is read\n // from `input.root`'s membership, which matters most in the\n // same-reference-mutation retry, where the row OBJECT is unchanged and the\n // two plans are distinct compilations of the same query — nothing keyed by\n // the row could separate the two answers, but the two ROOTS are separate\n // objects.\n const nextVerdicts = new Map();\n const passesNext = (record) => nextVerdicts.get(record);\n const passedPreviously = (rowId) => rowPassesFilter(input.root, rowId);\n const diagnostics = [];\n let sameReferenceMutation = false;\n let added = 0;\n let updated = 0;\n let unchanged = 0;\n for (let sourceOrder = 0; sourceOrder < captured.length; sourceOrder += 1) {\n const row = captured[sourceOrder];\n const rowId = ids[sourceOrder];\n const previous = input.root.rows.get(rowId);\n const sameReference = previous !== undefined && Object.is(previous.row, row);\n const inspection = inspectRowIntegrity(row, rowId, previous?.integrity, sameReference);\n if (inspection.diagnostic)\n diagnostics.push(inspection.diagnostic);\n if (inspection.sameReferenceMutation)\n sameReferenceMutation = true;\n if (previous !== undefined &&\n sameReference &&\n previous.sourceOrder === sourceOrder &&\n !inspection.sameReferenceMutation) {\n unchanged += 1;\n continue;\n }\n candidates.push({\n row,\n rowId,\n sourceOrder,\n integrity: inspection.integrity,\n cachedMetadata: sameReference && !inspection.sameReferenceMutation\n ? previous?.metadata\n : undefined,\n previousSlot: previous?.slot,\n });\n if (previous === undefined)\n added += 1;\n else\n updated += 1;\n }\n const removedRecords = [];\n for (const [rowId, record] of input.root.rows.entries()) {\n if (!seen.has(rowId))\n removedRecords.push(record);\n }\n const removed = removedRecords.length;\n const effective = added > 0 || updated > 0 || removed > 0;\n if (sameReferenceMutation && input.acceptSameReferenceMutation !== true) {\n return {\n rows: input.root.rows,\n sourceOrder: input.root.sourceOrder,\n visible: input.root.visible,\n recordsBySlot: input.root.recordsBySlot,\n visibleSlots: input.root.visibleSlots,\n nextSourceOrder: input.nextSourceOrder,\n added,\n updated,\n removed,\n unchanged,\n ignored: 0,\n issues: Object.freeze([]),\n diagnostics: Object.freeze(diagnostics),\n operations: Object.freeze([]),\n affectedRowIds: Object.freeze([]),\n effective: false,\n sameReferenceMutation: true,\n };\n }\n /*\n * Abandon rule (see `applyFlatTransactionDraft` for the rationale): fresh\n * allocations are recorded and released if this draft is abandoned mid-way\n * (metadata evaluation runs user code and can throw). Removed rows' slots\n * are NEVER released on a failure path — the committed root still owns\n * them. On success they are released at the very end, except the ones\n * handed straight to new rows: a set-rows call both retires and ingests\n * rows in one commit, and handing a retiring row's slot to a new row is\n * release-then-reuse without an allocator round trip — which also keeps a\n * mid-draft throw from ever leaving a still-live row's slot on the free\n * list.\n */\n const allocatedSlots = [];\n const reusableRemovedSlots = removedRecords.map((record) => record.slot);\n const takeSlot = () => {\n const reused = reusableRemovedSlots.pop();\n if (reused !== undefined)\n return reused;\n const slot = input.slots.allocate();\n allocatedSlots.push(slot);\n return slot;\n };\n try {\n for (const candidate of candidates) {\n const { row, rowId, sourceOrder } = candidate;\n // `evaluate` needs a slot up front (it's part of `CompiledRowInput`\n // now, unread this task), but the REAL slot for a brand-new row is\n // still resolved after evaluation succeeds, exactly as before this\n // field existed: `takeSlot()` calls `input.slots.allocate()`, a real\n // allocator mutation that bumps the high-water mark permanently (see\n // `slot-allocator.ts` — capacity never shrinks), and doing that before\n // a throwing accessor runs would leak capacity that a release can't\n // undo. A carried row's slot has no such hazard (no allocator call),\n // so it is used directly. `-1` is a placeholder for the fresh-slot\n // case only: harmless because nothing reads `CompiledRowInput.slot`\n // yet.\n const placeholderSlot = candidate.previousSlot !== undefined ? candidate.previousSlot : -1;\n let metadata;\n try {\n if (candidate.cachedMetadata === undefined) {\n if (input.instrumentation !== undefined)\n input.instrumentation.work.rowsEvaluated += 1;\n metadata = input.queryPlan.evaluate({\n rowId,\n row: row,\n sourceOrder,\n slot: placeholderSlot,\n });\n }\n else {\n metadata = rebaseSourceOrder(candidate.cachedMetadata, sourceOrder);\n }\n }\n catch (error) {\n if (error instanceof PretableRowModelError &&\n error.operation !== \"set-rows\") {\n throw new PretableRowModelError(error.code, error.message, {\n operation: \"set-rows\",\n rowId: error.rowId,\n columnId: error.columnId,\n cause: error.cause,\n });\n }\n throw error;\n }\n const slot = candidate.previousSlot !== undefined\n ? candidate.previousSlot\n : takeSlot();\n const publicRow = Object.freeze({\n kind: \"data\",\n rowId,\n row,\n sourceIndex: sourceOrder,\n depth: 0,\n });\n const record = Object.freeze({\n rowId,\n row,\n sourceOrder,\n slot,\n metadata,\n publicRow,\n integrity: candidate.integrity,\n });\n changedRecords.push(record);\n // A record whose metadata was CARRIED carries its verdict too, and the\n // carried verdict is the previous root's membership: `cachedMetadata` is\n // only offered for an unmutated same-reference row, whose filter-column\n // values are by definition the ones the committed root already judged.\n // Re-running the predicate here would be a second accessor pass over\n // rows this path exists to avoid re-evaluating (a pinned budget).\n nextVerdicts.set(record, candidate.cachedMetadata === undefined\n ? filterVerdict(input.queryPlan, record)\n : passedPreviously(rowId));\n }\n if (!effective) {\n return {\n rows: input.root.rows,\n sourceOrder: input.root.sourceOrder,\n visible: input.root.visible,\n recordsBySlot: input.root.recordsBySlot,\n visibleSlots: input.root.visibleSlots,\n nextSourceOrder: input.nextSourceOrder,\n added,\n updated,\n removed,\n unchanged,\n ignored: 0,\n issues: Object.freeze([]),\n diagnostics: Object.freeze(diagnostics),\n operations: Object.freeze([]),\n affectedRowIds: Object.freeze([]),\n effective: false,\n sameReferenceMutation,\n };\n }\n const rowDraft = instrumentPersistentMap(input.root.rows, input.instrumentation).asTransient();\n const sourceDraft = instrumentOrderStatisticTree(input.root.sourceOrder, input.instrumentation).asTransient();\n const orderChangedRecords = changedRecords.filter((record) => {\n const previous = input.root.rows.get(record.rowId);\n return (previous === undefined ||\n !sameFlatOrder(input.root.queryPlan, input.queryPlan, previous, record, passedPreviously(record.rowId), passesNext(record)));\n });\n const affectedVisibleIds = new Set(orderChangedRecords\n .filter((record) => passedPreviously(record.rowId) || passesNext(record))\n .map((record) => record.rowId));\n for (const record of removedRecords) {\n // A removed row's verdict is the one it was drawn under: membership.\n if (passedPreviously(record.rowId))\n affectedVisibleIds.add(record.rowId);\n }\n let hasUnaffectedVisible = false;\n for (const entry of input.root.visible.rows.entries()) {\n if (!affectedVisibleIds.has(entry.record.rowId)) {\n hasUnaffectedVisible = true;\n break;\n }\n }\n const visibleDraft = affectedVisibleIds.size === 0\n ? undefined\n : instrumentOrderStatisticTree(hasUnaffectedVisible\n ? input.root.visible.rows\n : createFlatVisibleTree(input.queryPlan), input.instrumentation).asTransient();\n for (const record of removedRecords) {\n rowDraft.delete(record.rowId);\n sourceDraft.remove(record.rowId);\n if (hasUnaffectedVisible)\n visibleDraft?.remove(record.rowId);\n }\n if (hasUnaffectedVisible) {\n for (const record of orderChangedRecords) {\n if (passedPreviously(record.rowId))\n visibleDraft?.remove(record.rowId);\n }\n }\n for (const record of changedRecords) {\n rowDraft.set(record.rowId, record);\n const previous = input.root.rows.get(record.rowId);\n if (previous === undefined ||\n previous.sourceOrder !== record.sourceOrder) {\n sourceDraft.insertOrReplace(Object.freeze({\n rowId: record.rowId,\n sourceOrder: record.sourceOrder,\n }));\n }\n }\n for (const record of orderChangedRecords) {\n if (passesNext(record)) {\n visibleDraft?.insertOrReplace(orderedRowEntry(input.queryPlan, record));\n }\n }\n const frozenRows = rowDraft.freeze();\n const frozenSource = sourceDraft.freeze();\n const previousGroups = getGroupIndex(input.root.visible);\n const visible = previousGroups === undefined\n ? visibleDraft === undefined\n ? input.root.visible\n : Object.freeze({ rows: visibleDraft.freeze() })\n : attachGroupIndex(input.root.visible.rows, updateGroupIndex(previousGroups, [\n ...removedRecords,\n ...changedRecords.flatMap((record) => {\n const old = input.root.rows.get(record.rowId);\n return old === undefined ? [] : [old];\n }),\n ], changedRecords, input.root.expansion.overrides, \"set-rows\", input.instrumentation));\n // Set-rows is O(n) already, so the flat bitset is simply rebuilt from the\n // final flat tree (carried or frozen — either way that tree IS the\n // membership this bitset indexes). Grouped roots keep the sentinel.\n const visibleSlots = previousGroups !== undefined\n ? EMPTY_MEMBERSHIP\n : membershipFromFlatTree(visible.rows, input.slots.capacity);\n // Success path only. ORDER IS LOAD-BEARING: the transfer pool above can\n // retire a record and ingest a new one ON THE SAME SLOT in this one\n // commit, so every removal-clear must precede every record-write — a\n // later write to the same slot wins inside `slotVectorWithAll`. Records\n // that carried unchanged keep their bindings via the COW carry.\n const slotWrites = [\n ...removedRecords.map((record) => [record.slot, undefined]),\n ...changedRecords.map((record) => [record.slot, record]),\n ];\n const { next: recordsBySlot, chunksTouched } = slotVectorWithAll(input.root.recordsBySlot, slotWrites, input.slots.capacity);\n if (input.instrumentation !== undefined)\n input.instrumentation.work.slotChunksTouched += chunksTouched;\n // Committed as effective: retired slots not handed to new rows go back to\n // the free list (see the abandon-rule comment above).\n for (const slot of reusableRemovedSlots)\n input.slots.release(slot);\n return {\n rows: frozenRows,\n sourceOrder: frozenSource,\n visible,\n recordsBySlot,\n visibleSlots,\n nextSourceOrder: Math.max(input.nextSourceOrder, captured.length),\n added,\n updated,\n removed,\n unchanged,\n ignored: 0,\n issues: Object.freeze([]),\n diagnostics: Object.freeze(diagnostics),\n operations: Object.freeze([]),\n affectedRowIds: Object.freeze([\n ...removedRecords.map((record) => record.rowId),\n ...changedRecords.map((record) => record.rowId),\n ]),\n effective: true,\n sameReferenceMutation,\n };\n }\n catch (error) {\n // Abandoned draft: give back what it allocated, keep every removed slot.\n for (const slot of allocatedSlots)\n input.slots.release(slot);\n throw error;\n }\n}\n","import { compileQuery, fillSortKeysFromPrevious, isFilterOnlyChange, isSortOnlyChange, } from \"./compiled-query\";\nimport { rebuildRootForFilterOnlyChange } from \"./filter-rebuild\";\nimport { rebuildRootForSortOnlyChange } from \"./sort-rebuild\";\nimport { createCooperativeTransitionCandidate, createCooperativeTransitionRuntime, runCooperativeTransitionSlice, } from \"./cooperative-transition\";\nimport { createDistinctValueManager } from \"./distinct-values\";\nimport { createChangeJournal, getChangeJournalDiagnosticsForTesting, } from \"./change-journal\";\nimport { PretableDisposedModelError, findPretableReentrantMutationError, PretableReentrantMutationError, PretableRowModelError, PretableTransitionCancelledError, } from \"./errors\";\nimport { attachGroupIndex, getGroupIndex, setGroupOverride, } from \"./group-index\";\nimport { createPersistentMap } from \"./persistent/persistent-map\";\nimport { buildRowStore } from \"./row-store\";\nimport { createSlotAllocator } from \"./slot-allocator\";\nimport { EMPTY_MEMBERSHIP } from \"./membership-bitset\";\nimport { createFlatSnapshot, createVisibleIndex, membershipFromFlatTree, } from \"./visible-index\";\nimport { applyFlatTransactionDraft, replaceFlatRowsDraft, } from \"./transaction-draft\";\nfunction createSnapshot(root, instrumentation) {\n const snapshot = createFlatSnapshot(root);\n if (instrumentation === undefined)\n return snapshot;\n const count = (value) => {\n if (value !== undefined)\n instrumentation.work.snapshotOutputRowsRead += 1;\n return value;\n };\n const instrumentedSnapshot = Object.freeze({\n ...snapshot,\n rowAt: (index) => count(snapshot.rowAt(index)),\n range: (start, end) => {\n const rows = snapshot.range(start, end);\n instrumentation.work.snapshotOutputRowsRead += rows.length;\n return rows;\n },\n // The dense range read is a visible-row output walk like `range`; the\n // k-sized reads (`ɵslotOfRowId`, `ɵslotCapacity`) pass through the\n // spread above uncounted.\n ɵvisibleSlotRange: (start, end) => {\n const slots = snapshot.ɵvisibleSlotRange?.(start, end);\n if (slots !== undefined) {\n instrumentation.work.snapshotOutputRowsRead += slots.length;\n }\n return slots;\n },\n dataRowAt: (index) => count(snapshot.dataRowAt(index)),\n firstDataRow: () => count(snapshot.firstDataRow()),\n lastDataRow: () => count(snapshot.lastDataRow()),\n nextDataRow: (ref) => count(snapshot.nextDataRow(ref)),\n previousDataRow: (ref) => count(snapshot.previousDataRow(ref)),\n });\n instrumentation.snapshotRoots.set(instrumentedSnapshot, root);\n instrumentation.currentRevisionRoot = root;\n return instrumentedSnapshot;\n}\n/**\n * Default resident-row ceiling for the synchronous sort-only fast path.\n * Measured, not guessed: the 2026-08-27 browser sweep\n * (`docs/superpowers/specs/2026-08-27-size-gate-sync-paths-results.md`) put\n * the sort path's crossover of the dense-handle arc's 50ms single-block bar\n * near 10k rows (64ms observed at 15k); the default halves the crossover for\n * 2x headroom on machines slower than the sweep's.\n */\nexport const SORT_FAST_PATH_ROW_LIMIT_DEFAULT = 5_000;\n/**\n * Default resident-row ceiling for the synchronous filter-only fast path.\n * From the same sweep: the filter path's 50ms-bar crossover sits near 30k\n * rows (50ms first observed there; 87-93ms at 50k), halved for the same 2x\n * slower-machine headroom.\n */\nexport const FILTER_FAST_PATH_ROW_LIMIT_DEFAULT = 15_000;\nconst modelChangeJournals = new WeakMap();\nconst optionInstrumentation = new WeakMap();\nconst modelRevisionCauses = new WeakMap();\nconst modelActiveTransitionCandidates = new WeakMap();\nconst modelFilterAuthoritySetters = new WeakMap();\nconst modelSortAuthoritySetters = new WeakMap();\nconst modelSlotInternals = new WeakMap();\n/**\n * Re-declares who selected the loaded records, recompiling the plan when the\n * answer changes. Deliberately a registry lookup rather than a method on\n * `PretableRowModel`: only the rows-mode React surface needs it — a consumer\n * who builds their own model already decides what goes into the query — and\n * the public model interface should not grow a knob that boundary excludes.\n *\n * Silently ignores any model this module did not create. Callers must still\n * withhold it from models they do not own — a consumer-supplied model built by\n * `createLocalRowModel` is registered here too, and moving its authority would\n * be exactly the explicit-model change this design excludes.\n *\n * @internal\n */\nexport function ɵsetLocalRowModelFilterAuthority(model, \n// Spelled out rather than named as `CompiledFilterAuthority`: this is the one\n// declaration that crosses into `@pretable/core`'s entry point, and naming an\n// unexported alias there is a forgotten export the public-API guard rejects.\nauthority) {\n modelFilterAuthoritySetters.get(model)?.(authority);\n}\n/**\n * Re-declares who ordered the loaded records. The sort twin of\n * `ɵsetLocalRowModelFilterAuthority`, with the same registry design and\n * the same ownership rule: withhold it from models the surface does not own.\n *\n * @internal\n */\nexport function ɵsetLocalRowModelSortAuthority(model, authority) {\n modelSortAuthoritySetters.get(model)?.(authority);\n}\n/** Direct diagnostics seam; intentionally absent from the package barrel. */\nexport function registerLocalRowModelInstrumentationForTesting(options, instrumentation) {\n optionInstrumentation.set(options, instrumentation);\n}\nexport function getLocalRowModelRevisionCauseForTesting(model) {\n const read = modelRevisionCauses.get(model);\n if (read === undefined) {\n throw new TypeError(\"Diagnostics require a local Pretable row model.\");\n }\n return read();\n}\nexport function getLocalRowModelActiveTransitionCandidateForTesting(model) {\n const read = modelActiveTransitionCandidates.get(model);\n if (read === undefined) {\n throw new TypeError(\"Diagnostics require a local Pretable row model.\");\n }\n return read();\n}\n/**\n * Committed-root and slot-allocator seam for the slot-lifecycle tests;\n * intentionally absent from the package barrel.\n *\n * @internal test-only\n */\nexport function getLocalRowModelSlotInternalsForTesting(model) {\n const read = modelSlotInternals.get(model);\n if (read === undefined) {\n throw new TypeError(\"Diagnostics require a local Pretable row model.\");\n }\n return read();\n}\nexport function getLocalRowModelChangeJournalDiagnosticsForTesting(model) {\n const journal = modelChangeJournals.get(model);\n if (journal === undefined) {\n throw new TypeError(\"Diagnostics require a local Pretable row model.\");\n }\n return getChangeJournalDiagnosticsForTesting(journal);\n}\nclass PretableSetRowsExecutionError extends PretableRowModelError {\n name = \"PretableSetRowsExecutionError\";\n rowIds;\n groupValues;\n groupId;\n value;\n constructor(error) {\n super(error.code, error.message, {\n operation: \"set-rows\",\n rowId: error.rowId,\n columnId: error.columnId,\n cause: error.cause,\n });\n const detailed = error;\n this.rowIds = detailed.rowIds && Object.freeze([...detailed.rowIds]);\n this.groupValues =\n detailed.groupValues && Object.freeze([...detailed.groupValues]);\n this.groupId = detailed.groupId;\n this.value = detailed.value;\n }\n}\nclass PretableOperationExecutionError extends PretableRowModelError {\n name = \"PretableOperationExecutionError\";\n rowIds;\n groupValues;\n groupId;\n value;\n constructor(error, operation) {\n super(error.code, error.message, {\n operation,\n rowId: error.rowId,\n columnId: error.columnId,\n cause: error.cause,\n });\n const detailed = error;\n this.rowIds = detailed.rowIds && Object.freeze([...detailed.rowIds]);\n this.groupValues =\n detailed.groupValues && Object.freeze([...detailed.groupValues]);\n this.groupId = detailed.groupId;\n this.value = detailed.value;\n }\n}\nfunction remapOperationError(error, operation) {\n if (error instanceof PretableRowModelError &&\n error.code !== \"reentrant-mutation\" &&\n error.operation !== operation) {\n return new PretableOperationExecutionError(error, operation);\n }\n return error;\n}\nfunction remapSetRowsError(error) {\n if (error instanceof PretableRowModelError &&\n error.code !== \"reentrant-mutation\" &&\n error.operation !== \"set-rows\") {\n return new PretableSetRowsExecutionError(error);\n }\n return error;\n}\nfunction emitDiagnostics(diagnostics, sink) {\n if (sink === undefined)\n return;\n for (const diagnostic of diagnostics) {\n try {\n sink(diagnostic);\n }\n catch {\n // Diagnostics run after publication and never change command success.\n }\n }\n}\nconst READY = Object.freeze({ kind: \"ready\" });\nconst DISPOSED = Object.freeze({ kind: \"disposed\" });\nfunction emptyQuery() {\n return Object.freeze({\n filters: Object.freeze([]),\n sort: Object.freeze([]),\n rowGroups: Object.freeze([]),\n });\n}\nfunction createExpansionRoot(policy) {\n // Expanded, not collapsed. Grouping here is an interactive act as much as a\n // configuration one — the user drags a column into the group panel while\n // reading their rows — and collapsing on drop makes the data they were just\n // looking at disappear. AG Grid (`groupDefaultExpanded: 0`) and TanStack\n // (empty expanded map) both default collapsed, where grouping is set up by a\n // developer before the user arrives; `{ kind: \"through-depth\" }` is the\n // escape hatch for datasets too large to open at once.\n const defaultPolicy = Object.freeze(policy === undefined ? { kind: \"expanded\" } : { ...policy });\n return Object.freeze({\n default: defaultPolicy,\n overrides: createPersistentMap(),\n state: Object.freeze({ default: defaultPolicy, overrideCount: 0 }),\n });\n}\nfunction mutationResult(previousRevision, revision, counts = {}, issues = []) {\n return Object.freeze({\n previousRevision,\n revision,\n added: counts.added ?? 0,\n updated: counts.updated ?? 0,\n removed: counts.removed ?? 0,\n unchanged: counts.unchanged ?? 0,\n ignored: counts.ignored ?? 0,\n issues: Object.freeze(Array.from(issues)),\n });\n}\nfunction visibleRef(row) {\n return row.kind === \"data\"\n ? Object.freeze({ kind: \"data\", rowId: row.rowId })\n : Object.freeze({ kind: \"group\", groupId: row.groupId });\n}\nfunction expansionChangeOperations(previous, next, groupId) {\n const ref = Object.freeze({ kind: \"group\", groupId });\n const previousIndex = previous.indexOf(ref);\n const index = next.indexOf(ref);\n if (previousIndex < 0 || index < 0)\n return Object.freeze([]);\n const previousGroup = previous.rowAt(previousIndex);\n const nextGroup = next.rowAt(index);\n if (previousGroup?.kind !== \"group\" || nextGroup?.kind !== \"group\") {\n return Object.freeze([]);\n }\n const operations = [];\n if (previousGroup.expanded !== nextGroup.expanded) {\n operations.push(Object.freeze({\n kind: \"update\",\n ref,\n index,\n fields: Object.freeze([\"expanded\"]),\n }));\n }\n if (previousGroup.expanded && !nextGroup.expanded) {\n const descendants = [];\n for (let descendantIndex = previousIndex + 1; descendantIndex < previous.visibleRowCount; descendantIndex += 1) {\n const row = previous.rowAt(descendantIndex);\n if (row === undefined || row.depth <= previousGroup.depth)\n break;\n descendants.push({\n ref: visibleRef(row),\n previousIndex: descendantIndex,\n });\n }\n for (const descendant of descendants.reverse()) {\n operations.push(Object.freeze({ kind: \"remove\", ...descendant }));\n }\n }\n else if (!previousGroup.expanded && nextGroup.expanded) {\n for (let descendantIndex = index + 1; descendantIndex < next.visibleRowCount; descendantIndex += 1) {\n const row = next.rowAt(descendantIndex);\n if (row === undefined || row.depth <= nextGroup.depth)\n break;\n operations.push(Object.freeze({\n kind: \"insert\",\n ref: visibleRef(row),\n index: descendantIndex,\n }));\n }\n }\n return Object.freeze(operations);\n}\n/** @public */\nexport function createLocalRowModel(options) {\n const instrumentation = optionInstrumentation.get(options);\n optionInstrumentation.delete(options);\n const columns = Object.freeze(Array.from(options.columns));\n const getRowId = options.getRowId ??\n ((row) => row.id);\n const requestedDerivations = (options.derivations ??\n columns);\n const requestedQuery = options.query ?? emptyQuery();\n let filterAuthority = options.ɵfilterAuthority ?? \"engine\";\n let sortAuthority = options.ɵsortAuthority ?? \"engine\";\n let queryPlan = compileQuery({\n derivations: requestedDerivations,\n query: requestedQuery,\n filterAuthority,\n sortAuthority,\n });\n let derivations = queryPlan.derivations;\n let query = queryPlan.query;\n const aggregateFilteredRows = options.aggregateFilteredRows ?? false;\n const diagnosticSink = options.onDiagnostic;\n /**\n * Per-model row-slot allocator — mutable instance state, like\n * `nextSourceOrder`. Every record-creating path below threads it so a row's\n * slot is assigned exactly once, at ingest, and released exactly once, on\n * permanent removal.\n */\n const slots = createSlotAllocator();\n const initialStore = buildRowStore({\n rows: options.rows,\n getRowId,\n queryPlan,\n slots,\n instrumentation,\n });\n const initialExpansion = createExpansionRoot(options.initialExpansion);\n const initialVisible = createVisibleIndex(initialStore.records, queryPlan, aggregateFilteredRows, initialExpansion.overrides);\n let root = Object.freeze({\n revision: 0,\n parentRevision: null,\n rows: initialStore.rows,\n sourceOrder: initialStore.sourceOrder,\n recordsBySlot: initialStore.recordsBySlot,\n slotCapacity: slots.capacity,\n // Flat roots index their membership per slot; grouped roots carry the\n // sentinel and keep answering from the group index.\n visibleSlots: queryPlan.query.rowGroups.length > 0\n ? EMPTY_MEMBERSHIP\n : membershipFromFlatTree(initialVisible.rows, slots.capacity),\n visible: initialVisible,\n queryPlan,\n expansion: initialExpansion,\n cause: Object.freeze({ kind: \"initial\" }),\n });\n let snapshot = createSnapshot(root, instrumentation);\n let state = Object.freeze({\n snapshot,\n status: READY,\n });\n let disposed = false;\n let activeMutation;\n let nextSourceOrder = initialStore.records.length;\n let nextTransitionId = 1;\n let activeTransition;\n const listeners = new Set();\n const changeJournal = createChangeJournal(options.changeJournalCapacity);\n const sortFastPathRowLimit = options.ɵsortFastPathRowLimit ?? SORT_FAST_PATH_ROW_LIMIT_DEFAULT;\n const filterFastPathRowLimit = options.ɵfilterFastPathRowLimit ?? FILTER_FAST_PATH_ROW_LIMIT_DEFAULT;\n const transitionRuntime = createCooperativeTransitionRuntime({\n scheduler: options.transitionScheduler,\n now: options.transitionClock,\n budgetMs: options.transitionBudgetMs,\n maxUnitsPerSlice: options.transitionMaxUnitsPerSlice,\n instrumentation,\n });\n const distinctValues = createDistinctValueManager({\n getRoot: () => root,\n getDerivations: () => derivations,\n runtime: transitionRuntime,\n cacheCapacity: options.distinctValueCacheCapacity,\n });\n const assertCommandAllowed = (operation) => {\n if (activeMutation !== undefined) {\n throw new PretableReentrantMutationError(operation, activeMutation);\n }\n if (disposed)\n throw new PretableDisposedModelError(operation);\n };\n const guarded = (operation, action) => {\n assertCommandAllowed(operation);\n activeMutation = operation;\n try {\n return action();\n }\n catch (error) {\n const reentrant = findPretableReentrantMutationError(error);\n if (reentrant !== undefined)\n throw reentrant;\n throw error;\n }\n finally {\n activeMutation = undefined;\n }\n };\n const rebuildingStatus = (transition) => Object.freeze({\n kind: \"rebuilding\",\n transitionId: transition.id,\n completedRows: transition.candidate.completedRows,\n totalRows: transition.candidate.totalRows,\n });\n const commit = (next, status = activeTransition === undefined\n ? READY\n : rebuildingStatus(activeTransition)) => {\n root = next;\n snapshot = createSnapshot(root, instrumentation);\n state = Object.freeze({ snapshot, status });\n };\n const notify = () => {\n for (const listener of Array.from(listeners)) {\n try {\n listener();\n }\n catch {\n // One consumer must not prevent the remaining subscribers from waking.\n }\n }\n };\n const publishCommittedRoot = (committedRoot, previousRevision, revision, \n // Only the sort-only fast path may pass \"reorder\" (the one commit that\n // provably changes order and nothing else) and only the filter-only\n // fast path may pass \"refilter\" (membership changed, surviving order\n // and identities intact). Every other publisher keeps the plain\n // barrier default.\n barrierReason = \"bulk-replace\") => {\n queryPlan = committedRoot.queryPlan;\n query = committedRoot.queryPlan.query;\n derivations = committedRoot.queryPlan.derivations;\n commit(committedRoot, READY);\n // Every publisher goes through this one recipe. On a sort-only change\n // the distinct publish is structurally a no-op (distinct-value cache\n // keys hash filter/column/population semantics, never sort); on a\n // filter-only change it is LOAD-BEARING — filters are part of those\n // cache keys, so the new root must reach the manager here.\n distinctValues.publishTransitionRoot(committedRoot);\n changeJournal.appendBarrier(previousRevision, revision, barrierReason);\n };\n const transitionError = (error, operation) => {\n const remapped = remapOperationError(error, operation);\n return remapped instanceof PretableRowModelError\n ? remapped\n : new PretableRowModelError(\"derivation-failed\", `The ${operation} transition failed.`, { operation, cause: remapped });\n };\n const cancelActiveTransition = (reason) => {\n const transition = activeTransition;\n if (transition === undefined)\n return undefined;\n activeTransition = undefined;\n const cancelScheduled = transition.cancelScheduled;\n transition.cancelScheduled = undefined;\n try {\n cancelScheduled?.();\n }\n catch {\n // Scheduler cancellation is best-effort; model ownership still releases.\n }\n transition.candidate.release();\n transition.reject(new PretableTransitionCancelledError(transition.id, reason));\n return transition;\n };\n const failTransition = (transition, error) => {\n if (activeTransition !== transition)\n return;\n activeTransition = undefined;\n const cancelScheduled = transition.cancelScheduled;\n transition.cancelScheduled = undefined;\n try {\n cancelScheduled?.();\n }\n catch {\n // Preserve the transition failure rather than a scheduler cleanup error.\n }\n transition.candidate.release();\n const typed = findPretableReentrantMutationError(error) ??\n transitionError(error, transition.operation);\n state = Object.freeze({\n snapshot,\n status: Object.freeze({\n kind: \"error\",\n transitionId: transition.id,\n error: typed,\n }),\n });\n transition.reject(typed);\n };\n const scheduleTransition = (transition) => {\n transition.cancelScheduled = transitionRuntime.scheduler.schedule(() => {\n if (disposed || activeTransition !== transition)\n return;\n let changed = false;\n try {\n changed = guarded(transition.operation, () => {\n transition.cancelScheduled = undefined;\n return runTransitionSlice(transition);\n });\n }\n catch (error) {\n failTransition(transition, error);\n changed = true;\n }\n if (changed)\n notify();\n });\n };\n const runTransitionSlice = (transition) => {\n if (activeTransition !== transition || disposed)\n return false;\n try {\n const complete = runCooperativeTransitionSlice(transitionRuntime, () => transition.candidate.step());\n if (activeTransition !== transition || disposed)\n return false;\n if (!complete) {\n state = Object.freeze({\n snapshot,\n status: rebuildingStatus(transition),\n });\n scheduleTransition(transition);\n return true;\n }\n const previousRevision = root.revision;\n const revision = previousRevision + 1;\n const committedRoot = transition.candidate.finish(revision);\n activeTransition = undefined;\n const cancelScheduled = transition.cancelScheduled;\n transition.cancelScheduled = undefined;\n try {\n cancelScheduled?.();\n }\n catch {\n // Successful publication cannot be rolled back by advisory cleanup.\n }\n publishCommittedRoot(committedRoot, previousRevision, revision);\n transition.candidate.release();\n transition.resolve(revision);\n return true;\n }\n catch (error) {\n failTransition(transition, error);\n return true;\n }\n };\n const startTransition = (id, operation, nextPlan) => {\n cancelActiveTransition(\"superseded\");\n let resolve;\n let reject;\n const finished = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n // Mark internal lifecycle rejection as observed without changing the\n // original promise returned to callers or its await/rejection semantics.\n void finished.catch(() => undefined);\n const transition = {\n id,\n operation,\n candidate: createCooperativeTransitionCandidate({\n captured: root,\n queryPlan: nextPlan,\n aggregateFilteredRows,\n operation,\n instrumentation,\n }),\n finished,\n resolve,\n reject,\n cancelScheduled: undefined,\n };\n activeTransition = transition;\n state = Object.freeze({ snapshot, status: rebuildingStatus(transition) });\n runTransitionSlice(transition);\n return transition;\n };\n const appendTransitionDelta = (target, affectedRowIds) => {\n activeTransition?.candidate.append(Object.freeze({\n target,\n affectedRowIds: Object.freeze([...affectedRowIds]),\n }));\n };\n const cancelTransitionHandle = (id, operation) => {\n const cancelled = guarded(operation, () => {\n if (activeTransition?.id !== id)\n return false;\n cancelActiveTransition(\"cancelled\");\n state = Object.freeze({ snapshot, status: READY });\n return true;\n });\n if (cancelled)\n notify();\n };\n const applyExpansionDefault = (operation, policy, expansionOptions) => {\n try {\n const prepared = guarded(operation, () => {\n const previousRoot = root;\n const nextPolicy = Object.freeze({\n ...policy,\n });\n const preserve = expansionOptions?.preserveOverrides === true;\n const samePolicy = JSON.stringify(previousRoot.expansion.default) ===\n JSON.stringify(nextPolicy);\n if (samePolicy &&\n (preserve || previousRoot.expansion.overrides.size === 0)) {\n return {\n result: mutationResult(previousRoot.revision, previousRoot.revision),\n notify: false,\n };\n }\n let groups = getGroupIndex(previousRoot.visible);\n if (!preserve && groups !== undefined) {\n for (const [groupId] of previousRoot.expansion.overrides.entries()) {\n groups = setGroupOverride(groups, groupId, undefined, operation);\n }\n }\n const overrides = preserve\n ? previousRoot.expansion.overrides\n : createPersistentMap();\n const expansion = Object.freeze({\n default: nextPolicy,\n overrides,\n state: Object.freeze({\n default: nextPolicy,\n overrideCount: overrides.size,\n }),\n });\n const revision = previousRoot.revision + 1;\n const committedRoot = Object.freeze({\n ...previousRoot,\n revision,\n parentRevision: previousRoot.revision,\n visible: groups === undefined\n ? previousRoot.visible\n : attachGroupIndex(previousRoot.visible.rows, groups),\n expansion,\n });\n appendTransitionDelta(committedRoot, []);\n commit(committedRoot);\n changeJournal.appendBarrier(previousRoot.revision, revision);\n return {\n result: mutationResult(previousRoot.revision, revision),\n notify: true,\n };\n });\n if (prepared.notify)\n notify();\n return prepared.result;\n }\n catch (error) {\n throw remapOperationError(error, operation);\n }\n };\n const model = {\n getState: () => state,\n getColumns: () => columns,\n subscribe(listener) {\n if (disposed)\n return () => undefined;\n listeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed)\n return;\n subscribed = false;\n listeners.delete(listener);\n };\n },\n setRows(nextRows) {\n try {\n const prepared = guarded(\"set-rows\", () => {\n const previousRoot = root;\n let nextPlan = queryPlan;\n let drafted = replaceFlatRowsDraft({\n root: previousRoot,\n rows: nextRows,\n getRowId,\n queryPlan: nextPlan,\n nextSourceOrder,\n slots,\n instrumentation,\n });\n const pendingDiagnostics = drafted.diagnostics;\n if (drafted.sameReferenceMutation) {\n nextPlan = compileQuery({\n derivations,\n query,\n filterAuthority,\n sortAuthority,\n });\n /*\n * The recompile is a plan swap, so the fresh plan's sort-key\n * store must be filled for every surviving row — rows the draft\n * re-evaluates get overwritten with recomputed values right\n * after, and untouched rows carry their previous keys. Without\n * this, records carried into the committed root would be\n * unresolvable under the root's own plan.\n */\n for (const [, record] of previousRoot.rows.entries()) {\n fillSortKeysFromPrevious(nextPlan, queryPlan, record, instrumentation);\n }\n drafted = replaceFlatRowsDraft({\n root: previousRoot,\n rows: nextRows,\n getRowId,\n queryPlan: nextPlan,\n nextSourceOrder,\n acceptSameReferenceMutation: true,\n slots,\n instrumentation,\n });\n if (drafted.effective) {\n /*\n * The draft's visible index reuses trees whose comparators\n * captured the RETIRED plan, and that plan's store still holds\n * the pre-mutation keys for every in-place-mutated row object.\n * Rebuild the index under the fresh plan so every entry is\n * re-decorated with keys from the store that actually saw the\n * mutation. The draft emits no per-row operations, so the\n * rebuild is journal-invisible.\n */\n const records = [];\n // `range(0, size)`, not `entries()` — a full walk into an\n // array (see `iterateEntries`).\n for (const entry of drafted.sourceOrder.range(0, drafted.sourceOrder.size)) {\n const record = drafted.rows.get(entry.rowId);\n if (record !== undefined)\n records.push(record);\n }\n const rebuiltVisible = createVisibleIndex(records, nextPlan, aggregateFilteredRows, previousRoot.expansion.overrides);\n drafted = {\n ...drafted,\n visible: rebuiltVisible,\n // The rebuilt index resolves the same membership (same rows,\n // same query, fresh plan), but derive the bitset from the\n // tree that ships rather than carrying the draft's — the two\n // must never be allowed to drift.\n visibleSlots: nextPlan.query.rowGroups.length > 0\n ? EMPTY_MEMBERSHIP\n : membershipFromFlatTree(rebuiltVisible.rows, slots.capacity),\n };\n }\n }\n if (!drafted.effective) {\n return {\n result: mutationResult(previousRoot.revision, previousRoot.revision, drafted),\n notify: false,\n diagnostics: Object.freeze([]),\n };\n }\n const previousRevision = previousRoot.revision;\n const committedRoot = Object.freeze({\n revision: previousRevision + 1,\n parentRevision: previousRevision,\n rows: drafted.rows,\n sourceOrder: drafted.sourceOrder,\n recordsBySlot: drafted.recordsBySlot,\n // Commit-time capacity: nothing between the draft and this\n // commit allocates, so this is the capacity the vector above\n // was built for.\n slotCapacity: slots.capacity,\n visibleSlots: drafted.visibleSlots,\n visible: drafted.visible,\n queryPlan: nextPlan,\n expansion: previousRoot.expansion,\n cause: Object.freeze({ kind: \"set-rows\" }),\n });\n const result = mutationResult(previousRevision, committedRoot.revision, drafted);\n const distinctCommit = distinctValues.prepareCommit(committedRoot, drafted.affectedRowIds, \"set-rows\");\n queryPlan = nextPlan;\n nextSourceOrder = drafted.nextSourceOrder;\n appendTransitionDelta(committedRoot, drafted.affectedRowIds);\n commit(committedRoot);\n distinctValues.publishCommit(distinctCommit, committedRoot, drafted.affectedRowIds);\n changeJournal.appendBarrier(previousRevision, committedRoot.revision);\n return {\n result,\n notify: true,\n diagnostics: pendingDiagnostics,\n };\n });\n if (prepared.notify)\n notify();\n emitDiagnostics(prepared.diagnostics, diagnosticSink);\n return prepared.result;\n }\n catch (error) {\n throw remapSetRowsError(error);\n }\n },\n applyTransaction(transaction) {\n const prepared = guarded(\"apply-transaction\", () => {\n const previousRoot = root;\n const drafted = applyFlatTransactionDraft({\n root: previousRoot,\n transaction,\n getRowId,\n queryPlan,\n nextSourceOrder,\n slots,\n instrumentation,\n });\n const result = mutationResult(previousRoot.revision, drafted.effective ? previousRoot.revision + 1 : previousRoot.revision, drafted, drafted.issues);\n if (!drafted.effective) {\n return { result, notify: false, diagnostics: drafted.diagnostics };\n }\n const committedRoot = Object.freeze({\n revision: result.revision,\n parentRevision: previousRoot.revision,\n rows: drafted.rows,\n sourceOrder: drafted.sourceOrder,\n recordsBySlot: drafted.recordsBySlot,\n // Commit-time capacity (see the setRows commit above).\n slotCapacity: slots.capacity,\n visibleSlots: drafted.visibleSlots,\n visible: drafted.visible,\n queryPlan,\n expansion: previousRoot.expansion,\n cause: Object.freeze({ kind: \"set-rows\" }),\n });\n const distinctCommit = distinctValues.prepareCommit(committedRoot, drafted.affectedRowIds, \"apply-transaction\");\n nextSourceOrder = drafted.nextSourceOrder;\n appendTransitionDelta(committedRoot, drafted.affectedRowIds);\n commit(committedRoot);\n distinctValues.publishCommit(distinctCommit, committedRoot, drafted.affectedRowIds);\n changeJournal.appendChanges(previousRoot.revision, committedRoot.revision, drafted.operations);\n return { result, notify: true, diagnostics: drafted.diagnostics };\n });\n if (prepared.notify)\n notify();\n emitDiagnostics(prepared.diagnostics, diagnosticSink);\n return prepared.result;\n },\n setQuery(nextQuery) {\n const prepared = guarded(\"set-query\", () => {\n const id = nextTransitionId++;\n const nextPlan = compileQuery({\n derivations,\n query: nextQuery,\n previous: queryPlan,\n operation: \"set-query\",\n filterAuthority,\n sortAuthority,\n });\n if (nextPlan === queryPlan) {\n const superseded = cancelActiveTransition(\"superseded\") !== undefined;\n if (superseded)\n state = Object.freeze({ snapshot, status: READY });\n return {\n transition: Object.freeze({\n id,\n requestedQuery: queryPlan.query,\n finished: Promise.resolve(root.revision),\n cancel: () => cancelTransitionHandle(id, \"set-query\"),\n }),\n notify: superseded,\n };\n }\n // The two synchronous fast paths share one commit and error shape;\n // they differ only in the rebuild and the barrier reason, and each\n // reason is that path's exclusive promise. \"reorder\" is the sort\n // path's — the one commit that provably changes order and nothing\n // else. \"refilter\" is the filter path's — membership changed while\n // surviving rows kept their relative order and identities. Neither\n // may cross over: a \"reorder\" on a membership change would tell\n // renderers to permute retained rows over a different row set and\n // corrupt their layout, and vice versa.\n //\n // Each path is additionally size-gated (#488): the arc's bar is that\n // no single main-thread block exceeds 50ms, and both sync rebuilds\n // run on the caller's stack with cost bounded by the RESIDENT\n // population (exact for the filter rebuild's bulk verdict pass; an\n // upper bound for the sort rebuild, which sorts the visible set).\n // The count is `root.rows.size`, the committed population — never\n // `slotCapacity` (inflated by churn), and for the filter arm never\n // `visible.rows.size` (a widening filter would dispatch as\n // \"small\"). Above a path's measured limit the same change falls\n // through to the cooperative transition, which blocks ~0; the gate\n // only ever moves work from sync to cooperative. Grouped queries\n // stay first and never consult the count.\n const residentRowCount = root.rows.size;\n const fastPath = nextPlan.query.rowGroups.length > 0\n ? undefined\n : isSortOnlyChange(queryPlan, nextPlan)\n ? residentRowCount <= sortFastPathRowLimit\n ? Object.freeze({\n rebuild: rebuildRootForSortOnlyChange,\n barrierReason: \"reorder\",\n })\n : undefined\n : isFilterOnlyChange(queryPlan, nextPlan)\n ? residentRowCount <= filterFastPathRowLimit\n ? Object.freeze({\n rebuild: rebuildRootForFilterOnlyChange,\n barrierReason: \"refilter\",\n })\n : undefined\n : undefined;\n if (fastPath !== undefined) {\n cancelActiveTransition(\"superseded\");\n const previousRevision = root.revision;\n const revision = previousRevision + 1;\n let committedRoot;\n try {\n committedRoot = fastPath.rebuild({\n captured: root,\n nextPlan,\n revision,\n now: transitionRuntime.now,\n instrumentation,\n });\n }\n catch (error) {\n // Mirrors failTransition's observable semantics: an error status\n // carrying this transition's id, a rejected `finished`, and the\n // committed root left untouched.\n const typed = findPretableReentrantMutationError(error) ??\n transitionError(error, \"set-query\");\n state = Object.freeze({\n snapshot,\n status: Object.freeze({\n kind: \"error\",\n transitionId: id,\n error: typed,\n }),\n });\n const finished = Promise.reject(typed);\n void finished.catch(() => undefined);\n return {\n transition: Object.freeze({\n id,\n requestedQuery: nextPlan.query,\n finished,\n cancel: () => cancelTransitionHandle(id, \"set-query\"),\n }),\n notify: true,\n };\n }\n publishCommittedRoot(committedRoot, previousRevision, revision, fastPath.barrierReason);\n return {\n transition: Object.freeze({\n id,\n requestedQuery: nextPlan.query,\n finished: Promise.resolve(revision),\n cancel: () => cancelTransitionHandle(id, \"set-query\"),\n }),\n notify: true,\n };\n }\n const active = startTransition(id, \"set-query\", nextPlan);\n return {\n transition: Object.freeze({\n id,\n requestedQuery: nextPlan.query,\n finished: active.finished,\n cancel: () => cancelTransitionHandle(id, \"set-query\"),\n }),\n notify: true,\n };\n });\n if (prepared.notify)\n notify();\n return prepared.transition;\n },\n setDerivations(nextDerivations) {\n try {\n const prepared = guarded(\"set-derivations\", () => {\n const id = nextTransitionId++;\n const capturedPlan = compileQuery({\n derivations: nextDerivations,\n query,\n operation: \"set-derivations\",\n filterAuthority,\n sortAuthority,\n });\n const nextPlan = compileQuery({\n derivations: capturedPlan.derivations,\n query,\n previous: queryPlan,\n operation: \"set-derivations\",\n filterAuthority,\n sortAuthority,\n });\n if (nextPlan === queryPlan) {\n derivations = capturedPlan.derivations;\n distinctValues.publishTransitionRoot(root);\n const superseded = cancelActiveTransition(\"superseded\") !== undefined;\n if (superseded)\n state = Object.freeze({ snapshot, status: READY });\n return {\n transition: Object.freeze({\n id,\n requestedDerivations: capturedPlan.derivations,\n finished: Promise.resolve(root.revision),\n cancel: () => cancelTransitionHandle(id, \"set-derivations\"),\n }),\n notify: superseded,\n };\n }\n const active = startTransition(id, \"set-derivations\", nextPlan);\n return {\n transition: Object.freeze({\n id,\n requestedDerivations: nextPlan.derivations,\n finished: active.finished,\n cancel: () => cancelTransitionHandle(id, \"set-derivations\"),\n }),\n notify: true,\n };\n });\n if (prepared.notify)\n notify();\n return prepared.transition;\n }\n catch (error) {\n throw remapOperationError(error, \"set-derivations\");\n }\n },\n setGroupExpanded(groupId, expanded) {\n try {\n const prepared = guarded(\"set-group-expanded\", () => {\n const previousRoot = root;\n const groups = getGroupIndex(previousRoot.visible);\n const group = groups?.groups.get(groupId);\n if (groups === undefined || group === undefined) {\n return {\n result: mutationResult(previousRoot.revision, previousRoot.revision, { ignored: 1 }, [Object.freeze({ code: \"unknown-group-id\", groupId })]),\n notify: false,\n };\n }\n const defaultExpanded = previousRoot.expansion.default.kind === \"expanded\" ||\n (previousRoot.expansion.default.kind === \"through-depth\" &&\n group.depth <= previousRoot.expansion.default.depth);\n const override = expanded === defaultExpanded ? undefined : expanded;\n const current = previousRoot.expansion.overrides.get(groupId);\n const exists = previousRoot.expansion.overrides.has(groupId);\n if ((override === undefined && !exists) ||\n (override !== undefined && exists && current === override)) {\n return {\n result: mutationResult(previousRoot.revision, previousRoot.revision),\n notify: false,\n };\n }\n const overrides = override === undefined\n ? previousRoot.expansion.overrides.delete(groupId)\n : previousRoot.expansion.overrides.set(groupId, override);\n const nextGroups = setGroupOverride(groups, groupId, override, \"set-group-expanded\");\n const expansion = Object.freeze({\n default: previousRoot.expansion.default,\n overrides,\n state: Object.freeze({\n default: previousRoot.expansion.default,\n overrideCount: overrides.size,\n }),\n });\n const revision = previousRoot.revision + 1;\n const committedRoot = Object.freeze({\n ...previousRoot,\n revision,\n parentRevision: previousRoot.revision,\n visible: attachGroupIndex(previousRoot.visible.rows, nextGroups),\n expansion,\n });\n const previousSnapshot = snapshot;\n const nextSnapshot = createFlatSnapshot(committedRoot);\n const operations = expansionChangeOperations(previousSnapshot, nextSnapshot, groupId);\n appendTransitionDelta(committedRoot, []);\n commit(committedRoot);\n changeJournal.appendChanges(previousRoot.revision, revision, operations);\n return {\n result: mutationResult(previousRoot.revision, revision),\n notify: true,\n };\n });\n if (prepared.notify)\n notify();\n return prepared.result;\n }\n catch (error) {\n throw remapOperationError(error, \"set-group-expanded\");\n }\n },\n setExpansionDefault(policy, expansionOptions) {\n return applyExpansionDefault(\"set-expansion-default\", policy, expansionOptions);\n },\n expandAll() {\n return applyExpansionDefault(\"expand-all\", { kind: \"expanded\" });\n },\n collapseAll() {\n return applyExpansionDefault(\"collapse-all\", { kind: \"collapsed\" });\n },\n changesSince(revision) {\n assertCommandAllowed(\"changes-since\");\n return changeJournal.changesSince(revision, root.revision);\n },\n distinctValues(columnId, distinctOptions) {\n return guarded(\"distinct-values\", () => distinctValues.query(columnId, distinctOptions));\n },\n dispose() {\n if (activeMutation !== undefined) {\n throw new PretableReentrantMutationError(\"dispose\", activeMutation);\n }\n if (disposed)\n return;\n const current = guarded(\"dispose\", () => {\n cancelActiveTransition(\"disposed\");\n distinctValues.dispose(new PretableDisposedModelError(\"distinct-values\"));\n changeJournal.clear();\n disposed = true;\n state = Object.freeze({ snapshot, status: DISPOSED });\n if (instrumentation !== undefined)\n instrumentation.currentRevisionRoot = root;\n const captured = Array.from(listeners);\n listeners.clear();\n return captured;\n });\n for (const listener of current) {\n try {\n listener();\n }\n catch {\n // Disposal still detaches and wakes every listener exactly once.\n }\n }\n },\n };\n // Construction has no subscribers. Future ingestion diagnostics, if any,\n // are delivered only after the initial immutable state and model exist.\n modelChangeJournals.set(model, changeJournal);\n modelRevisionCauses.set(model, () => root.cause);\n modelActiveTransitionCandidates.set(model, () => activeTransition?.candidate);\n modelSlotInternals.set(model, () => ({ root: root, slots }));\n /*\n * Re-running `setQuery` with the query the model already holds is what makes\n * the flip take effect: the query is unchanged, so nothing reported moves,\n * while the plan differs by authority alone and `semanticallyMatches` now\n * refuses to reuse it. The rebuild is the ordinary cooperative transition,\n * cancellation and status included.\n */\n modelFilterAuthoritySetters.set(model, (authority) => {\n if (disposed || authority === filterAuthority)\n return;\n filterAuthority = authority;\n const transition = model.setQuery(query);\n void transition.finished.catch(() => undefined);\n });\n modelSortAuthoritySetters.set(model, (authority) => {\n if (disposed || authority === sortAuthority)\n return;\n sortAuthority = authority;\n const transition = model.setQuery(query);\n void transition.finished.catch(() => undefined);\n });\n distinctValues.attachModel(model);\n emitDiagnostics(initialStore.diagnostics, diagnosticSink);\n return model;\n}\n","/**\n * Per-column aggregate OVERRIDES, applied to a derivation list.\n *\n * grid-core stores what a tool panel chose (`PretableGridUiState`'s\n * `columnAggregates`); row-model resolves what an aggregate MEANS. Both layers\n * CAN see both halves — `createGridUiCore` takes a `rowModel` and that\n * interface exposes `setDerivations` — so this is a layering choice, not an\n * impossibility: row-model must not depend on grid-core's state shape, and\n * grid-core deliberately drives no derivations at all (it never calls\n * `setDerivations`). The merge is therefore a pure function that a composing\n * layer calls with both inputs, and the merged list travels the ordinary\n * `setDerivations` / `compileQuery` path from there.\n */\n/**\n * Apply `overrides` on top of the `aggregate` each derivation declares.\n *\n * IDS ARE THE SCHEMA VOCABULARY — the `id` on the derivations themselves, the\n * same ids `PretableQueryFor` and `RuntimeColumn` use. grid-core keys\n * `columnAggregates` by the LAYOUT column vocabulary instead (see its doc on\n * `PretableGridUiState.columnAggregates`), so a caller reading that state owes\n * the translation before calling this. Nothing in the signature enforces that:\n * both vocabularies are `string`, so the fence is this sentence.\n *\n * An override LAYER, not a replacement: a derivation whose id is absent from\n * `overrides` keeps whatever it declared, so clearing an override — which\n * strips the key rather than storing `undefined` — restores the declared\n * value. A key carrying `undefined` is likewise treated as no override, so\n * `undefined` never acquires a second meaning here. `null` is the value that\n * says \"draw NO aggregate for a column whose prop declares one\": the merge\n * strips the declared `aggregate` from that derivation, so `compileQuery`\n * never sees the sentinel and validates nothing new.\n *\n * An override for an id no derivation carries is ignored, never appended: this\n * function only ever rewrites the `aggregate` of derivations it was given, and\n * preserves their order, so a merged list stays positionally comparable with\n * the one it came from — which is what `derivationsEqualForPlan` needs to\n * decide plan reuse.\n *\n * TYPES DESCRIBE THE DECLARED SHAPE, NOT THE MERGED ONE. An override arrives\n * as `unknown`, so the returned list keeps the input's type: a column that\n * declared no `aggregate` but carries an override aggregates at runtime while\n * its type still says it does not, and an override of a different output type\n * is invisible to `PretableAggregatesFor`. The alternative — inferring a new\n * derivation type per override — cannot work off state grid-core stores as\n * `unknown`.\n *\n * IDENTITY: returns the INPUT ARRAY ITSELF when nothing applies, so a caller\n * memoising on identity (React) does not re-request derivations every render;\n * that covers a restated override too, since an override `Object.is`-equal to\n * the declared value changes nothing. It is NOT idempotent on the applying\n * path: two calls with equal inputs return two DISTINCT arrays whenever any\n * override actually applies. A React caller must therefore `useMemo` the merge\n * on `[derivations, overrides]` and hold the MERGED array as its\n * last-requested value, rather than calling this inline inside the effect that\n * compares against it — otherwise every render looks like a change and pays a\n * `compileQuery` before concluding no-op. That memo is sound because\n * grid-core's `columnAggregates` object identity is stable across publishes\n * that do not touch it.\n *\n * @public\n */\nexport function mergeColumnAggregateOverrides(derivations, overrides) {\n let changed = false;\n const merged = derivations.map((derivation) => {\n if (!Object.hasOwn(overrides, derivation.id))\n return derivation;\n const aggregate = overrides[derivation.id];\n if (aggregate === undefined)\n return derivation;\n const declared = derivation.aggregate;\n if (aggregate === null) {\n // The \"no aggregate\" sentinel: strip what the prop declared. A column\n // that declares none is already there — identity, not a change. That\n // covers an own `aggregate: undefined` key too: every consumer reads\n // the value, never key presence, so stripping it would churn identity\n // over a semantic no-op.\n if (declared === undefined)\n return derivation;\n changed = true;\n // Copy + delete rather than rest-destructuring: this repo's\n // no-unused-vars rule has no rest-sibling exemption.\n const stripped = { ...derivation };\n delete stripped.aggregate;\n return stripped;\n }\n if (Object.is(declared, aggregate))\n return derivation;\n changed = true;\n return { ...derivation, aggregate };\n });\n return changed ? merged : derivations;\n}\n","const MAX_REPRESENTATIVE_LEAVES = 8;\nconst DEVELOPMENT = process.env.NODE_ENV !== \"production\";\nfunction sameLeafId(left, right) {\n return left === right || (left !== left && right !== right);\n}\nfunction clonedContext(context) {\n return {\n leftToRight: new Map(context.leftToRight),\n rightToLeft: new Map(context.rightToLeft),\n };\n}\nfunction commitContext(target, source) {\n target.leftToRight = source.leftToRight;\n target.rightToLeft = source.rightToLeft;\n}\nfunction equalBytes(left, right) {\n if (left.byteLength !== right.byteLength)\n return false;\n const leftBytes = new Uint8Array(left.buffer, left.byteOffset, left.byteLength);\n const rightBytes = new Uint8Array(right.buffer, right.byteOffset, right.byteLength);\n return leftBytes.every((value, index) => value === rightBytes[index]);\n}\nfunction boxedPrimitiveValue(value) {\n switch (Object.prototype.toString.call(value)) {\n case \"[object Boolean]\":\n return Boolean.prototype.valueOf.call(value);\n case \"[object Number]\":\n return Number.prototype.valueOf.call(value);\n case \"[object String]\":\n return String.prototype.valueOf.call(value);\n case \"[object BigInt]\":\n return BigInt.prototype.valueOf.call(value);\n case \"[object Symbol]\":\n return Symbol.prototype.valueOf.call(value);\n default:\n return undefined;\n }\n}\nfunction structuredEqual(left, right, context) {\n if (Object.is(left, right))\n return true;\n if (left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\") {\n return false;\n }\n const knownRight = context.leftToRight.get(left);\n if (knownRight !== undefined)\n return knownRight === right;\n const knownLeft = context.rightToLeft.get(right);\n if (knownLeft !== undefined)\n return knownLeft === left;\n if (Object.getPrototypeOf(left) !== Object.getPrototypeOf(right))\n return false;\n const leftBoxed = boxedPrimitiveValue(left);\n const rightBoxed = boxedPrimitiveValue(right);\n if (leftBoxed !== undefined || rightBoxed !== undefined) {\n return Object.is(leftBoxed, rightBoxed);\n }\n if (left instanceof Date && right instanceof Date) {\n return Object.is(left.getTime(), right.getTime());\n }\n if (left instanceof RegExp && right instanceof RegExp) {\n return (left.source === right.source &&\n left.flags === right.flags &&\n left.lastIndex === right.lastIndex);\n }\n if (left instanceof ArrayBuffer && right instanceof ArrayBuffer) {\n return equalBytes(new Uint8Array(left), new Uint8Array(right));\n }\n if (typeof SharedArrayBuffer !== \"undefined\" &&\n left instanceof SharedArrayBuffer &&\n right instanceof SharedArrayBuffer) {\n return equalBytes(new Uint8Array(left), new Uint8Array(right));\n }\n if (ArrayBuffer.isView(left) && ArrayBuffer.isView(right)) {\n return equalBytes(left, right);\n }\n context.leftToRight.set(left, right);\n context.rightToLeft.set(right, left);\n if (left instanceof Map && right instanceof Map) {\n if (left.size !== right.size)\n return false;\n const unmatched = [...right.entries()];\n for (const [leftKey, leftValue] of left) {\n let matched = false;\n for (let index = 0; index < unmatched.length; index += 1) {\n const rightEntry = unmatched[index];\n const trial = clonedContext(context);\n if (structuredEqual(leftKey, rightEntry[0], trial) &&\n structuredEqual(leftValue, rightEntry[1], trial)) {\n commitContext(context, trial);\n unmatched.splice(index, 1);\n matched = true;\n break;\n }\n }\n if (!matched)\n return false;\n }\n return true;\n }\n if (left instanceof Set && right instanceof Set) {\n if (left.size !== right.size)\n return false;\n const unmatched = [...right.values()];\n for (const leftValue of left) {\n let matched = false;\n for (let index = 0; index < unmatched.length; index += 1) {\n const trial = clonedContext(context);\n if (structuredEqual(leftValue, unmatched[index], trial)) {\n commitContext(context, trial);\n unmatched.splice(index, 1);\n matched = true;\n break;\n }\n }\n if (!matched)\n return false;\n }\n return true;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n if (leftKeys.length !== rightKeys.length)\n return false;\n for (const key of leftKeys) {\n if (!Object.prototype.hasOwnProperty.call(right, key))\n return false;\n const leftDescriptor = Object.getOwnPropertyDescriptor(left, key);\n const rightDescriptor = Object.getOwnPropertyDescriptor(right, key);\n if (leftDescriptor === undefined || rightDescriptor === undefined)\n return false;\n if (leftDescriptor.enumerable !== rightDescriptor.enumerable ||\n leftDescriptor.configurable !== rightDescriptor.configurable) {\n return false;\n }\n const leftIsData = \"value\" in leftDescriptor;\n const rightIsData = \"value\" in rightDescriptor;\n if (leftIsData !== rightIsData)\n return false;\n if (leftIsData && rightIsData) {\n if (!structuredEqual(leftDescriptor.value, rightDescriptor.value, context)) {\n return false;\n }\n }\n else if (leftDescriptor.get !== rightDescriptor.get ||\n leftDescriptor.set !== rightDescriptor.set) {\n return false;\n }\n }\n return true;\n}\n/** Compares scalar and common structured finalized outputs by value. */\nexport function defaultAggregatorOutputEquality(left, right) {\n return structuredEqual(left, right, {\n leftToRight: new Map(),\n rightToLeft: new Map(),\n });\n}\nconst productionValidator = Object.freeze({\n observe: () => undefined,\n});\n/**\n * Creates development-only validation for the custom aggregator merge law.\n * Production replacements of `process.env.NODE_ENV` eliminate the sampling\n * branch, and the runtime fallback is a shared no-op validator.\n */\nexport function createAggregatorLawValidator(options) {\n if (!DEVELOPMENT)\n return productionValidator;\n const states = new WeakMap();\n const equals = options.equals ?? defaultAggregatorOutputEquality;\n return {\n observe(observation) {\n const aggregatorObject = observation.aggregator;\n let columns = states.get(aggregatorObject);\n if (columns === undefined) {\n columns = new Map();\n states.set(aggregatorObject, columns);\n }\n let state = columns.get(observation.columnId);\n if (state === undefined) {\n state = { samples: [], warned: false };\n columns.set(observation.columnId, state);\n }\n if (state.warned)\n return;\n const existingIndex = state.samples.findIndex((sample) => sameLeafId(sample.id, observation.leafId));\n if (existingIndex >= 0) {\n state.samples[existingIndex] = {\n id: observation.leafId,\n row: observation.row,\n value: observation.value,\n };\n }\n else {\n if (state.samples.length >= MAX_REPRESENTATIVE_LEAVES)\n return;\n state.samples.push({\n id: observation.leafId,\n row: observation.row,\n value: observation.value,\n });\n }\n if (state.samples.length < 2)\n return;\n const aggregator = observation.aggregator;\n try {\n let sequential = aggregator.init();\n const partitions = [];\n for (const sample of state.samples) {\n sequential = aggregator.accumulate(sequential, sample.value, sample.row);\n partitions.push(aggregator.accumulate(aggregator.init(), sample.value, sample.row));\n }\n let merged = partitions[0];\n for (let index = 1; index < partitions.length; index += 1) {\n merged = aggregator.merge(merged, partitions[index]);\n }\n const sequentialOutput = aggregator.finalize(sequential);\n const mergedOutput = aggregator.finalize(merged);\n if (equals(sequentialOutput, mergedOutput))\n return;\n state.warned = true;\n options.sink({\n code: \"aggregator-law-violation\",\n law: \"sequential-vs-merged-one-row-partitions\",\n columnId: observation.columnId,\n sampleSize: state.samples.length,\n sequentialOutput,\n mergedOutput,\n });\n }\n catch {\n // Development diagnostics must not add a new failure mode to updates.\n }\n },\n };\n}\n","import {\n createColumnHelper as createInternalColumnHelper,\n type PretableColumnHelper,\n} from \"@pretable-internal/row-model\";\n\n/**\n * Creates a typed column-definition helper for an ordinary row object.\n *\n * @public\n */\nexport function createColumnHelper<\n TRow extends object,\n>(): PretableColumnHelper<TRow> {\n return createInternalColumnHelper<TRow>();\n}\n","import {\n createLocalRowModel as createInternalLocalRowModel,\n type CreateLocalRowModelOptions as InternalCreateLocalRowModelOptions,\n type PretableDerivationsFor,\n type PretableExpansionDefault,\n type PretableQueryFor,\n type Prettify,\n type PretableRowId,\n type PretableRowModel,\n} from \"@pretable-internal/row-model\";\n\n/** Options for a local row model with an explicit row-ID accessor. @public */\nexport interface CreateLocalRowModelOptions<\n TColumns,\n TRowId extends PretableRowId,\n> {\n readonly rows: readonly (TColumns extends readonly [\n infer TFirstColumn,\n ...(readonly unknown[]),\n ]\n ? TFirstColumn extends {\n readonly accessor: (row: infer TRow extends object) => infer TValue;\n }\n ? [TValue] extends [unknown]\n ? TRow\n : never\n : never\n : never)[];\n readonly columns: TColumns & {\n readonly [K in keyof TColumns]: TColumns[K] extends {\n readonly accessor: (\n row: infer TColumnRow extends object,\n ) => infer TColumnValue;\n }\n ? [TColumnValue] extends [unknown]\n ? TColumns extends readonly [\n infer TFirstColumn,\n ...(readonly unknown[]),\n ]\n ? TFirstColumn extends {\n readonly accessor: (\n row: infer TFirstRow extends object,\n ) => infer TFirstValue;\n }\n ? [TFirstValue] extends [unknown]\n ? [TColumnRow] extends [TFirstRow]\n ? [TFirstRow] extends [TColumnRow]\n ? TColumns[K]\n : never\n : never\n : never\n : never\n : never\n : never\n : never;\n };\n readonly derivations?: PretableDerivationsFor<TColumns>;\n readonly query?: PretableQueryFor<TColumns>;\n readonly initialExpansion?: PretableExpansionDefault;\n readonly aggregateFilteredRows?: boolean;\n readonly getRowId: (\n row: TColumns extends readonly [infer TFirstColumn, ...(readonly unknown[])]\n ? TFirstColumn extends {\n readonly accessor: (row: infer TRow extends object) => infer TValue;\n }\n ? [TValue] extends [unknown]\n ? TRow\n : never\n : never\n : never,\n ) => TRowId;\n}\n\n/** Options for a local row model using the conventional `row.id`. @public */\nexport type CreateLocalRowModelWithDefaultIdOptions<TColumns> = (\n TColumns extends readonly [infer TFirstColumn, ...(readonly unknown[])]\n ? TFirstColumn extends {\n readonly accessor: (row: infer TRow extends object) => infer TValue;\n }\n ? [TValue] extends [unknown]\n ? TRow\n : never\n : never\n : never\n) extends { readonly id: PretableRowId }\n ? Prettify<{\n readonly rows: readonly (TColumns extends readonly [\n infer TFirstColumn,\n ...(readonly unknown[]),\n ]\n ? TFirstColumn extends {\n readonly accessor: (row: infer TRow extends object) => infer TValue;\n }\n ? [TValue] extends [unknown]\n ? TRow\n : never\n : never\n : never)[];\n readonly columns: TColumns & {\n readonly [K in keyof TColumns]: TColumns[K] extends {\n readonly accessor: (\n row: infer TColumnRow extends object,\n ) => infer TColumnValue;\n }\n ? [TColumnValue] extends [unknown]\n ? TColumns extends readonly [\n infer TFirstColumn,\n ...(readonly unknown[]),\n ]\n ? TFirstColumn extends {\n readonly accessor: (\n row: infer TFirstRow extends object,\n ) => infer TFirstValue;\n }\n ? [TFirstValue] extends [unknown]\n ? [TColumnRow] extends [TFirstRow]\n ? [TFirstRow] extends [TColumnRow]\n ? TColumns[K]\n : never\n : never\n : never\n : never\n : never\n : never\n : never;\n };\n readonly derivations?: PretableDerivationsFor<TColumns>;\n readonly query?: PretableQueryFor<TColumns>;\n readonly initialExpansion?: PretableExpansionDefault;\n readonly aggregateFilteredRows?: boolean;\n readonly getRowId?: undefined;\n }>\n : never;\n\n/**\n * Creates a local row model using the conventional `row.id` field.\n *\n * @public\n */\nexport function createLocalRowModel<\n const TColumns extends readonly [unknown, ...(readonly unknown[])],\n>(\n options: CreateLocalRowModelWithDefaultIdOptions<TColumns>,\n): PretableRowModel<\n CreateLocalRowModelWithDefaultIdOptions<TColumns>[\"rows\"][number],\n CreateLocalRowModelWithDefaultIdOptions<TColumns>[\"rows\"][number] extends {\n readonly id: infer TRowId extends PretableRowId;\n }\n ? TRowId\n : never,\n TColumns\n>;\n/**\n * Creates a local row model using an explicit string or number row ID.\n *\n * @public\n */\nexport function createLocalRowModel<\n const TColumns extends readonly [unknown, ...(readonly unknown[])],\n const TRowId extends PretableRowId,\n>(\n options: CreateLocalRowModelOptions<TColumns, TRowId>,\n): PretableRowModel<\n CreateLocalRowModelOptions<TColumns, TRowId>[\"rows\"][number],\n TRowId,\n TColumns\n>;\nexport function createLocalRowModel<\n const TColumns extends readonly unknown[],\n const TRowId extends PretableRowId,\n>(\n options:\n | CreateLocalRowModelWithDefaultIdOptions<TColumns>\n | CreateLocalRowModelOptions<TColumns, TRowId>,\n): unknown {\n return createInternalLocalRowModel(\n options as unknown as InternalCreateLocalRowModelOptions<TColumns, TRowId>,\n );\n}\n","/**\n * Options for Pretable's currency number-format presets.\n *\n * @public\n */\nexport type PretableCurrencyFormatOptions = Omit<\n Intl.NumberFormatOptions,\n \"style\" | \"currency\" | \"currencySign\"\n> & {\n currency: string;\n};\n\nfunction currencyOptions(\n options: PretableCurrencyFormatOptions,\n currencySign: \"standard\" | \"accounting\",\n): Intl.NumberFormatOptions {\n return {\n ...options,\n style: \"currency\",\n currency: options.currency,\n currencySign,\n };\n}\n\n/**\n * Native number-format presets for money and accounting presentation.\n *\n * @public\n */\nexport const numberFormats = {\n money(options: PretableCurrencyFormatOptions): Intl.NumberFormatOptions {\n return currencyOptions(options, \"standard\");\n },\n accounting(options: PretableCurrencyFormatOptions): Intl.NumberFormatOptions {\n return currencyOptions(options, \"accounting\");\n },\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,SAAgB,sBAAsB,UAAU;CAC5C,OAAO,IAAI,YAAa,WAAW,OAAQ,CAAC;AAChD;;AAEA,SAAgB,qBAAqB,MAAM,UAAU;CACjD,MAAM,QAAQ,KAAK,IAAI,KAAK,QAAS,WAAW,OAAQ,CAAC;CACzD,MAAM,OAAO,IAAI,YAAY,KAAK;CAClC,KAAK,IAAI,IAAI;CACb,OAAO;AACX;AACA,SAAgB,YAAY,MAAM,MAAM;CACpC,KAAK,SAAS,MAAM,MAAM,OAAO;AACrC;AACA,SAAgB,cAAc,MAAM,MAAM;CACtC,KAAK,SAAS,MAAM,EAAE,MAAM,OAAO;AACvC;;AAEA,SAAgB,aAAa,MAAM,MAAM;CACrC,MAAM,OAAO,KAAK,SAAS;CAC3B,OAAO,SAAS,SAAY,SAAU,UAAU,OAAO,MAAO,OAAO;AACzE;;;;AC9BA,IAAIA;AAEJ,SAAS,WAAW,iBAAiB,GAAG;CACpC,OAAO;EACH,cAAc;EACd;EACA,i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AAgB,8BAA8B,aAAa,WAAW;CAClE,IAAI,UAAU;CACd,MAAM,SAAS,YAAY,KAAK,eAAe;EAC3C,IAAI,CAAC,OAAO,OAAO,WAAW,WAAW,EAAE,GACvC,OAAO;EACX,MAAM,YAAY,UAAU,WAAW;EACvC,IAAI,cAAc,QACd,OAAO;EACX,MAAM,WAAW,WAAW;EAC5B,IAAI,cAAc,MAAM;GAMpB,IAAI,aAAa,QACb,OAAO;GACX,UAAU;GAGV,MAAM,WAAW,EAAE,GAAG,WAAW;GACjC,OAAO,SAAS;GAChB,OAAO;EACX;EACA,IAAI,OAAO,GAAG,UAAU,SAAS,GAC7B,OAAO;EACX,UAAU;EACV,OAAO;GAAE,GAAG;GAAY;EAAU;CACtC,CAAC;CACD,OAAO,UAAU,SAAS;AAC9B;;;;AC1FA,MAAM,cAAc,QAAQ,IAAI,aAAa;AAgK7C,MAAM,sBAAsB,OAAO,OAAO,EACtC,eAAe,OACnB,CAAC;;;;;;;;;ACzJD,SAAgB,qBAEgB;CAC9B,OAAOC,qBAAiC;AAC1C;;;;ACyJA,SAAgB,oBAId,SAGS;CACT,OAAOC,sBACL,OACF;AACF;;;;ACtKA,SAAS,gBACP,SACA,cAC0B;CAC1B,OAAO;EACL,GAAG;EACH,OAAO;EACP,UAAU,QAAQ;EAClB;CACF;AACF;;;;;;AAOA,MAAa,gBAAgB;CAC3B,MAAM,SAAkE;EACtE,OAAO,gBAAgB,SAAS,UAAU;CAC5C;CACA,WAAW,SAAkE;EAC3E,OAAO,gBAAgB,SAAS,YAAY;CAC9C;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["_a","nodeHeight","dataRef","nodeHeight","createColumnHelper","isRuntimeFilterGroup","readDateTimestamp","collator","fail","attachInstrumentation","iterateEntries","attachInstrumentation","createDeferredMeasureDraft","DEVELOPMENT","factory","dataRef","DEVELOPMENT","createLocalRowModel","previousSnapshot","createInternalColumnHelper","createInternalLocalRowModel"],"sources":["../../layout-core/dist/dense-membership.js","../../layout-core/dist/row-height-index.js","../../grid-core/dist/indexed-selection.js","../../grid-core/dist/indexed-focus.js","../../grid-core/dist/create-grid-ui-core.js","../../grid-core/dist/group-column.js","../src/create-grid.ts","../../row-model/dist/column-types.js","../../calendar-date/dist/calendar-date.js","../../row-model/dist/calendar-date-aggregates.js","../../row-model/dist/errors.js","../../row-model/dist/query-equality.js","../../row-model/dist/compiled-query.js","../../row-model/dist/membership-bitset.js","../../row-model/dist/persistent/transient.js","../../row-model/dist/persistent/persistent-map.js","../../row-model/dist/persistent/order-statistic-tree.js","../../row-model/dist/slot-vector.js","../../row-model/dist/ordered-row-entry.js","../../row-model/dist/persistent/aggregate-tree.js","../../row-model/dist/group-index.js","../../row-model/dist/visible-index.js","../../row-model/dist/filter-rebuild.js","../../row-model/dist/filter-membership.js","../../row-model/dist/sort-rebuild.js","../../row-model/dist/flat-cooperative-candidate.js","../../row-model/dist/cooperative-transition.js","../../row-model/dist/distinct-values.js","../../row-model/dist/change-journal.js","../../row-model/dist/row-integrity.js","../../row-model/dist/row-store.js","../../row-model/dist/slot-allocator.js","../../row-model/dist/transaction-draft.js","../../row-model/dist/create-local-row-model.js","../../row-model/dist/aggregate-overrides.js","../../row-model/dist/aggregator-law.js","../src/create-column-helper.ts","../src/create-local-row-model.ts","../src/number-formats.ts"],"sourcesContent":["/**\n * Membership bitset: one bit per dense key (row-model SLOT). Duplicated from\n * `@pretable-internal/row-model`'s `membership-bitset.ts` BY DESIGN —\n * layout-core stays dependency-free (it cannot import row-model), so this\n * ~40-line primitive is hand-copied rather than shared. Keep the two files\n * in sync by hand; if one changes shape, mirror the change in the other.\n *\n * See `docs/superpowers/specs/2026-08-24-dense-handle-amendment-i-layout-seam.md`\n * for the dense lane this backs.\n */\nexport function createDenseMembership(capacity) {\n return new Uint32Array((capacity + 31) >>> 5);\n}\n/** Clone, growing to `capacity` when it exceeds the source's words. */\nexport function cloneDenseMembership(bits, capacity) {\n const words = Math.max(bits.length, (capacity + 31) >>> 5);\n const next = new Uint32Array(words);\n next.set(bits);\n return next;\n}\nexport function setDenseBit(bits, slot) {\n bits[slot >>> 5] |= 1 << (slot & 31);\n}\nexport function clearDenseBit(bits, slot) {\n bits[slot >>> 5] &= ~(1 << (slot & 31));\n}\n/** Out-of-range slots read as false. */\nexport function testDenseBit(bits, slot) {\n const word = bits[slot >>> 5];\n return word === undefined ? false : ((word >>> (slot & 31)) & 1) === 1;\n}\n","var _a;\nimport { clearDenseBit, cloneDenseMembership, createDenseMembership, setDenseBit, testDenseBit, } from \"./dense-membership\";\nfunction createWork(entriesVisited = 0) {\n return {\n nodesCreated: 0,\n entriesVisited,\n identityLookups: 0,\n identityComparisons: 0,\n measurementEntriesScanned: 0,\n previousEntriesScanned: 0,\n sortComparisons: 0,\n reorderEntriesReused: 0,\n reorderEntriesRemeasured: 0,\n refilterEntriesReused: 0,\n refilterEntriesInserted: 0,\n refilterEntriesRetired: 0,\n };\n}\nconst DEFAULT_MAX_RETAINED_MEASUREMENTS = 100_000;\nconst TICKET_KEY_WIDTH = String(Number.MAX_SAFE_INTEGER).length;\nexport class RowHeightReplacementLifecycleError extends Error {\n code;\n constructor(code, message) {\n super(message);\n this.name = \"RowHeightReplacementLifecycleError\";\n this.code = code;\n }\n}\nfunction nodeHeight(node) {\n return node?.height ?? 0;\n}\nfunction nodeCount(node) {\n return node?.count ?? 0;\n}\nfunction nodePixels(node) {\n return node?.pixels ?? 0;\n}\nfunction sequenceNode(value, left, right, work) {\n work.nodesCreated += 1;\n return {\n value,\n left,\n right,\n height: 1 + Math.max(nodeHeight(left), nodeHeight(right)),\n count: nodeCount(left) + 1 + nodeCount(right),\n pixels: nodePixels(left) + value.height + nodePixels(right),\n };\n}\nfunction rebalanceSequence(value, left, right, work) {\n if (nodeHeight(left) > nodeHeight(right) + 1) {\n const pivot = left;\n if (nodeHeight(pivot.left) >= nodeHeight(pivot.right)) {\n return sequenceNode(pivot.value, pivot.left, sequenceNode(value, pivot.right, right, work), work);\n }\n const middle = pivot.right;\n return sequenceNode(middle.value, sequenceNode(pivot.value, pivot.left, middle.left, work), sequenceNode(value, middle.right, right, work), work);\n }\n if (nodeHeight(right) > nodeHeight(left) + 1) {\n const pivot = right;\n if (nodeHeight(pivot.right) >= nodeHeight(pivot.left)) {\n return sequenceNode(pivot.value, sequenceNode(value, left, pivot.left, work), pivot.right, work);\n }\n const middle = pivot.left;\n return sequenceNode(middle.value, sequenceNode(value, left, middle.left, work), sequenceNode(pivot.value, middle.right, pivot.right, work), work);\n }\n return sequenceNode(value, left, right, work);\n}\nfunction insertSequence(root, index, value, work) {\n if (root === null)\n return sequenceNode(value, null, null, work);\n const leftCount = nodeCount(root.left);\n if (index <= leftCount) {\n return rebalanceSequence(root.value, insertSequence(root.left, index, value, work), root.right, work);\n }\n return rebalanceSequence(root.value, root.left, insertSequence(root.right, index - leftCount - 1, value, work), work);\n}\nfunction extractSequenceMinimum(root, work) {\n if (root.left === null)\n return { root: root.right, minimum: root.value };\n const extracted = extractSequenceMinimum(root.left, work);\n return {\n minimum: extracted.minimum,\n root: rebalanceSequence(root.value, extracted.root, root.right, work),\n };\n}\nfunction removeSequence(root, index, work) {\n const leftCount = nodeCount(root.left);\n if (index < leftCount) {\n const removed = removeSequence(root.left, index, work);\n return {\n value: removed.value,\n root: rebalanceSequence(root.value, removed.root, root.right, work),\n };\n }\n if (index > leftCount) {\n const removed = removeSequence(root.right, index - leftCount - 1, work);\n return {\n value: removed.value,\n root: rebalanceSequence(root.value, root.left, removed.root, work),\n };\n }\n if (root.left === null)\n return { root: root.right, value: root.value };\n if (root.right === null)\n return { root: root.left, value: root.value };\n const extracted = extractSequenceMinimum(root.right, work);\n return {\n value: root.value,\n root: rebalanceSequence(extracted.minimum, root.left, extracted.root, work),\n };\n}\nfunction updateSequence(root, index, value, work) {\n const leftCount = nodeCount(root.left);\n if (index < leftCount) {\n return rebalanceSequence(root.value, updateSequence(root.left, index, value, work), root.right, work);\n }\n if (index > leftCount) {\n return rebalanceSequence(root.value, root.left, updateSequence(root.right, index - leftCount - 1, value, work), work);\n }\n return sequenceNode(value, root.left, root.right, work);\n}\nfunction sequenceAt(root, index) {\n let current = root;\n let rank = index;\n while (current !== null) {\n const leftCount = nodeCount(current.left);\n if (rank < leftCount)\n current = current.left;\n else if (rank > leftCount) {\n rank -= leftCount + 1;\n current = current.right;\n }\n else\n return current.value;\n }\n return undefined;\n}\n/**\n * One-pass balanced build over an already-ordered value array — the\n * synchronous counterpart of the replacement builder's `build-sequence` phase\n * (same midpoint convention, so both produce the same shape). Depth is\n * logarithmic, so the recursion is stack-safe at any realistic row count.\n */\nfunction buildBalancedSequence(values, start, end, work) {\n if (start >= end)\n return null;\n const middle = Math.floor((start + end) / 2);\n return sequenceNode(values[middle], buildBalancedSequence(values, start, middle, work), buildBalancedSequence(values, middle + 1, end, work), work);\n}\nfunction hashIdentity(identity) {\n let hash = 0x811c9dc5;\n for (let index = 0; index < identity.length; index += 1) {\n hash ^= identity.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\nfunction hashCount(root) {\n return root?.count ?? 0;\n}\n/** Total of a map's numeric values; see {@link HashLeaf}. */\nfunction hashSum(root) {\n return root?.sum ?? 0;\n}\nfunction entryWeight(value) {\n return typeof value === \"number\" ? value : 0;\n}\nfunction popCount(value) {\n let remaining = value >>> 0;\n remaining -= (remaining >>> 1) & 0x55555555;\n remaining = (remaining & 0x33333333) + ((remaining >>> 2) & 0x33333333);\n return (((remaining + (remaining >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24;\n}\nfunction hashFragment(hash, shift) {\n return (hash >>> shift) & 31;\n}\nfunction hashBit(fragment) {\n return (1 << fragment) >>> 0;\n}\nfunction hashPosition(bitmap, bit) {\n return popCount((bitmap & (bit - 1)) >>> 0);\n}\nfunction hashLeaf(hash, entry, work) {\n work.nodesCreated += 1;\n return { kind: \"leaf\", hash, entry, count: 1, sum: entryWeight(entry.value) };\n}\nfunction collisionCount(root) {\n return root?.count ?? 0;\n}\nfunction collisionSum(root) {\n return root?.sum ?? 0;\n}\nfunction collisionNode(entry, left, right, work) {\n work.nodesCreated += 1;\n return {\n entry,\n left,\n right,\n height: 1 + Math.max(nodeHeight(left), nodeHeight(right)),\n count: collisionCount(left) + 1 + collisionCount(right),\n sum: collisionSum(left) + entryWeight(entry.value) + collisionSum(right),\n };\n}\nfunction rebalanceCollision(entry, left, right, work) {\n if (nodeHeight(left) > nodeHeight(right) + 1) {\n const pivot = left;\n if (nodeHeight(pivot.left) >= nodeHeight(pivot.right)) {\n return collisionNode(pivot.entry, pivot.left, collisionNode(entry, pivot.right, right, work), work);\n }\n const middle = pivot.right;\n return collisionNode(middle.entry, collisionNode(pivot.entry, pivot.left, middle.left, work), collisionNode(entry, middle.right, right, work), work);\n }\n if (nodeHeight(right) > nodeHeight(left) + 1) {\n const pivot = right;\n if (nodeHeight(pivot.right) >= nodeHeight(pivot.left)) {\n return collisionNode(pivot.entry, collisionNode(entry, left, pivot.left, work), pivot.right, work);\n }\n const middle = pivot.left;\n return collisionNode(middle.entry, collisionNode(entry, left, middle.left, work), collisionNode(pivot.entry, middle.right, pivot.right, work), work);\n }\n return collisionNode(entry, left, right, work);\n}\nfunction compareIdentity(left, right, work) {\n work.identityComparisons += 1;\n return left < right ? -1 : left > right ? 1 : 0;\n}\nfunction collisionGet(root, key, work) {\n let current = root;\n while (current !== null) {\n const comparison = work === undefined\n ? key < current.entry.key\n ? -1\n : key > current.entry.key\n ? 1\n : 0\n : compareIdentity(key, current.entry.key, work);\n if (comparison < 0)\n current = current.left;\n else if (comparison > 0)\n current = current.right;\n else\n return current.entry.value;\n }\n return undefined;\n}\nfunction collisionSet(root, entry, work) {\n if (root === null)\n return collisionNode(entry, null, null, work);\n const comparison = compareIdentity(entry.key, root.entry.key, work);\n if (comparison < 0) {\n return rebalanceCollision(root.entry, collisionSet(root.left, entry, work), root.right, work);\n }\n if (comparison > 0) {\n return rebalanceCollision(root.entry, root.left, collisionSet(root.right, entry, work), work);\n }\n if (Object.is(root.entry.value, entry.value))\n return root;\n return collisionNode(entry, root.left, root.right, work);\n}\nfunction extractCollisionMinimum(root, work) {\n if (root.left === null)\n return { root: root.right, minimum: root.entry };\n const extracted = extractCollisionMinimum(root.left, work);\n return {\n minimum: extracted.minimum,\n root: rebalanceCollision(root.entry, extracted.root, root.right, work),\n };\n}\nfunction collisionDelete(root, key, work) {\n if (root === null)\n return null;\n const comparison = compareIdentity(key, root.entry.key, work);\n if (comparison < 0) {\n const left = collisionDelete(root.left, key, work);\n if (left === root.left)\n return root;\n return rebalanceCollision(root.entry, left, root.right, work);\n }\n if (comparison > 0) {\n const right = collisionDelete(root.right, key, work);\n if (right === root.right)\n return root;\n return rebalanceCollision(root.entry, root.left, right, work);\n }\n if (root.left === null)\n return root.right;\n if (root.right === null)\n return root.left;\n const extracted = extractCollisionMinimum(root.right, work);\n return rebalanceCollision(extracted.minimum, root.left, extracted.root, work);\n}\nfunction minimumCollisionEntry(root) {\n let current = root;\n while (current.left !== null)\n current = current.left;\n return current.entry;\n}\nfunction hashCollision(hash, root, work) {\n work.nodesCreated += 1;\n return { kind: \"collision\", hash, root, count: root.count, sum: root.sum };\n}\nfunction hashBranch(bitmap, children, work) {\n work.nodesCreated += 1;\n return {\n kind: \"branch\",\n bitmap: bitmap >>> 0,\n children,\n count: children.reduce((count, child) => count + child.count, 0),\n sum: children.reduce((sum, child) => sum + child.sum, 0),\n };\n}\nfunction mergeHashTerminals(left, right, shift, work) {\n const leftFragment = hashFragment(left.hash, shift);\n const rightFragment = hashFragment(right.hash, shift);\n if (leftFragment === rightFragment) {\n const child = mergeHashTerminals(left, right, shift + 5, work);\n return hashBranch(hashBit(leftFragment), [child], work);\n }\n const leftBit = hashBit(leftFragment);\n const rightBit = hashBit(rightFragment);\n return hashBranch((leftBit | rightBit) >>> 0, leftFragment < rightFragment ? [left, right] : [right, left], work);\n}\nfunction hashGetNode(root, key, hash, shift, work) {\n if (root === null)\n return undefined;\n if (root.kind !== \"branch\") {\n if (root.hash !== hash)\n return undefined;\n if (root.kind === \"leaf\") {\n if (work !== undefined)\n work.identityComparisons += 1;\n return root.entry.key === key ? root.entry.value : undefined;\n }\n return collisionGet(root.root, key, work);\n }\n const bit = hashBit(hashFragment(hash, shift));\n if ((root.bitmap & bit) === 0)\n return undefined;\n return hashGetNode(root.children[hashPosition(root.bitmap, bit)], key, hash, shift + 5, work);\n}\nfunction hashGet(root, key, work) {\n if (work !== undefined)\n work.identityLookups += 1;\n return hashGetNode(root, key, hashIdentity(key), 0, work);\n}\nfunction hashSetNode(root, key, value, hash, shift, work) {\n if (root === null)\n return hashLeaf(hash, { key, value }, work);\n if (root.kind !== \"branch\") {\n if (root.hash !== hash) {\n return mergeHashTerminals(root, hashLeaf(hash, { key, value }, work), shift, work);\n }\n if (root.kind === \"leaf\") {\n work.identityComparisons += 1;\n if (root.entry.key === key) {\n return Object.is(root.entry.value, value)\n ? root\n : hashLeaf(hash, { key, value }, work);\n }\n let collisionRoot = collisionSet(null, root.entry, work);\n collisionRoot = collisionSet(collisionRoot, { key, value }, work);\n return hashCollision(hash, collisionRoot, work);\n }\n const collisionRoot = collisionSet(root.root, { key, value }, work);\n return collisionRoot === root.root\n ? root\n : hashCollision(hash, collisionRoot, work);\n }\n const bit = hashBit(hashFragment(hash, shift));\n const position = hashPosition(root.bitmap, bit);\n if ((root.bitmap & bit) === 0) {\n const children = [...root.children];\n children.splice(position, 0, hashLeaf(hash, { key, value }, work));\n return hashBranch((root.bitmap | bit) >>> 0, children, work);\n }\n const child = hashSetNode(root.children[position], key, value, hash, shift + 5, work);\n if (child === root.children[position])\n return root;\n const children = [...root.children];\n children[position] = child;\n return hashBranch(root.bitmap, children, work);\n}\nfunction hashSet(root, key, value, work) {\n work.identityLookups += 1;\n return hashSetNode(root, key, value, hashIdentity(key), 0, work);\n}\nfunction hashDeleteNode(root, key, hash, shift, work) {\n if (root === null)\n return null;\n if (root.kind !== \"branch\") {\n if (root.hash !== hash)\n return root;\n if (root.kind === \"leaf\") {\n work.identityComparisons += 1;\n return root.entry.key === key ? null : root;\n }\n const collisionRoot = collisionDelete(root.root, key, work);\n if (collisionRoot === root.root)\n return root;\n if (collisionRoot === null)\n return null;\n if (collisionRoot.count === 1) {\n return hashLeaf(hash, minimumCollisionEntry(collisionRoot), work);\n }\n return hashCollision(hash, collisionRoot, work);\n }\n const bit = hashBit(hashFragment(hash, shift));\n if ((root.bitmap & bit) === 0)\n return root;\n const position = hashPosition(root.bitmap, bit);\n const child = hashDeleteNode(root.children[position], key, hash, shift + 5, work);\n if (child === root.children[position])\n return root;\n if (child === null) {\n if (root.children.length === 1)\n return null;\n const children = root.children.filter((_, childIndex) => childIndex !== position);\n if (children.length === 1 && children[0]?.kind !== \"branch\") {\n return children[0];\n }\n return hashBranch((root.bitmap & ~bit) >>> 0, children, work);\n }\n const children = [...root.children];\n children[position] = child;\n return hashBranch(root.bitmap, children, work);\n}\nfunction hashDelete(root, key, work) {\n work.identityLookups += 1;\n return hashDeleteNode(root, key, hashIdentity(key), 0, work);\n}\nfunction mapNode(key, value, left, right, work) {\n work.nodesCreated += 1;\n return {\n key,\n value,\n left,\n right,\n height: 1 + Math.max(nodeHeight(left), nodeHeight(right)),\n };\n}\nfunction rebalanceMap(key, value, left, right, work) {\n if (nodeHeight(left) > nodeHeight(right) + 1) {\n const pivot = left;\n if (nodeHeight(pivot.left) >= nodeHeight(pivot.right)) {\n return mapNode(pivot.key, pivot.value, pivot.left, mapNode(key, value, pivot.right, right, work), work);\n }\n const middle = pivot.right;\n return mapNode(middle.key, middle.value, mapNode(pivot.key, pivot.value, pivot.left, middle.left, work), mapNode(key, value, middle.right, right, work), work);\n }\n if (nodeHeight(right) > nodeHeight(left) + 1) {\n const pivot = right;\n if (nodeHeight(pivot.right) >= nodeHeight(pivot.left)) {\n return mapNode(pivot.key, pivot.value, mapNode(key, value, left, pivot.left, work), pivot.right, work);\n }\n const middle = pivot.left;\n return mapNode(middle.key, middle.value, mapNode(key, value, left, middle.left, work), mapNode(pivot.key, pivot.value, middle.right, pivot.right, work), work);\n }\n return mapNode(key, value, left, right, work);\n}\nfunction mapSet(root, key, value, work) {\n if (root === null)\n return mapNode(key, value, null, null, work);\n if (key < root.key) {\n return rebalanceMap(root.key, root.value, mapSet(root.left, key, value, work), root.right, work);\n }\n if (key > root.key) {\n return rebalanceMap(root.key, root.value, root.left, mapSet(root.right, key, value, work), work);\n }\n if (Object.is(root.value, value))\n return root;\n return mapNode(key, value, root.left, root.right, work);\n}\nfunction extractMapMinimum(root, work) {\n if (root.left === null)\n return { root: root.right, minimum: root };\n const extracted = extractMapMinimum(root.left, work);\n return {\n minimum: extracted.minimum,\n root: rebalanceMap(root.key, root.value, extracted.root, root.right, work),\n };\n}\nfunction mapDelete(root, key, work) {\n if (root === null)\n return null;\n if (key < root.key) {\n const left = mapDelete(root.left, key, work);\n if (left === root.left)\n return root;\n return rebalanceMap(root.key, root.value, left, root.right, work);\n }\n if (key > root.key) {\n const right = mapDelete(root.right, key, work);\n if (right === root.right)\n return root;\n return rebalanceMap(root.key, root.value, root.left, right, work);\n }\n if (root.left === null)\n return root.right;\n if (root.right === null)\n return root.left;\n const extracted = extractMapMinimum(root.right, work);\n return rebalanceMap(extracted.minimum.key, extracted.minimum.value, root.left, extracted.root, work);\n}\nfunction minimumMapEntry(root) {\n let current = root;\n while (current?.left !== null && current?.left !== undefined) {\n current = current.left;\n }\n return current ?? undefined;\n}\nfunction normalizeHeight(height, label) {\n if (!Number.isFinite(height) || height <= 0) {\n throw new RangeError(`${label} must be a finite number greater than zero.`);\n }\n return height;\n}\nfunction encodeStableKey(key) {\n if (typeof key === \"string\")\n return `s:${key.length}:${key}`;\n if (typeof key !== \"number\") {\n throw new TypeError(\"A row-height stable key must be a string or number.\");\n }\n if (Number.isNaN(key))\n return \"n:NaN\";\n if (key === 0)\n return \"n:0\";\n return `n:${String(key)}`;\n}\nfunction assertExistingIndex(index, count, label) {\n if (!Number.isSafeInteger(index) || index < 0 || index >= count) {\n throw new RangeError(`${label} ${index} is out of bounds.`);\n }\n}\nfunction assertInsertIndex(index, count) {\n if (!Number.isSafeInteger(index) || index < 0 || index > count) {\n throw new RangeError(`Row insertion index ${index} is out of bounds.`);\n }\n}\nfunction ticketKey(ticket) {\n return String(ticket).padStart(TICKET_KEY_WIDTH, \"0\");\n}\nfunction takeNextTicket(ticket) {\n if (!Number.isSafeInteger(ticket) ||\n ticket < 0 ||\n ticket >= Number.MAX_SAFE_INTEGER) {\n throw new RangeError(\"Removed-measurement retention ticket space is exhausted.\");\n }\n return ticket + 1;\n}\nclass PersistentRowHeightIndex {\n #defaultHeight;\n #getKey;\n #root;\n #visibleKeys;\n /**\n * INVARIANT (Amendment I §1): `#visibleSlots !== undefined` ⇔ this\n * generation is DENSE ⇔ every sequence entry carries a `denseKey` less\n * than `#denseCapacity`. A dense generation does NOT maintain\n * `#visibleKeys` (it stays `null`); a string generation never allocates\n * `#visibleSlots`. Measurements, tombstones, and retention order stay\n * string-identity-keyed in BOTH lanes — slot reuse must never touch\n * retention (the amendment's §3 trap).\n */\n #denseCapacity;\n #visibleSlots;\n #measurements;\n #tombstones;\n #tombstoneOrder;\n #nextTicket;\n #maxRetainedMeasurements;\n diagnostics;\n constructor(options) {\n this.#defaultHeight = options.defaultHeight;\n this.#getKey = options.getKey;\n this.#root = options.root;\n this.#visibleKeys = options.visibleKeys;\n this.#denseCapacity = options.denseCapacity;\n this.#visibleSlots = options.visibleSlots;\n this.#measurements = options.measurements;\n this.#tombstones = options.tombstones;\n this.#tombstoneOrder = options.tombstoneOrder;\n this.#nextTicket = options.nextTicket;\n this.#maxRetainedMeasurements = options.maxRetainedMeasurements;\n this.diagnostics = Object.freeze({\n nodesCreated: options.work.nodesCreated,\n entriesVisited: options.work.entriesVisited,\n treeDepth: nodeHeight(options.root),\n identityLookups: options.work.identityLookups,\n identityComparisons: options.work.identityComparisons,\n measurementEntriesScanned: options.work.measurementEntriesScanned,\n previousEntriesScanned: options.work.previousEntriesScanned,\n sortComparisons: options.work.sortComparisons,\n reorderEntriesReused: options.work.reorderEntriesReused,\n refilterEntriesReused: options.work.refilterEntriesReused,\n refilterEntriesInserted: options.work.refilterEntriesInserted,\n refilterEntriesRetired: options.work.refilterEntriesRetired,\n reorderEntriesRemeasured: options.work.reorderEntriesRemeasured,\n visibleMeasurementCount: hashCount(options.measurements) - hashCount(options.tombstones),\n tombstoneCount: hashCount(options.tombstones),\n measurementCacheCount: hashCount(options.measurements),\n });\n }\n get rowCount() {\n return nodeCount(this.#root);\n }\n /**\n * Derivation — what must be empty for a bulk replacement to be\n * byte-equivalent to the cooperative one. The cooperative builder consults\n * prior state in exactly three places:\n *\n * 1. The ingest's measured-height lookup reads `#measurements` — a hit makes\n * a produced entry `measured` with the cached height.\n * 2. The `scan-retained` walk reads `#tombstoneOrder` (whose entries mirror\n * `#tombstones`) to carry removed-row measurements forward.\n * 3. The `scan-visible` walk retains a prior VISIBLE entry's measurement\n * only when `value.measured` — and a visible entry is `measured` only\n * while its identity is in `#measurements` (`measure` sets both,\n * `apply`'s re-estimate clears both), so `#measurements` empty makes this\n * branch unreachable.\n * 4. Both paths also walk the prior visible sequence to let a SURVIVING\n * row's height ride (`#rideSurvivorHeight`, #516) — the one read of\n * sequence entry VALUES — and they do it identically, so it does not\n * enter this predicate.\n *\n * `#visibleKeys`, `#nextTicket`, and the sequence entries themselves are\n * otherwise never read for values — the builder rebuilds the key set and\n * sequence from the source — so a populated but never-measured index (e.g.\n * 50k rows at true mount) has NO retained state: every lookup above would\n * miss, and a bulk build over the source produces the identical index.\n * The predicate is therefore exactly \"measurements, tombstones, and\n * retention order are all empty\".\n */\n get hasRetainedState() {\n return (hashCount(this.#measurements) > 0 ||\n hashCount(this.#tombstones) > 0 ||\n this.#tombstoneOrder !== null);\n }\n getHeight(index) {\n if (!Number.isSafeInteger(index))\n return 0;\n return sequenceAt(this.#root, index)?.height ?? 0;\n }\n getOffsetForIndex(index) {\n if (Number.isNaN(index) || index <= 0 || this.#root === null)\n return 0;\n if (index === Number.POSITIVE_INFINITY || index >= this.rowCount) {\n return this.getTotalHeight();\n }\n let target = Math.floor(index);\n let current = this.#root;\n let offset = 0;\n while (current !== null) {\n const leftCount = nodeCount(current.left);\n if (target <= leftCount)\n current = current.left;\n else {\n offset += nodePixels(current.left);\n if (target === leftCount + 1)\n return offset + current.value.height;\n offset += current.value.height;\n target -= leftCount + 1;\n current = current.right;\n }\n }\n return offset;\n }\n getIndexForOffset(offset) {\n if (Number.isNaN(offset) || offset <= 0 || this.#root === null)\n return 0;\n if (offset >= this.getTotalHeight())\n return this.rowCount;\n let current = this.#root;\n let remaining = offset;\n let rank = 0;\n while (current !== null) {\n const leftPixels = nodePixels(current.left);\n if (remaining < leftPixels) {\n current = current.left;\n continue;\n }\n remaining -= leftPixels;\n const leftCount = nodeCount(current.left);\n if (remaining < current.value.height)\n return rank + leftCount;\n remaining -= current.value.height;\n rank += leftCount + 1;\n current = current.right;\n }\n return rank;\n }\n getTotalHeight() {\n return nodePixels(this.#root);\n }\n keyAt(index) {\n if (!Number.isSafeInteger(index))\n return undefined;\n return sequenceAt(this.#root, index)?.ref;\n }\n hasMeasurement(ref) {\n return hashGet(this.#measurements, this.#identity(ref)) !== undefined;\n }\n getMeasuredHeightMean() {\n const count = hashCount(this.#measurements);\n return count === 0 ? undefined : hashSum(this.#measurements) / count;\n }\n measure(index, ref, height) {\n assertExistingIndex(index, this.rowCount, \"Row measurement index\");\n const normalized = normalizeHeight(height, \"Measured row height\");\n const identity = this.#identity(ref);\n const current = sequenceAt(this.#root, index);\n this.#assertIdentity(current, identity);\n if (current.measured && current.height === normalized)\n return this;\n const work = createWork(1);\n const measurements = hashSet(this.#measurements, identity, normalized, work);\n const root = updateSequence(this.#root, index, { ...current, height: normalized, measured: true }, work);\n return this.#next(root, this.#visibleKeys, this.#denseCapacity, this.#visibleSlots, measurements, this.#tombstones, this.#tombstoneOrder, this.#nextTicket, work);\n }\n retainMeasurement(ref, height, denseKey) {\n const normalized = normalizeHeight(height, \"Measured row height\");\n const identity = this.#identity(ref);\n const work = createWork(1);\n if (this.#visibleSlots !== undefined) {\n // Dense generation: `#visibleKeys` is null, so the string-lane guard\n // below would be vacuous — visibility is answered by the slot bitset.\n if (denseKey === undefined) {\n throw new RowHeightReplacementLifecycleError(\"failed\", \"A dense row-height index requires dense-keyed operations; \" +\n \"fall back to a full replacement.\");\n }\n if (!Number.isSafeInteger(denseKey) || denseKey < 0) {\n // Mirror the insert arm: a negative or fractional key would silently\n // mis-read here (1.5's `&31` truncation reads a DIFFERENT row's bit).\n throw new RangeError(`Dense row-height key ${denseKey} must be a non-negative ` +\n \"safe integer.\");\n }\n if (testDenseBit(this.#visibleSlots, denseKey)) {\n throw new RangeError(\"Cannot retain an absent measurement for a visible row.\");\n }\n }\n else if (hashGet(this.#visibleKeys, identity, work) !== undefined) {\n throw new RangeError(\"Cannot retain an absent measurement for a visible row.\");\n }\n if (this.#maxRetainedMeasurements === 0)\n return this;\n let measurements = hashSet(this.#measurements, identity, normalized, work);\n let tombstones = this.#tombstones;\n let tombstoneOrder = this.#tombstoneOrder;\n const previousTicket = hashGet(tombstones, identity, work);\n if (previousTicket !== undefined) {\n tombstoneOrder = mapDelete(tombstoneOrder, ticketKey(previousTicket), work);\n }\n const ticket = this.#nextTicket;\n const nextTicket = takeNextTicket(ticket);\n tombstones = hashSet(tombstones, identity, ticket, work);\n tombstoneOrder = mapSet(tombstoneOrder, ticketKey(ticket), identity, work);\n while (hashCount(tombstones) > this.#maxRetainedMeasurements) {\n const oldest = minimumMapEntry(tombstoneOrder);\n if (oldest === undefined) {\n throw new Error(\"Removed-measurement retention is inconsistent.\");\n }\n tombstoneOrder = mapDelete(tombstoneOrder, oldest.key, work);\n tombstones = hashDelete(tombstones, oldest.value, work);\n measurements = hashDelete(measurements, oldest.value, work);\n }\n return this.#next(this.#root, this.#visibleKeys, this.#denseCapacity, this.#visibleSlots, measurements, tombstones, tombstoneOrder, nextTicket, work);\n }\n apply(operations) {\n if (operations.length === 0)\n return this;\n let root = this.#root;\n let visibleKeys = this.#visibleKeys;\n let denseCapacity = this.#denseCapacity;\n let visibleSlots = this.#visibleSlots;\n // The slot bitset is MUTABLE, so the persistent contract demands a clone\n // before the first membership write of this call; reference equality with\n // `this.#visibleSlots` doubles as the no-op signal below.\n let slotsShared = true;\n let measurements = this.#measurements;\n let tombstones = this.#tombstones;\n let tombstoneOrder = this.#tombstoneOrder;\n const work = createWork();\n let nextTicket = this.#nextTicket;\n for (const operation of operations) {\n work.entriesVisited += 1;\n if (visibleSlots !== undefined && operation.denseKey === undefined) {\n throw new RowHeightReplacementLifecycleError(\"failed\", \"A dense row-height index requires dense-keyed operations; \" +\n \"fall back to a full replacement.\");\n }\n if (operation.kind === \"insert\") {\n assertInsertIndex(operation.index, nodeCount(root));\n const identity = this.#identity(operation.ref);\n if (visibleSlots !== undefined) {\n const denseKey = operation.denseKey;\n if (!Number.isSafeInteger(denseKey) || denseKey < 0) {\n throw new RangeError(`Dense row-height key ${denseKey} must be a non-negative ` +\n \"safe integer.\");\n }\n if (testDenseBit(visibleSlots, denseKey)) {\n throw new Error(`Duplicate dense row-height slot ${denseKey}: ${identity}`);\n }\n }\n else if (hashGet(visibleKeys, identity, work) !== undefined) {\n throw new Error(`Duplicate stable row-height key: ${identity}`);\n }\n const estimatedHeight = this.#estimated(operation.estimatedHeight);\n const measuredHeight = hashGet(measurements, identity, work);\n const retainedTicket = hashGet(tombstones, identity, work);\n root = insertSequence(root, operation.index, {\n ref: operation.ref,\n identity,\n estimatedHeight: operation.estimatedHeight,\n height: measuredHeight ?? estimatedHeight,\n measured: measuredHeight !== undefined,\n denseKey: operation.denseKey,\n }, work);\n if (visibleSlots !== undefined) {\n const denseKey = operation.denseKey;\n const neededCapacity = Math.max(denseCapacity, denseKey + 1);\n if (slotsShared) {\n visibleSlots = cloneDenseMembership(visibleSlots, neededCapacity);\n slotsShared = false;\n }\n else if (denseKey >>> 5 >= visibleSlots.length) {\n visibleSlots = cloneDenseMembership(visibleSlots, neededCapacity);\n }\n setDenseBit(visibleSlots, denseKey);\n denseCapacity = neededCapacity;\n }\n else {\n visibleKeys = hashSet(visibleKeys, identity, true, work);\n }\n if (retainedTicket !== undefined) {\n tombstones = hashDelete(tombstones, identity, work);\n tombstoneOrder = mapDelete(tombstoneOrder, ticketKey(retainedTicket), work);\n }\n continue;\n }\n const sourceIndex = operation.kind === \"remove\" || operation.kind === \"move\"\n ? operation.previousIndex\n : operation.index;\n assertExistingIndex(sourceIndex, nodeCount(root), \"Row operation index\");\n const identity = this.#identity(operation.ref);\n const current = sequenceAt(root, sourceIndex);\n this.#assertIdentity(current, identity);\n // Dense slot-drift guard for every variant that resolves a current\n // entry (remove, move, update — insert has no current entry; its slot\n // is range-validated and duplicate-checked in its own arm instead): a\n // caller whose slot view drifted from the entry's stamped slot must\n // fail loud rather than silently clearing or riding the wrong bit.\n if (visibleSlots !== undefined &&\n operation.denseKey !== current.denseKey) {\n throw new RowHeightReplacementLifecycleError(\"failed\", `Dense slot drift: operation denseKey ${operation.denseKey} does ` +\n `not match the entry's stamped slot ${current.denseKey} for ` +\n `${identity}; fall back to a full replacement.`);\n }\n if (operation.kind === \"remove\") {\n root = removeSequence(root, sourceIndex, work).root;\n if (visibleSlots !== undefined) {\n // Clear by the ENTRY's stamped slot — the one that set the bit —\n // which the identity assertion above ties to the caller's ref.\n if (slotsShared) {\n visibleSlots = cloneDenseMembership(visibleSlots, denseCapacity);\n slotsShared = false;\n }\n clearDenseBit(visibleSlots, current.denseKey);\n }\n else {\n visibleKeys = hashDelete(visibleKeys, identity, work);\n }\n if (current.measured) {\n if (this.#maxRetainedMeasurements === 0) {\n measurements = hashDelete(measurements, identity, work);\n }\n else {\n const ticket = nextTicket;\n nextTicket = takeNextTicket(nextTicket);\n tombstones = hashSet(tombstones, identity, ticket, work);\n tombstoneOrder = mapSet(tombstoneOrder, ticketKey(ticket), identity, work);\n while (hashCount(tombstones) > this.#maxRetainedMeasurements) {\n const oldest = minimumMapEntry(tombstoneOrder);\n if (oldest === undefined) {\n throw new Error(\"Removed-measurement retention is inconsistent.\");\n }\n tombstoneOrder = mapDelete(tombstoneOrder, oldest.key, work);\n tombstones = hashDelete(tombstones, oldest.value, work);\n measurements = hashDelete(measurements, oldest.value, work);\n }\n }\n }\n }\n else if (operation.kind === \"move\") {\n assertExistingIndex(operation.index, nodeCount(root), \"Row move destination index\");\n if (operation.index === operation.previousIndex)\n continue;\n const removed = removeSequence(root, operation.previousIndex, work);\n root = insertSequence(removed.root, operation.index, removed.value, work);\n }\n else {\n const estimatedHeight = this.#estimated(operation.estimatedHeight);\n if (!current.measured &&\n current.estimatedHeight === operation.estimatedHeight) {\n continue;\n }\n measurements = hashDelete(measurements, identity, work);\n root = updateSequence(root, operation.index, {\n ...current,\n estimatedHeight: operation.estimatedHeight,\n height: estimatedHeight,\n measured: false,\n }, work);\n }\n }\n if (root === this.#root &&\n visibleKeys === this.#visibleKeys &&\n visibleSlots === this.#visibleSlots &&\n denseCapacity === this.#denseCapacity &&\n measurements === this.#measurements &&\n tombstones === this.#tombstones &&\n tombstoneOrder === this.#tombstoneOrder &&\n nextTicket === this.#nextTicket) {\n return this;\n }\n return this.#next(root, visibleKeys, denseCapacity, visibleSlots, measurements, tombstones, tombstoneOrder, nextTicket, work);\n }\n /**\n * Builds a source with NO `denseCapacity`, so on a dense generation this\n * is a deliberate LANE EXIT: the result is a string-lane generation (the\n * full-replacement path is where the lane is legally re-decided).\n */\n replace(rows) {\n const builder = this.beginReplacement({\n rowCount: rows.length,\n entryAt: (index) => rows[index],\n });\n while (!builder.done)\n builder.advance({ maxUnits: 256 });\n return builder.finish();\n }\n /**\n * Synchronous BY DESIGN, like `reorder`/`refilter`: the row set stands\n * still, only the estimator's inputs changed, so one in-order pass over\n * the existing entries plus a balanced rebuild answers it — no source, no\n * identity re-hash, no HAMT work. Measurements, tombstones, retention\n * order, and the lane (dense bitset included) are carried through\n * verbatim; only entries with an `estimatedHeight` are rewritten. See the\n * interface docblock for the semantics.\n */\n clearEstimates() {\n if (this.#root === null)\n return this;\n const work = createWork();\n const values = [];\n let changed = false;\n const stack = [];\n let cursor = this.#root;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n const value = node.value;\n work.previousEntriesScanned += 1;\n if (value.estimatedHeight === undefined) {\n values.push(value);\n }\n else {\n changed = true;\n values.push({\n ...value,\n estimatedHeight: undefined,\n // A measurement is a fact the DOM reported and survives; an\n // estimate is arithmetic over the inputs that just changed.\n height: value.measured ? value.height : this.#defaultHeight,\n });\n }\n cursor = node.right;\n }\n if (!changed)\n return this;\n const root = buildBalancedSequence(values, 0, values.length, work);\n return this.#next(root, this.#visibleKeys, this.#denseCapacity, this.#visibleSlots, this.#measurements, this.#tombstones, this.#tombstoneOrder, this.#nextTicket, work);\n }\n /**\n * Synchronous BY DESIGN: a sort-only commit reorders EXISTING rows whose\n * heights are already known, so only the ordered structure and its prefix\n * sums change — no re-measure, no re-estimate, no identity re-hash beyond\n * the per-row key encoding. Measured ~10–20ms at 50k rows versus ~215ms of\n * cooperative `beginReplacement` re-ingest (identity hash + HAMT insert +\n * frozen rowRef per row, in 8ms slices), which is the whole point of the\n * method. The caller (renderer-dom's row-layout controller) falls back to a\n * full replacement on ANY throw, so violations of the permutation contract\n * fail loud here rather than fabricating entries.\n */\n reorder(source) {\n const rowCount = source.rowCount;\n if (!Number.isSafeInteger(rowCount) || rowCount < 0) {\n throw new RangeError(\"Reorder source rowCount must be a non-negative safe integer.\");\n }\n const entryAt = source.entryAt;\n if (typeof entryAt !== \"function\") {\n throw new TypeError(\"Reorder source entryAt must be a function.\");\n }\n if (rowCount !== this.rowCount) {\n throw new RangeError(`Reorder source rowCount (${rowCount}) must equal the current row ` +\n `count (${this.rowCount}); reorder permutes the existing rows only.`);\n }\n if (rowCount === 0)\n return this;\n const boundEntryAt = entryAt.bind(source);\n if (this.#visibleSlots !== undefined) {\n // Dense generation (Amendment I): resolve the permutation by slot.\n // The string-lane body below stays INLINE and byte-identical to its\n // pre-dense form deliberately (the Task 3 pin: the string lane must be\n // provably untouched by diff alone): do not unify the lanes or hoist\n // the shared walks into helpers.\n return this.#reorderDense(boundEntryAt, rowCount);\n }\n const work = createWork();\n // One in-order pass over the current sequence: the by-identity lookup\n // table for the walk below, and the old order for no-op detection.\n const previousValues = [];\n const unconsumed = new Map();\n {\n const stack = [];\n let cursor = this.#root;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n previousValues.push(node.value);\n unconsumed.set(node.value.identity, node.value);\n work.previousEntriesScanned += 1;\n cursor = node.right;\n }\n }\n // Walk the new order, relinking each EXISTING entry verbatim. Estimates\n // and measurements ride along untouched inside the reused entry objects,\n // so the source's `estimatedHeight`s are deliberately ignored.\n const values = new Array(rowCount);\n let unchanged = true;\n for (let index = 0; index < rowCount; index += 1) {\n const row = boundEntryAt(index);\n const identity = this.#identity(row.key);\n work.entriesVisited += 1;\n work.identityLookups += 1;\n const value = unconsumed.get(identity);\n if (value === undefined) {\n throw new Error(`Reorder key does not match an existing row (missing, or ` +\n `duplicated in the new order): ${identity}`);\n }\n unconsumed.delete(identity);\n values[index] = value;\n work.reorderEntriesReused += 1;\n if (value !== previousValues[index])\n unchanged = false;\n }\n if (unchanged)\n return this;\n const root = buildBalancedSequence(values, 0, rowCount, work);\n return this.#next(root, this.#visibleKeys, this.#denseCapacity, this.#visibleSlots, this.#measurements, this.#tombstones, this.#tombstoneOrder, this.#nextTicket, work);\n }\n /**\n * Dense-lane reorder (Amendment I): the permutation resolves each source\n * row by its `denseKey` (model slot) against a slot-indexed array — ZERO\n * identity strings on the hot path; identities are computed only to name\n * a row in an error. Key validation mirrors the builder's\n * `#ingestDenseKey` cases (missing / malformed / out-of-range → lifecycle\n * error), which the controller's fallback-on-throw contract routes to a\n * full replacement that re-decides the lane. Membership is unchanged by\n * construction — reorder permutes the existing rows — so the generation\n * carries `#visibleSlots` and `#denseCapacity` forward untouched.\n *\n * TRUST BOUNDARY: a resolved row's `row.key` is trusted to match the\n * slot's stored identity and deliberately never re-verified — that\n * verification IS the per-row string cost this lane exists to delete.\n * `apply` guards slot drift instead, because its operations are k-sized.\n */\n #reorderDense(boundEntryAt, rowCount) {\n const capacity = this.#denseCapacity;\n const work = createWork();\n // One in-order pass over the current sequence: the by-slot lookup table\n // for the walk below, and the old order for no-op detection.\n const previousValues = [];\n const unconsumedBySlot = new Array(capacity);\n {\n const stack = [];\n let cursor = this.#root;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n previousValues.push(node.value);\n unconsumedBySlot[node.value.denseKey] = node.value;\n work.previousEntriesScanned += 1;\n cursor = node.right;\n }\n }\n // Walk the new order, relinking each EXISTING entry verbatim. Estimates\n // and measurements ride along untouched inside the reused entry objects,\n // so the source's `estimatedHeight`s are deliberately ignored.\n const values = new Array(rowCount);\n let unchanged = true;\n for (let index = 0; index < rowCount; index += 1) {\n const row = boundEntryAt(index);\n work.entriesVisited += 1;\n const denseKey = row.denseKey;\n if (denseKey === undefined) {\n throw new RowHeightReplacementLifecycleError(\"failed\", \"A dense row-height index requires a denseKey on every source \" +\n `row (${this.#identity(row.key)} carries none); fall back to ` +\n \"a full replacement.\");\n }\n if (!Number.isSafeInteger(denseKey) ||\n denseKey < 0 ||\n denseKey >= capacity) {\n throw new RowHeightReplacementLifecycleError(\"failed\", `Dense key ${denseKey} for row ${this.#identity(row.key)} is ` +\n `outside the dense generation's capacity ${capacity}.`);\n }\n const value = unconsumedBySlot[denseKey];\n if (value === undefined) {\n throw new Error(`Reorder slot does not match an existing row (missing, or ` +\n `duplicated in the new order): ${denseKey}`);\n }\n unconsumedBySlot[denseKey] = undefined;\n values[index] = value;\n work.reorderEntriesReused += 1;\n if (value !== previousValues[index])\n unchanged = false;\n }\n if (unchanged)\n return this;\n const root = buildBalancedSequence(values, 0, rowCount, work);\n return this.#next(root, this.#visibleKeys, this.#denseCapacity, this.#visibleSlots, this.#measurements, this.#tombstones, this.#tombstoneOrder, this.#nextTicket, work);\n }\n /**\n * Synchronous BY DESIGN (Amendment G, G3b): a filter-only commit changes\n * MEMBERSHIP while surviving rows keep their relative order and their\n * already-measured heights, so the cooperative replacement's per-row\n * re-ingest and its sliced interval — the window the blank-viewport defect\n * lived in — are pure overhead here. Measured in Node against dist:\n * a 50k→12.5k narrowing runs 15–26ms (the amendment's 20–25ms ceiling);\n * a 12.5k→50k widening runs ~57–80ms, dominated by the fresh ingest of\n * 37.5k entrants — above the cost model's 30–35ms projection but still one\n * synchronous pass with no replacement interval, versus the 45–63ms sliced\n * cooperative flush (`reingest-composition.md`). Retention semantics deliberately mirror the\n * cooperative path observable-for-observable: entrants reuse a retained\n * (tombstoned) measurement when one exists, measured leavers tombstone in\n * old-sequence ticket order (or drop outright at cap 0), unmeasured\n * leavers vanish, and cap pressure evicts oldest-first. The caller\n * (renderer-dom's row-layout controller) falls back to a full replacement\n * on ANY throw.\n */\n refilter(source) {\n const rowCount = source.rowCount;\n if (!Number.isSafeInteger(rowCount) || rowCount < 0) {\n throw new RangeError(\"Refilter source rowCount must be a non-negative safe integer.\");\n }\n const entryAt = source.entryAt;\n if (typeof entryAt !== \"function\") {\n throw new TypeError(\"Refilter source entryAt must be a function.\");\n }\n const boundEntryAt = entryAt.bind(source);\n if (this.#visibleSlots !== undefined) {\n // Dense generation (Amendment I): resolve survivors by slot.\n // The string-lane body below stays INLINE and byte-identical to its\n // pre-dense form deliberately (the Task 3 pin: the string lane must be\n // provably untouched by diff alone): do not unify the lanes or hoist\n // the shared walks into helpers.\n return this.#refilterDense(boundEntryAt, rowCount);\n }\n const work = createWork();\n // One in-order pass over the current sequence: the by-identity lookup\n // table for the walk below, and the old order for no-op detection.\n const previousValues = [];\n const unconsumed = new Map();\n {\n const stack = [];\n let cursor = this.#root;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n previousValues.push(node.value);\n unconsumed.set(node.value.identity, node.value);\n work.previousEntriesScanned += 1;\n cursor = node.right;\n }\n }\n // Walk the new order: survivors relink verbatim (their measurements and\n // estimates ride, exactly as in `reorder`), entrants ingest fresh under\n // the cooperative path's rule — measured-lookup against the FULL cache,\n // so a returning tombstoned key gets its retained measurement back and\n // sheds its tombstone.\n const values = new Array(rowCount);\n const seen = new Set();\n let visibleKeys = null;\n let measurements = this.#measurements;\n let tombstones = this.#tombstones;\n let tombstoneOrder = this.#tombstoneOrder;\n let nextTicket = this.#nextTicket;\n let unchanged = rowCount === previousValues.length;\n for (let index = 0; index < rowCount; index += 1) {\n const row = boundEntryAt(index);\n const identity = this.#identity(row.key);\n work.entriesVisited += 1;\n work.identityLookups += 1;\n if (seen.has(identity)) {\n throw new Error(`Duplicate stable row-height key: ${identity}`);\n }\n seen.add(identity);\n visibleKeys = hashSet(visibleKeys, identity, true, work);\n const existing = unconsumed.get(identity);\n if (existing !== undefined) {\n unconsumed.delete(identity);\n values[index] = existing;\n work.refilterEntriesReused += 1;\n if (existing !== previousValues[index])\n unchanged = false;\n continue;\n }\n unchanged = false;\n const estimatedHeight = this.#estimated(row.estimatedHeight);\n const measuredHeight = hashGet(measurements, identity, work);\n if (measuredHeight !== undefined) {\n work.measurementEntriesScanned += 1;\n // A tombstone can only exist where a retained measurement does, so\n // the lookup is skipped for the (common) genuinely-new entrant.\n const retainedTicket = hashGet(tombstones, identity, work);\n if (retainedTicket !== undefined) {\n tombstones = hashDelete(tombstones, identity, work);\n tombstoneOrder = mapDelete(tombstoneOrder, ticketKey(retainedTicket), work);\n }\n }\n values[index] = {\n ref: row.key,\n identity,\n estimatedHeight: row.estimatedHeight,\n height: measuredHeight ?? estimatedHeight,\n measured: measuredHeight !== undefined,\n denseKey: row.denseKey,\n };\n work.refilterEntriesInserted += 1;\n }\n // Whatever the walk left unconsumed has LEFT the visible set. The Map\n // preserves old-sequence order, so measured leavers take new tickets in\n // exactly the order the cooperative scan-visible phase would assign them.\n for (const value of unconsumed.values()) {\n unchanged = false;\n work.refilterEntriesRetired += 1;\n if (!value.measured)\n continue;\n if (this.#maxRetainedMeasurements === 0) {\n measurements = hashDelete(measurements, value.identity, work);\n continue;\n }\n const ticket = nextTicket;\n nextTicket = takeNextTicket(nextTicket);\n tombstones = hashSet(tombstones, value.identity, ticket, work);\n tombstoneOrder = mapSet(tombstoneOrder, ticketKey(ticket), value.identity, work);\n }\n while (hashCount(tombstones) > this.#maxRetainedMeasurements) {\n const oldest = minimumMapEntry(tombstoneOrder);\n if (oldest === undefined) {\n throw new Error(\"Removed-measurement retention is inconsistent.\");\n }\n tombstoneOrder = mapDelete(tombstoneOrder, oldest.key, work);\n tombstones = hashDelete(tombstones, oldest.value, work);\n measurements = hashDelete(measurements, oldest.value, work);\n }\n if (unchanged)\n return this;\n const root = buildBalancedSequence(values, 0, rowCount, work);\n return this.#next(root, visibleKeys, this.#denseCapacity, this.#visibleSlots, measurements, tombstones, tombstoneOrder, nextTicket, work);\n }\n /**\n * Dense-lane refilter (Amendment I): survivors resolve by `denseKey`\n * (model slot) against a slot-indexed array — ZERO identity strings for\n * the (dominant) survivor population. Only ENTRANTS compute an identity,\n * because measurements and tombstones stay string-identity-keyed in both\n * lanes: a slot is lifetime-bound and reused after permanent removal, so\n * slot reuse must never touch retention (the amendment's §3 trap). Key\n * validation mirrors the builder's `#ingestDenseKey` cases (missing /\n * malformed / out-of-range → lifecycle error → the controller's\n * fallback-on-throw contract), and the duplicate check shares one bitset\n * with the next generation's membership, exactly as the builder does.\n *\n * TRUST BOUNDARY: a survivor's `row.key` is trusted to match the slot's\n * stored identity and deliberately never re-verified — that verification\n * IS the per-row string cost this lane exists to delete. `apply` guards\n * slot drift instead, because its operations are k-sized.\n *\n * LEAVER ORDER IS LOAD-BEARING: measured leavers take tombstone tickets\n * in OLD-SEQUENCE order (the string lane inherits this from its Map's\n * insertion order), and ticket order is observable through cap eviction.\n * The leaver pass therefore walks `previousValues` in order and consumes\n * the slot cells — NEVER the slot array by index, whose order is\n * unrelated to the sequence.\n */\n #refilterDense(boundEntryAt, rowCount) {\n const capacity = this.#denseCapacity;\n const work = createWork();\n // One in-order pass over the current sequence: the by-slot lookup table\n // for the walk below, and the old order for no-op detection and the\n // leaver pass.\n const previousValues = [];\n const unconsumedBySlot = new Array(capacity);\n {\n const stack = [];\n let cursor = this.#root;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n previousValues.push(node.value);\n unconsumedBySlot[node.value.denseKey] = node.value;\n work.previousEntriesScanned += 1;\n cursor = node.right;\n }\n }\n // Walk the new order: survivors relink verbatim by slot (measurements\n // and estimates ride, exactly as in `reorder`), entrants ingest fresh\n // under the cooperative path's rule — measured-lookup against the FULL\n // cache BY IDENTITY, so a returning tombstoned key gets its retained\n // measurement back and sheds its tombstone. `nextVisibleSlots` doubles\n // as the duplicate check and the next generation's membership.\n const values = new Array(rowCount);\n const nextVisibleSlots = createDenseMembership(capacity);\n let measurements = this.#measurements;\n let tombstones = this.#tombstones;\n let tombstoneOrder = this.#tombstoneOrder;\n let nextTicket = this.#nextTicket;\n let unchanged = rowCount === previousValues.length;\n for (let index = 0; index < rowCount; index += 1) {\n const row = boundEntryAt(index);\n work.entriesVisited += 1;\n const denseKey = row.denseKey;\n if (denseKey === undefined) {\n throw new RowHeightReplacementLifecycleError(\"failed\", \"A dense row-height index requires a denseKey on every source \" +\n `row (${this.#identity(row.key)} carries none); fall back to ` +\n \"a full replacement.\");\n }\n if (!Number.isSafeInteger(denseKey) ||\n denseKey < 0 ||\n denseKey >= capacity) {\n throw new RowHeightReplacementLifecycleError(\"failed\", `Dense key ${denseKey} for row ${this.#identity(row.key)} is ` +\n `outside the dense generation's capacity ${capacity}.`);\n }\n if (testDenseBit(nextVisibleSlots, denseKey)) {\n throw new Error(`Duplicate dense row-height slot ${denseKey}: ` +\n this.#identity(row.key));\n }\n setDenseBit(nextVisibleSlots, denseKey);\n const existing = unconsumedBySlot[denseKey];\n if (existing !== undefined) {\n unconsumedBySlot[denseKey] = undefined;\n values[index] = existing;\n work.refilterEntriesReused += 1;\n if (existing !== previousValues[index])\n unchanged = false;\n continue;\n }\n unchanged = false;\n const identity = this.#identity(row.key);\n work.identityLookups += 1;\n const estimatedHeight = this.#estimated(row.estimatedHeight);\n const measuredHeight = hashGet(measurements, identity, work);\n if (measuredHeight !== undefined) {\n work.measurementEntriesScanned += 1;\n // A tombstone can only exist where a retained measurement does, so\n // the lookup is skipped for the (common) genuinely-new entrant.\n const retainedTicket = hashGet(tombstones, identity, work);\n if (retainedTicket !== undefined) {\n tombstones = hashDelete(tombstones, identity, work);\n tombstoneOrder = mapDelete(tombstoneOrder, ticketKey(retainedTicket), work);\n }\n }\n values[index] = {\n ref: row.key,\n identity,\n estimatedHeight: row.estimatedHeight,\n height: measuredHeight ?? estimatedHeight,\n measured: measuredHeight !== undefined,\n denseKey,\n };\n work.refilterEntriesInserted += 1;\n }\n // Whatever the walk left unconsumed has LEFT the visible set. Iterate\n // the OLD SEQUENCE (see the doc comment above — ticket order is\n // observable via cap eviction) and consume each leaver's slot cell.\n for (const value of previousValues) {\n const slot = value.denseKey;\n if (unconsumedBySlot[slot] === undefined)\n continue;\n unconsumedBySlot[slot] = undefined;\n unchanged = false;\n work.refilterEntriesRetired += 1;\n if (!value.measured)\n continue;\n if (this.#maxRetainedMeasurements === 0) {\n measurements = hashDelete(measurements, value.identity, work);\n continue;\n }\n const ticket = nextTicket;\n nextTicket = takeNextTicket(nextTicket);\n tombstones = hashSet(tombstones, value.identity, ticket, work);\n tombstoneOrder = mapSet(tombstoneOrder, ticketKey(ticket), value.identity, work);\n }\n while (hashCount(tombstones) > this.#maxRetainedMeasurements) {\n const oldest = minimumMapEntry(tombstoneOrder);\n if (oldest === undefined) {\n throw new Error(\"Removed-measurement retention is inconsistent.\");\n }\n tombstoneOrder = mapDelete(tombstoneOrder, oldest.key, work);\n tombstones = hashDelete(tombstones, oldest.value, work);\n measurements = hashDelete(measurements, oldest.value, work);\n }\n if (unchanged)\n return this;\n const root = buildBalancedSequence(values, 0, rowCount, work);\n return this.#next(root, null, this.#denseCapacity, nextVisibleSlots, measurements, tombstones, tombstoneOrder, nextTicket, work);\n }\n beginReplacement(source) {\n const rowCount = source.rowCount;\n if (!Number.isSafeInteger(rowCount) || rowCount < 0) {\n throw new RangeError(\"Replacement source rowCount must be a non-negative safe integer.\");\n }\n const entryAt = source.entryAt;\n if (typeof entryAt !== \"function\") {\n throw new TypeError(\"Replacement source entryAt must be a function.\");\n }\n const denseCapacity = source.denseCapacity;\n if (denseCapacity !== undefined &&\n (!Number.isSafeInteger(denseCapacity) || denseCapacity < 0)) {\n throw new RangeError(\"Replacement source denseCapacity must be a non-negative safe integer.\");\n }\n return new PersistentRowHeightReplacementBuilder({\n denseCapacity,\n // With no retained state every ingest lookup would miss (see\n // `hasRetainedState`'s derivation), so the builder may build everything\n // in one synchronous O(n) pass instead of cooperative phases.\n bulk: !this.hasRetainedState,\n base: {\n index: this,\n defaultHeight: this.#defaultHeight,\n getKey: this.#getKey,\n root: this.#root,\n visibleKeys: this.#visibleKeys,\n denseCapacity: this.#denseCapacity,\n measurements: this.#measurements,\n tombstones: this.#tombstones,\n tombstoneOrder: this.#tombstoneOrder,\n nextTicket: this.#nextTicket,\n maxRetainedMeasurements: this.#maxRetainedMeasurements,\n },\n rowCount,\n entryAt: entryAt.bind(source),\n });\n }\n captureAnchor(index, scrollTop) {\n if (!Number.isSafeInteger(index))\n return undefined;\n const value = sequenceAt(this.#root, index);\n if (value === undefined)\n return undefined;\n if (!Number.isFinite(scrollTop)) {\n throw new RangeError(\"Anchor scrollTop must be finite.\");\n }\n return Object.freeze({\n ref: value.ref,\n offset: scrollTop - this.getOffsetForIndex(index),\n });\n }\n restoreAnchor(anchor, index) {\n assertExistingIndex(index, this.rowCount, \"Anchor row index\");\n if (!Number.isFinite(anchor.offset)) {\n throw new RangeError(\"Anchor offset must be finite.\");\n }\n const value = sequenceAt(this.#root, index);\n if (value.identity !== this.#identity(anchor.ref)) {\n throw new Error(\"The anchor key does not match the row at the new index.\");\n }\n return this.getOffsetForIndex(index) + anchor.offset;\n }\n #identity(ref) {\n return encodeStableKey(this.#getKey(ref));\n }\n #estimated(height) {\n return height === undefined\n ? this.#defaultHeight\n : normalizeHeight(height, \"Estimated row height\");\n }\n #assertIdentity(current, identity) {\n if (current.identity !== identity) {\n throw new Error(\"The row-height operation key does not match the row at its index.\");\n }\n }\n #next(root, visibleKeys, denseCapacity, visibleSlots, measurements, tombstones, tombstoneOrder, nextTicket, work) {\n return new _a({\n defaultHeight: this.#defaultHeight,\n getKey: this.#getKey,\n root,\n visibleKeys,\n denseCapacity,\n visibleSlots,\n measurements,\n tombstones,\n tombstoneOrder,\n nextTicket,\n maxRetainedMeasurements: this.#maxRetainedMeasurements,\n work,\n });\n }\n}\n_a = PersistentRowHeightIndex;\nclass PersistentRowHeightReplacementBuilder {\n #status = \"pending\";\n #phase = \"ingest\";\n #base;\n #entryAt;\n #sourceRowCount;\n #values = [];\n /** Ingested identity → its position in `#values`. Doubles as the duplicate\n * check the ingest has always run and as the survivor lookup the scan\n * phases use to let a surviving row's height RIDE\n * (see `#rideSurvivorHeight`). */\n #identities = new Map();\n #retainedMeasurements = [];\n #retainedTraversal = [];\n #visibleTraversal = [];\n #sequenceBuildStack = [];\n #retentionBuildStack = [];\n #visibleKeys = null;\n /** Dense lane (Amendment I §1): declared by the source at `begin`. */\n #denseCapacity;\n #visibleSlots;\n #measurements;\n #tombstones = null;\n #tombstoneOrder = null;\n #root = null;\n #nextTicket;\n #ingestIndex = 0;\n #retainedStart = 0;\n #evictionIndex = 0;\n #tombstoneBuildIndex = 0;\n #completedUnits = 0;\n #lastSliceUnits = 0;\n #sliceCount = 0;\n #maxSliceUnits = 0;\n #maxSliceDuration = 0;\n #noOp = false;\n #equalVisible = true;\n #phaseUnits = {\n ingest: 0,\n \"scan-retained\": 0,\n \"scan-visible\": 0,\n evict: 0,\n \"build-tombstones\": 0,\n \"build-sequence\": 0,\n \"build-retention-order\": 0,\n done: 0,\n };\n #totalUnits;\n #bulk;\n #work = createWork();\n constructor(options) {\n this.#base = options.base;\n this.#entryAt = options.entryAt;\n this.#sourceRowCount = options.rowCount;\n this.#denseCapacity = options.denseCapacity;\n this.#visibleSlots =\n options.denseCapacity === undefined\n ? null\n : createDenseMembership(options.denseCapacity);\n this.#measurements = options.base.measurements;\n this.#nextTicket = options.base.nextTicket;\n this.#bulk = options.bulk;\n // The bulk pass is one unit of work by construction; the cooperative\n // estimate below deliberately over-counts so progress never regresses.\n this.#totalUnits = options.bulk\n ? 1\n : Math.min(Number.MAX_SAFE_INTEGER, options.rowCount * 4 +\n nodeCount(options.base.root) * 8 +\n hashCount(options.base.tombstones) * 8 +\n 8);\n }\n get done() {\n return this.#status === \"done\" || this.#status === \"finished\";\n }\n get progress() {\n return Object.freeze({\n phase: this.#phase,\n completedUnits: this.#completedUnits,\n totalUnits: Math.max(this.#totalUnits, this.#completedUnits),\n unitsThisSlice: this.#lastSliceUnits,\n sourceRowsIngested: this.#ingestIndex,\n previousRowsScanned: this.#work.previousEntriesScanned,\n done: this.done,\n });\n }\n get diagnostics() {\n const candidateRoots = [\n this.#root,\n this.#visibleKeys,\n this.#measurements,\n this.#tombstones,\n this.#tombstoneOrder,\n ].filter((root) => root !== null).length;\n return Object.freeze({\n status: this.#status,\n phase: this.#phase,\n retainedBaseRootCount: this.#base === null ? 0 : 1,\n retainedSourceCount: this.#entryAt === null ? 0 : 1,\n candidateArrayEntryCount: (this.#values?.length ?? 0) + (this.#retainedMeasurements?.length ?? 0),\n candidateStackEntryCount: (this.#retainedTraversal?.length ?? 0) +\n (this.#visibleTraversal?.length ?? 0) +\n (this.#sequenceBuildStack?.length ?? 0) +\n (this.#retentionBuildStack?.length ?? 0),\n candidateRootCount: candidateRoots,\n identitySetEntryCount: this.#identities?.size ?? 0,\n maxSliceUnits: this.#maxSliceUnits,\n maxSliceDuration: this.#maxSliceDuration,\n sliceCount: this.#sliceCount,\n completedUnits: this.#completedUnits,\n totalUnits: Math.max(this.#totalUnits, this.#completedUnits),\n phaseUnits: Object.freeze({ ...this.#phaseUnits }),\n nodesCreated: this.#work.nodesCreated,\n identityLookups: this.#work.identityLookups,\n identityComparisons: this.#work.identityComparisons,\n });\n }\n advance(options) {\n this.#assertPending();\n if (!Number.isSafeInteger(options.maxUnits) || options.maxUnits <= 0) {\n throw new RangeError(\"Replacement maxUnits must be a positive safe integer.\");\n }\n if (options.now !== undefined && typeof options.now !== \"function\") {\n throw new TypeError(\"Replacement now must be a function.\");\n }\n if (options.deadline !== undefined) {\n if (!Number.isFinite(options.deadline)) {\n throw new RangeError(\"Replacement deadline must be finite.\");\n }\n if (options.now === undefined) {\n throw new TypeError(\"Replacement now is required when deadline is supplied.\");\n }\n }\n const maxUnits = Math.min(256, Math.floor(options.maxUnits));\n let units = 0;\n let startedAt;\n let observedAt;\n try {\n if (options.now !== undefined) {\n startedAt = options.now();\n if (!Number.isFinite(startedAt)) {\n throw new RangeError(\"Replacement clock must return a finite number.\");\n }\n observedAt = startedAt;\n }\n if (this.#bulk && this.#status === \"pending\") {\n // Synchronous BY DESIGN (spec C2a): with no retained state the\n // cooperative phases degenerate — every measured-height lookup misses,\n // scan-retained walks nothing, and eviction/tombstone/retention builds\n // are all empty — so the entire replacement is one O(n) pass:\n // duplicate-checked ingest + `buildBalancedSequence`. Measured\n // ~15-20ms at 50k rows (B3's balanced build) versus ~450ms of sliced\n // cooperative re-ingest during which a mounting grid paints nothing.\n // `maxUnits`/`deadline` are deliberately not consulted: the pass is a\n // single unit, and slicing it would recreate the blank mount.\n this.#stepBulk();\n this.#phaseUnits.ingest += 1;\n units = 1;\n this.#completedUnits += 1;\n if (options.now !== undefined) {\n observedAt = options.now();\n if (!Number.isFinite(observedAt)) {\n throw new RangeError(\"Replacement clock must return a finite number.\");\n }\n }\n }\n while (units < maxUnits && this.#status === \"pending\") {\n const phase = this.#phase;\n this.#step();\n this.#phaseUnits[phase] += 1;\n units += 1;\n this.#completedUnits += 1;\n if (options.now !== undefined) {\n observedAt = options.now();\n if (!Number.isFinite(observedAt)) {\n throw new RangeError(\"Replacement clock must return a finite number.\");\n }\n if (options.deadline !== undefined &&\n observedAt >= options.deadline) {\n break;\n }\n }\n }\n }\n catch (error) {\n this.#status = \"failed\";\n this.#release();\n throw error;\n }\n this.#lastSliceUnits = units;\n this.#sliceCount += 1;\n this.#maxSliceUnits = Math.max(this.#maxSliceUnits, units);\n if (startedAt !== undefined && observedAt !== undefined) {\n this.#maxSliceDuration = Math.max(this.#maxSliceDuration, Math.max(0, observedAt - startedAt));\n }\n return this.progress;\n }\n finish() {\n if (this.#status !== \"done\") {\n if (this.#status === \"pending\") {\n throw new RowHeightReplacementLifecycleError(\"not-ready\", \"Replacement is not complete.\");\n }\n throw this.#lifecycleError(this.#status);\n }\n const base = this.#base;\n const result = this.#noOp\n ? base.index\n : new PersistentRowHeightIndex({\n defaultHeight: base.defaultHeight,\n getKey: base.getKey,\n root: this.#root,\n visibleKeys: this.#visibleKeys,\n denseCapacity: this.#denseCapacity,\n visibleSlots: this.#visibleSlots ?? undefined,\n measurements: this.#measurements,\n tombstones: this.#tombstones,\n tombstoneOrder: this.#tombstoneOrder,\n nextTicket: this.#nextTicket,\n maxRetainedMeasurements: base.maxRetainedMeasurements,\n work: this.#work,\n });\n this.#status = \"finished\";\n this.#release();\n return result;\n }\n cancel() {\n if (this.#status === \"cancelled\")\n return;\n if (this.#status === \"pending\" || this.#status === \"done\") {\n this.#status = \"cancelled\";\n this.#release();\n }\n }\n #assertPending() {\n if (this.#status === \"pending\")\n return;\n throw this.#lifecycleError(this.#status);\n }\n #lifecycleError(status) {\n const code = status === \"pending\" ? \"not-ready\" : status;\n return new RowHeightReplacementLifecycleError(code, `Replacement builder is ${status}.`);\n }\n #step() {\n switch (this.#phase) {\n case \"ingest\":\n this.#stepIngest();\n return;\n case \"scan-retained\":\n this.#stepRetainedTraversal();\n return;\n case \"scan-visible\":\n this.#stepVisibleTraversal();\n return;\n case \"evict\":\n this.#stepEviction();\n return;\n case \"build-tombstones\":\n this.#stepTombstoneBuild();\n return;\n case \"build-sequence\":\n this.#stepSequenceBuild();\n return;\n case \"build-retention-order\":\n this.#stepRetentionBuild();\n return;\n case \"done\":\n throw new RowHeightReplacementLifecycleError(\"done\", \"Replacement builder is done.\");\n }\n }\n /**\n * The dense lane's per-row ingest (Amendment I §1). With no declared\n * capacity the input's `denseKey` is stamped verbatim and stays inert\n * (string lane). Under a declared capacity every row MUST carry an\n * in-range `denseKey` — the source promised dense coverage, so a missing\n * or out-of-range key is a CALLER BUG and throws rather than silently\n * falling back (the controller only declares `denseCapacity` when the\n * snapshot guarantees slots). The visible-slot bitset is built here, in\n * place of the `#visibleKeys` HAMT the dense lane skips entirely; the\n * string-identity `#identities` duplicate check still runs first at both\n * call sites, because retention stays identity-keyed in both lanes.\n */\n #ingestDenseKey(row, identity) {\n const capacity = this.#denseCapacity;\n if (capacity === undefined)\n return row.denseKey;\n const denseKey = row.denseKey;\n if (denseKey === undefined) {\n throw new RowHeightReplacementLifecycleError(\"failed\", `Replacement source declared denseCapacity ${capacity} but a row ` +\n `(${identity}) carries no denseKey; the source broke its dense ` +\n \"promise.\");\n }\n if (!Number.isSafeInteger(denseKey) ||\n denseKey < 0 ||\n denseKey >= capacity) {\n throw new RowHeightReplacementLifecycleError(\"failed\", `Dense key ${denseKey} for row ${identity} is outside the declared ` +\n `denseCapacity ${capacity}.`);\n }\n if (testDenseBit(this.#visibleSlots, denseKey)) {\n throw new Error(`Duplicate dense row-height slot ${denseKey}: ${identity}`);\n }\n setDenseBit(this.#visibleSlots, denseKey);\n return denseKey;\n }\n /**\n * The whole replacement in one pass, valid only when the base has no\n * retained state (`hasRetainedState === false`, checked by\n * `beginReplacement`). Reproduces the cooperative ingest exactly, with the\n * measured-height lookup resolved by the gate itself: `#measurements` is\n * empty, so every lookup would miss and height starts as\n * `estimatedHeight ?? defaultHeight` with `measured: false` — after which\n * the base walk below lets a SURVIVING row's height ride, exactly as the\n * cooperative scan-visible phase does. The duplicate identity check and\n * its error are the cooperative ingest's, verbatim. Semantic no-op\n * detection is preserved too: an identical visible sequence (same\n * identities and estimates, in order) finishes to the base index.\n */\n #stepBulk() {\n const base = this.#base;\n const values = this.#values;\n const identities = this.#identities;\n const entryAt = this.#entryAt;\n while (this.#ingestIndex < this.#sourceRowCount) {\n const row = entryAt(this.#ingestIndex);\n const identity = encodeStableKey(base.getKey(row.key));\n this.#work.entriesVisited += 1;\n this.#work.identityLookups += 1;\n if (identities.has(identity)) {\n throw new Error(`Duplicate stable row-height key: ${identity}`);\n }\n identities.set(identity, values.length);\n const estimatedHeight = row.estimatedHeight === undefined\n ? base.defaultHeight\n : normalizeHeight(row.estimatedHeight, \"Estimated row height\");\n const denseKey = this.#ingestDenseKey(row, identity);\n if (this.#denseCapacity === undefined) {\n this.#visibleKeys = hashSet(this.#visibleKeys, identity, true, this.#work);\n }\n values.push({\n ref: row.key,\n identity,\n estimatedHeight: row.estimatedHeight,\n height: estimatedHeight,\n measured: false,\n denseKey,\n });\n this.#ingestIndex += 1;\n }\n this.#entryAt = null;\n // One walk over the prior visible sequence, doing the cooperative path's\n // two scan-visible jobs in the bulk pass's single unit (a true mount has\n // an empty base and pays nothing here):\n //\n // 1. The no-op predicate: every prior visible entry matches its\n // candidate's identity, estimate, AND dense stamp, and the counts and\n // lanes agree. A no-op finishes to the BASE generation, so lane\n // disagreement (or a reassigned slot) must rebuild even when the\n // identities match — otherwise a stale bitset would answer for new\n // slots.\n // 2. Survivor heights RIDE (`#rideSurvivorHeight`): the bulk gate proves\n // no MEASUREMENT exists, but a never-measured base still carries the\n // estimate-laden heights its rows are drawn at, and byte-equivalence\n // with the cooperative path requires carrying them identically.\n if (base.root !== null) {\n let equal = nodeCount(base.root) === values.length &&\n this.#denseCapacity === base.denseCapacity;\n const stack = [];\n let cursor = base.root;\n let position = 0;\n while (cursor !== null || stack.length > 0) {\n while (cursor !== null) {\n stack.push(cursor);\n cursor = cursor.left;\n }\n const node = stack.pop();\n this.#work.previousEntriesScanned += 1;\n if (equal) {\n const candidate = values[position];\n if (candidate.identity !== node.value.identity ||\n candidate.estimatedHeight !== node.value.estimatedHeight ||\n candidate.denseKey !== node.value.denseKey) {\n equal = false;\n }\n }\n this.#work.identityLookups += 1;\n const survivorPosition = identities.get(node.value.identity);\n if (survivorPosition !== undefined) {\n this.#rideSurvivorHeight(survivorPosition, node.value);\n }\n position += 1;\n cursor = node.right;\n }\n if (equal) {\n this.#noOp = true;\n this.#phase = \"done\";\n this.#status = \"done\";\n return;\n }\n }\n this.#root = buildBalancedSequence(values, 0, values.length, this.#work);\n this.#phase = \"done\";\n this.#status = \"done\";\n }\n #stepIngest() {\n const base = this.#base;\n const values = this.#values;\n const identities = this.#identities;\n if (this.#ingestIndex < this.#sourceRowCount) {\n const row = this.#entryAt(this.#ingestIndex);\n const identity = encodeStableKey(base.getKey(row.key));\n this.#work.entriesVisited += 1;\n this.#work.identityLookups += 1;\n if (identities.has(identity)) {\n throw new Error(`Duplicate stable row-height key: ${identity}`);\n }\n identities.set(identity, values.length);\n const estimatedHeight = row.estimatedHeight === undefined\n ? base.defaultHeight\n : normalizeHeight(row.estimatedHeight, \"Estimated row height\");\n const measuredHeight = hashGet(this.#measurements, identity, this.#work);\n if (measuredHeight !== undefined) {\n this.#work.measurementEntriesScanned += 1;\n }\n const denseKey = this.#ingestDenseKey(row, identity);\n if (this.#denseCapacity === undefined) {\n this.#visibleKeys = hashSet(this.#visibleKeys, identity, true, this.#work);\n }\n values.push({\n ref: row.key,\n identity,\n estimatedHeight: row.estimatedHeight,\n height: measuredHeight ?? estimatedHeight,\n measured: measuredHeight !== undefined,\n denseKey,\n });\n this.#ingestIndex += 1;\n return;\n }\n this.#entryAt = null;\n this.#phase = \"scan-retained\";\n if (base.tombstoneOrder !== null) {\n this.#retainedTraversal.push({\n node: base.tombstoneOrder,\n state: 0,\n });\n }\n }\n #stepRetainedTraversal() {\n const stack = this.#retainedTraversal;\n const frame = stack.at(-1);\n if (frame === undefined) {\n this.#phase = \"scan-visible\";\n const root = this.#base.root;\n if (root !== null)\n this.#visibleTraversal.push({ node: root, state: 0 });\n return;\n }\n if (frame.state === 0) {\n frame.state = 1;\n if (frame.node.left !== null) {\n stack.push({ node: frame.node.left, state: 0 });\n }\n return;\n }\n if (frame.state === 1) {\n frame.state = 2;\n this.#work.identityLookups += 1;\n if (!this.#identities.has(frame.node.value)) {\n this.#retainedMeasurements.push({\n identity: frame.node.value,\n ticket: Number(frame.node.key),\n });\n }\n return;\n }\n stack.pop();\n if (frame.node.right !== null) {\n stack.push({ node: frame.node.right, state: 0 });\n }\n }\n #stepVisibleTraversal() {\n const stack = this.#visibleTraversal;\n const frame = stack.at(-1);\n if (frame === undefined) {\n if (this.#equalVisible &&\n this.#work.previousEntriesScanned === this.#values.length &&\n this.#denseCapacity === this.#base.denseCapacity) {\n this.#noOp = true;\n this.#phase = \"done\";\n this.#status = \"done\";\n return;\n }\n this.#phase = \"evict\";\n this.#retainedStart = Math.max(0, this.#retainedMeasurements.length -\n this.#base.maxRetainedMeasurements);\n return;\n }\n if (frame.state === 0) {\n frame.state = 1;\n if (frame.node.left !== null) {\n stack.push({ node: frame.node.left, state: 0 });\n }\n return;\n }\n if (frame.state === 1) {\n frame.state = 2;\n const value = frame.node.value;\n const candidate = this.#values[this.#work.previousEntriesScanned];\n if (candidate === undefined ||\n candidate.identity !== value.identity ||\n candidate.estimatedHeight !== value.estimatedHeight ||\n candidate.denseKey !== value.denseKey) {\n this.#equalVisible = false;\n }\n this.#work.previousEntriesScanned += 1;\n this.#work.identityLookups += 1;\n const survivorPosition = this.#identities.get(value.identity);\n if (value.measured) {\n if (survivorPosition === undefined) {\n if (this.#base.maxRetainedMeasurements === 0) {\n this.#measurements = hashDelete(this.#measurements, value.identity, this.#work);\n }\n else {\n const ticket = this.#nextTicket;\n this.#nextTicket = takeNextTicket(this.#nextTicket);\n this.#retainedMeasurements.push({\n identity: value.identity,\n ticket,\n });\n }\n }\n }\n else if (survivorPosition !== undefined) {\n this.#rideSurvivorHeight(survivorPosition, value);\n }\n return;\n }\n stack.pop();\n if (frame.node.right !== null) {\n stack.push({ node: frame.node.right, state: 0 });\n }\n }\n /**\n * A SURVIVING row's height rides through the replacement (#516): the base\n * entry's height — measured or estimated — is what the row is drawn at\n * right now, and re-ingesting the same identity at the default (or at a\n * fresh estimate) moves every row top below it while the scroller's own\n * offset stays put, sliding the visible window down the dataset. The same\n * principle `reorder`/`refilter` already state for their survivors\n * (\"estimates ride\") applies to a full replacement's survivors.\n *\n * Measured candidates are skipped — the measurement lookup already gave\n * them the exact height — and so are measured base entries (their height\n * reached the candidate through `#measurements`; a candidate that missed\n * that lookup while its base entry is measured cannot occur, because\n * `measured` is set if and only if the identity is in `#measurements`).\n */\n #rideSurvivorHeight(position, value) {\n if (value.measured)\n return;\n const survivor = this.#values[position];\n if (survivor.measured || survivor.height === value.height)\n return;\n this.#values[position] = { ...survivor, height: value.height };\n }\n #stepEviction() {\n if (this.#evictionIndex < this.#retainedStart) {\n const evicted = this.#retainedMeasurements[this.#evictionIndex];\n this.#measurements = hashDelete(this.#measurements, evicted.identity, this.#work);\n this.#evictionIndex += 1;\n return;\n }\n this.#phase = \"build-tombstones\";\n this.#tombstoneBuildIndex = this.#retainedStart;\n }\n #stepTombstoneBuild() {\n const retained = this.#retainedMeasurements;\n if (this.#tombstoneBuildIndex < retained.length) {\n const value = retained[this.#tombstoneBuildIndex];\n this.#tombstones = hashSet(this.#tombstones, value.identity, value.ticket, this.#work);\n this.#tombstoneBuildIndex += 1;\n return;\n }\n this.#phase = \"build-sequence\";\n if (this.#values.length > 0) {\n this.#sequenceBuildStack.push(this.#newSequenceBuildFrame(0, this.#values.length));\n }\n }\n #stepSequenceBuild() {\n const stack = this.#sequenceBuildStack;\n const frame = stack.at(-1);\n if (frame === undefined) {\n this.#phase = \"build-retention-order\";\n if (this.#retainedStart < this.#retainedMeasurements.length) {\n this.#retentionBuildStack.push(this.#newRetentionBuildFrame(this.#retainedStart, this.#retainedMeasurements.length));\n }\n return;\n }\n if (frame.state === 0) {\n frame.state = 1;\n if (frame.start < frame.middle) {\n stack.push(this.#newSequenceBuildFrame(frame.start, frame.middle));\n }\n return;\n }\n if (frame.state === 1) {\n frame.state = 2;\n if (frame.middle + 1 < frame.end) {\n stack.push(this.#newSequenceBuildFrame(frame.middle + 1, frame.end));\n }\n return;\n }\n const node = sequenceNode(this.#values[frame.middle], frame.left, frame.right, this.#work);\n stack.pop();\n const parent = stack.at(-1);\n if (parent === undefined)\n this.#root = node;\n else if (parent.state === 1)\n parent.left = node;\n else\n parent.right = node;\n }\n #stepRetentionBuild() {\n const stack = this.#retentionBuildStack;\n const frame = stack.at(-1);\n if (frame === undefined) {\n this.#phase = \"done\";\n this.#status = \"done\";\n return;\n }\n if (frame.state === 0) {\n frame.state = 1;\n if (frame.start < frame.middle) {\n stack.push(this.#newRetentionBuildFrame(frame.start, frame.middle));\n }\n return;\n }\n if (frame.state === 1) {\n frame.state = 2;\n if (frame.middle + 1 < frame.end) {\n stack.push(this.#newRetentionBuildFrame(frame.middle + 1, frame.end));\n }\n return;\n }\n const retained = this.#retainedMeasurements[frame.middle];\n const node = mapNode(ticketKey(retained.ticket), retained.identity, frame.left, frame.right, this.#work);\n stack.pop();\n const parent = stack.at(-1);\n if (parent === undefined)\n this.#tombstoneOrder = node;\n else if (parent.state === 1)\n parent.left = node;\n else\n parent.right = node;\n }\n #newSequenceBuildFrame(start, end) {\n return {\n start,\n end,\n middle: Math.floor((start + end) / 2),\n state: 0,\n left: null,\n right: null,\n };\n }\n #newRetentionBuildFrame(start, end) {\n return {\n start,\n end,\n middle: Math.floor((start + end) / 2),\n state: 0,\n left: null,\n right: null,\n };\n }\n #release() {\n this.#base = null;\n this.#entryAt = null;\n this.#values = null;\n this.#identities = null;\n this.#retainedMeasurements = null;\n this.#retainedTraversal = null;\n this.#visibleTraversal = null;\n this.#sequenceBuildStack = null;\n this.#retentionBuildStack = null;\n this.#visibleKeys = null;\n this.#visibleSlots = null;\n this.#measurements = null;\n this.#tombstones = null;\n this.#tombstoneOrder = null;\n this.#root = null;\n }\n}\nexport function createRowHeightIndex(options) {\n const defaultHeight = normalizeHeight(options.defaultHeight, \"Default row height\");\n const maxRetainedMeasurements = options.maxRetainedMeasurements ?? DEFAULT_MAX_RETAINED_MEASUREMENTS;\n if (!Number.isSafeInteger(maxRetainedMeasurements) ||\n maxRetainedMeasurements < 0) {\n throw new RangeError(\"maxRetainedMeasurements must be a non-negative safe integer.\");\n }\n const empty = new PersistentRowHeightIndex({\n defaultHeight,\n getKey: options.getKey,\n root: null,\n visibleKeys: null,\n denseCapacity: undefined,\n visibleSlots: undefined,\n measurements: null,\n tombstones: null,\n tombstoneOrder: null,\n nextTicket: 0,\n maxRetainedMeasurements,\n work: createWork(),\n });\n return options.rows === undefined || options.rows.length === 0\n ? empty\n : empty.replace(options.rows);\n}\n/** Direct test seam; intentionally not exported from the layout-core barrel. */\nexport function getRowHeightIndexDiagnosticsForTesting(index) {\n if (!(index instanceof PersistentRowHeightIndex)) {\n throw new TypeError(\"Diagnostics require a persistent row-height index.\");\n }\n return index.diagnostics;\n}\n/** Direct test seam; intentionally not exported from the layout-core barrel. */\nexport function getRowHeightReplacementBuilderDiagnosticsForTesting(builder) {\n if (!(builder instanceof PersistentRowHeightReplacementBuilder)) {\n throw new TypeError(\"Diagnostics require a persistent row-height replacement builder.\");\n }\n return builder.diagnostics;\n}\n","function dataRef(rowId) {\n return { kind: \"data\", rowId };\n}\nclass ImmutableSet {\n #values;\n constructor(values) {\n this.#values = new Set(values);\n }\n get size() {\n return this.#values.size;\n }\n has(value) {\n return this.#values.has(value);\n }\n forEach(callbackfn, thisArg) {\n for (const value of this.#values) {\n callbackfn.call(thisArg, value, value, this);\n }\n }\n entries() {\n return this.#values.entries();\n }\n keys() {\n return this.#values.keys();\n }\n values() {\n return this.#values.values();\n }\n [Symbol.iterator]() {\n return this.#values[Symbol.iterator]();\n }\n get [Symbol.toStringTag]() {\n return \"ImmutableSet\";\n }\n}\n/** @internal Clones mutable caller input behind a read-only collection surface. */\nexport function toImmutableIndexedSet(values) {\n return Object.freeze(new ImmutableSet(values));\n}\nfunction isVisibleData(snapshot, rowId) {\n return snapshot.indexOf(dataRef(rowId)) >= 0;\n}\nexport function createEmptyIndexedSelection() {\n const rows = attachRowSelectionProgram(Object.freeze({\n kind: \"explicit\",\n rowIds: toImmutableIndexedSet(),\n }), Object.freeze({\n baseSelected: false,\n sequence: 0,\n points: null,\n layers: Object.freeze([]),\n }));\n return Object.freeze({\n rows,\n ranges: Object.freeze([]),\n anchor: null,\n });\n}\nexport function selectAllVisibleRows(selection, snapshot) {\n if (snapshot.visibleDataRowCount === 0)\n return selection;\n if (selection.rows.kind === \"all\" &&\n (selection.rows.excludedRanges?.size ?? 0) === 0 &&\n selection.ranges.length === 0 &&\n selection.anchor === null)\n return selection;\n const program = Object.freeze({\n baseSelected: true,\n sequence: 0,\n points: null,\n layers: Object.freeze([]),\n projection: Object.freeze({\n snapshot: snapshot,\n runs: singletonRun(true, snapshot.visibleDataRowCount),\n }),\n });\n const rows = attachRowSelectionProgram(Object.freeze({ kind: \"all\" }), program);\n return Object.freeze({\n ...selection,\n rows,\n ranges: Object.freeze([]),\n anchor: null,\n });\n}\nexport function toggleIndexedRowSelection(selection, rowId, snapshot) {\n if (!isVisibleData(snapshot, rowId))\n return selection;\n const program = rowSelectionProgram(selection, snapshot);\n const selected = semanticRowSelected(program, rowId);\n const sequence = program.sequence + 1;\n const projection = projectionFor(program, snapshot);\n const rank = snapshot.dataIndexOf(dataRef(rowId));\n const nextProgram = Object.freeze({\n ...program,\n sequence,\n points: setPointRule(program.points, {\n rowId,\n sequence,\n selected: !selected,\n }),\n projection: Object.freeze({\n snapshot: snapshot,\n runs: assignRunRange(projection.runs, rank, rank + 1, !selected),\n }),\n });\n if (selection.rows.kind === \"explicit\") {\n const rowIds = new Set(selection.rows.rowIds);\n const rangeIndex = currentRangeIndex(selection.rows.ranges, snapshot);\n let excludedRanges = currentExclusionIndex(selection.rows.excludedRanges, snapshot);\n const point = resolvedRowRange({ startRowId: rowId, endRowId: rowId }, snapshot);\n const selectedByRange = rangeTreeContains(rangeIndex.root, point.lo);\n if (selected) {\n rowIds.delete(rowId);\n if (selectedByRange)\n excludedRanges = insertExcludedPoint(excludedRanges, point);\n else\n excludedRanges = removeExcludedSpan(excludedRanges, point);\n }\n else {\n excludedRanges = removeExcludedSpan(excludedRanges, point);\n rowIds.add(rowId);\n }\n const rows = attachRowSelectionProgram(Object.freeze({\n kind: \"explicit\",\n rowIds: toImmutableIndexedSet(rowIds),\n ...(rangeIndex.size === 0 ? {} : { ranges: rangeIndex }),\n ...(excludedRanges.size === 0 ? {} : { excludedRanges }),\n }), nextProgram);\n return Object.freeze({\n ...selection,\n rows,\n });\n }\n let excludedRanges = currentExclusionIndex(selection.rows.excludedRanges, snapshot);\n const point = resolvedRowRange({ startRowId: rowId, endRowId: rowId }, snapshot);\n excludedRanges = rangeTreeContains(excludedRanges.root, point.lo)\n ? removeExcludedSpan(excludedRanges, point)\n : insertExcludedPoint(excludedRanges, point);\n const rows = attachRowSelectionProgram(Object.freeze({\n kind: \"all\",\n ...(excludedRanges.size === 0 ? {} : { excludedRanges }),\n }), nextProgram);\n return Object.freeze({\n ...selection,\n rows,\n });\n}\nfunction nodeHeight(node) {\n return node?.height ?? 0;\n}\nfunction makeRangeNode(range, left = null, right = null) {\n return Object.freeze({\n ...range,\n left,\n right,\n height: Math.max(nodeHeight(left), nodeHeight(right)) + 1,\n maxHi: Math.max(range.hi, left?.maxHi ?? -1, right?.maxHi ?? -1),\n selectedCount: range.hi -\n range.lo +\n 1 +\n (left?.selectedCount ?? 0) +\n (right?.selectedCount ?? 0),\n size: 1 + (left?.size ?? 0) + (right?.size ?? 0),\n });\n}\nfunction balanceRangeNode(node) {\n const balance = nodeHeight(node.left) - nodeHeight(node.right);\n if (balance > 1 && node.left !== null) {\n let left = node.left;\n if (nodeHeight(left.left) < nodeHeight(left.right) && left.right !== null) {\n const pivot = left.right;\n left = makeRangeNode(pivot, makeRangeNode(left, left.left, pivot.left), pivot.right);\n }\n return makeRangeNode(left, left.left, makeRangeNode(node, left.right, node.right));\n }\n if (balance < -1 && node.right !== null) {\n let right = node.right;\n if (nodeHeight(right.right) < nodeHeight(right.left) &&\n right.left !== null) {\n const pivot = right.left;\n right = makeRangeNode(pivot, pivot.left, makeRangeNode(right, pivot.right, right.right));\n }\n return makeRangeNode(right, makeRangeNode(node, node.left, right.left), right.right);\n }\n return node;\n}\nfunction insertRangeNode(root, range) {\n if (root === null)\n return makeRangeNode(range);\n return range.lo < root.lo\n ? balanceRangeNode(makeRangeNode(root, insertRangeNode(root.left, range), root.right))\n : balanceRangeNode(makeRangeNode(root, root.left, insertRangeNode(root.right, range)));\n}\nfunction minimumRangeNode(root) {\n let current = root;\n while (current.left !== null)\n current = current.left;\n return current;\n}\nfunction removeRangeNode(root, lo) {\n if (root === null)\n return null;\n if (lo < root.lo)\n return balanceRangeNode(makeRangeNode(root, removeRangeNode(root.left, lo), root.right));\n if (lo > root.lo)\n return balanceRangeNode(makeRangeNode(root, root.left, removeRangeNode(root.right, lo)));\n if (root.left === null)\n return root.right;\n if (root.right === null)\n return root.left;\n const successor = minimumRangeNode(root.right);\n return balanceRangeNode(makeRangeNode(successor, root.left, removeRangeNode(root.right, successor.lo)));\n}\nfunction splitRangeTree(root, lo) {\n if (root === null)\n return [null, null];\n if (root.lo < lo) {\n const [leftOfSplit, rightOfSplit] = splitRangeTree(root.right, lo);\n return [\n balanceRangeNode(makeRangeNode(root, root.left, leftOfSplit)),\n rightOfSplit,\n ];\n }\n const [leftOfSplit, rightOfSplit] = splitRangeTree(root.left, lo);\n return [\n leftOfSplit,\n balanceRangeNode(makeRangeNode(root, rightOfSplit, root.right)),\n ];\n}\nfunction concatenateRangeTrees(left, right) {\n if (left === null)\n return right;\n if (right === null)\n return left;\n if (nodeHeight(left) > nodeHeight(right) + 1)\n return balanceRangeNode(makeRangeNode(left, left.left, concatenateRangeTrees(left.right, right)));\n if (nodeHeight(right) > nodeHeight(left) + 1)\n return balanceRangeNode(makeRangeNode(right, concatenateRangeTrees(left, right.left), right.right));\n const successor = minimumRangeNode(right);\n return balanceRangeNode(makeRangeNode(successor, left, removeRangeNode(right, successor.lo)));\n}\nfunction findOverlappingRange(root, lo, hi) {\n if (root === null)\n return undefined;\n if (root.left !== null && root.left.maxHi >= lo - 1) {\n const left = findOverlappingRange(root.left, lo, hi);\n if (left !== undefined)\n return left;\n }\n if (root.lo <= hi + 1 && root.hi >= lo - 1)\n return root;\n return root.lo > hi + 1\n ? undefined\n : findOverlappingRange(root.right, lo, hi);\n}\nfunction findIntersectingRange(root, lo, hi) {\n if (root === null)\n return undefined;\n if (root.left !== null && root.left.maxHi >= lo) {\n const left = findIntersectingRange(root.left, lo, hi);\n if (left !== undefined)\n return left;\n }\n if (root.lo <= hi && root.hi >= lo)\n return root;\n return root.lo > hi ? undefined : findIntersectingRange(root.right, lo, hi);\n}\nfunction rangeTreeContains(root, rank) {\n let current = root;\n while (current !== null) {\n if (rank < current.lo)\n current = current.left;\n else if (rank > current.hi)\n current = current.right;\n else\n return true;\n }\n return false;\n}\nclass IndexedRowRangeIndex {\n revision;\n root;\n size;\n constructor(revision, root) {\n this.revision = revision;\n this.root = root;\n this.size = root?.size ?? 0;\n Object.freeze(this);\n }\n *[Symbol.iterator]() {\n const stack = [];\n let current = this.root;\n while (current !== null || stack.length > 0) {\n while (current !== null) {\n stack.push(current);\n current = current.left;\n }\n const next = stack.pop();\n yield Object.freeze({ startRowId: next.loId, endRowId: next.hiId });\n current = next.right;\n }\n }\n}\nfunction compareRowIds(left, right) {\n if (sameRowId(left, right))\n return 0;\n if (typeof left !== typeof right)\n return typeof left === \"number\" ? -1 : 1;\n if (typeof left === \"number\" && typeof right === \"number\") {\n if (Number.isNaN(left))\n return 1;\n if (Number.isNaN(right))\n return -1;\n return left < right ? -1 : 1;\n }\n return left < right ? -1 : 1;\n}\nfunction pointHeight(node) {\n return node?.height ?? 0;\n}\nfunction makePointNode(rule, left = null, right = null) {\n return Object.freeze({\n ...rule,\n left,\n right,\n height: Math.max(pointHeight(left), pointHeight(right)) + 1,\n });\n}\nfunction balancePointNode(node) {\n const balance = pointHeight(node.left) - pointHeight(node.right);\n if (balance > 1 && node.left !== null) {\n let left = node.left;\n if (pointHeight(left.left) < pointHeight(left.right) &&\n left.right !== null) {\n const pivot = left.right;\n left = makePointNode(pivot, makePointNode(left, left.left, pivot.left), pivot.right);\n }\n return makePointNode(left, left.left, makePointNode(node, left.right, node.right));\n }\n if (balance < -1 && node.right !== null) {\n let right = node.right;\n if (pointHeight(right.right) < pointHeight(right.left) &&\n right.left !== null) {\n const pivot = right.left;\n right = makePointNode(pivot, pivot.left, makePointNode(right, pivot.right, right.right));\n }\n return makePointNode(right, makePointNode(node, node.left, right.left), right.right);\n }\n return node;\n}\nfunction setPointRule(root, rule) {\n if (root === null)\n return makePointNode(rule);\n const comparison = compareRowIds(rule.rowId, root.rowId);\n if (comparison === 0)\n return makePointNode(rule, root.left, root.right);\n return comparison < 0\n ? balancePointNode(makePointNode(root, setPointRule(root.left, rule), root.right))\n : balancePointNode(makePointNode(root, root.left, setPointRule(root.right, rule)));\n}\nfunction getPointRule(root, rowId) {\n let current = root;\n while (current !== null) {\n const comparison = compareRowIds(rowId, current.rowId);\n if (comparison === 0)\n return current;\n current = comparison < 0 ? current.left : current.right;\n }\n return undefined;\n}\nfunction ruleHeight(node) {\n return node?.height ?? 0;\n}\nfunction makeRuleNode(rule, left = null, right = null) {\n return Object.freeze({\n lo: rule.lo,\n hi: rule.hi,\n sequence: rule.sequence,\n left,\n right,\n height: Math.max(ruleHeight(left), ruleHeight(right)) + 1,\n maxHi: Math.max(rule.hi, left?.maxHi ?? -1, right?.maxHi ?? -1),\n maxSequence: Math.max(rule.sequence, left?.maxSequence ?? -1, right?.maxSequence ?? -1),\n });\n}\nfunction balanceRuleNode(node) {\n const balance = ruleHeight(node.left) - ruleHeight(node.right);\n if (balance > 1 && node.left !== null) {\n let left = node.left;\n if (ruleHeight(left.left) < ruleHeight(left.right) && left.right !== null) {\n const pivot = left.right;\n left = makeRuleNode(pivot, makeRuleNode(left, left.left, pivot.left), pivot.right);\n }\n return makeRuleNode(left, left.left, makeRuleNode(node, left.right, node.right));\n }\n if (balance < -1 && node.right !== null) {\n let right = node.right;\n if (ruleHeight(right.right) < ruleHeight(right.left) &&\n right.left !== null) {\n const pivot = right.left;\n right = makeRuleNode(pivot, pivot.left, makeRuleNode(right, pivot.right, right.right));\n }\n return makeRuleNode(right, makeRuleNode(node, node.left, right.left), right.right);\n }\n return node;\n}\nfunction insertRuleNode(root, rule) {\n if (root === null)\n return makeRuleNode(rule);\n return rule.lo < root.lo\n ? balanceRuleNode(makeRuleNode(root, insertRuleNode(root.left, rule), root.right))\n : balanceRuleNode(makeRuleNode(root, root.left, insertRuleNode(root.right, rule)));\n}\nfunction findIntersectingRule(root, lo, hi) {\n if (root === null)\n return undefined;\n if (root.left !== null && root.left.maxHi >= lo) {\n const left = findIntersectingRule(root.left, lo, hi);\n if (left !== undefined)\n return left;\n }\n if (root.lo <= hi && root.hi >= lo)\n return root;\n return root.lo > hi ? undefined : findIntersectingRule(root.right, lo, hi);\n}\nfunction minimumRuleNode(root) {\n let current = root;\n while (current.left !== null)\n current = current.left;\n return current;\n}\nfunction removeRuleNode(root, lo) {\n if (root === null)\n return null;\n if (lo < root.lo)\n return balanceRuleNode(makeRuleNode(root, removeRuleNode(root.left, lo), root.right));\n if (lo > root.lo)\n return balanceRuleNode(makeRuleNode(root, root.left, removeRuleNode(root.right, lo)));\n if (root.left === null)\n return root.right;\n if (root.right === null)\n return root.left;\n const successor = minimumRuleNode(root.right);\n return balanceRuleNode(makeRuleNode(successor, root.left, removeRuleNode(root.right, successor.lo)));\n}\nfunction concatenateRuleTrees(left, right) {\n if (left === null)\n return right;\n if (right === null)\n return left;\n if (ruleHeight(left) > ruleHeight(right) + 1)\n return balanceRuleNode(makeRuleNode(left, left.left, concatenateRuleTrees(left.right, right)));\n if (ruleHeight(right) > ruleHeight(left) + 1)\n return balanceRuleNode(makeRuleNode(right, concatenateRuleTrees(left, right.left), right.right));\n const successor = minimumRuleNode(right);\n return balanceRuleNode(makeRuleNode(successor, left, removeRuleNode(right, successor.lo)));\n}\nfunction splitRuleTree(root, rank) {\n if (root === null)\n return [null, null];\n if (rank <= root.lo) {\n const [left, right] = splitRuleTree(root.left, rank);\n return [\n left,\n concatenateRuleTrees(right, makeRuleNode(root, null, root.right)),\n ];\n }\n if (rank > root.hi) {\n const [left, right] = splitRuleTree(root.right, rank);\n return [\n concatenateRuleTrees(makeRuleNode(root, root.left, null), left),\n right,\n ];\n }\n return [\n concatenateRuleTrees(root.left, makeRuleNode({ lo: root.lo, hi: rank - 1, sequence: root.sequence })),\n concatenateRuleTrees(makeRuleNode({ lo: rank, hi: root.hi, sequence: root.sequence }), root.right),\n ];\n}\nfunction assignRuleRange(root, lo, hi, sequence) {\n if (findIntersectingRule(root, lo, hi) === undefined)\n return insertRuleNode(root, { lo, hi, sequence });\n const [left, fromLo] = splitRuleTree(root, lo);\n const [, right] = splitRuleTree(fromLo, hi + 1);\n return concatenateRuleTrees(left, concatenateRuleTrees(makeRuleNode({ lo, hi, sequence }), right));\n}\nfunction newestRuleAt(root, rank, best = -1) {\n if (root === null || root.maxHi < rank || root.maxSequence <= best)\n return best;\n let next = best;\n if (root.left !== null)\n next = newestRuleAt(root.left, rank, next);\n if (root.lo <= rank && rank <= root.hi && root.sequence > next)\n next = root.sequence;\n if (root.lo <= rank && root.right !== null)\n next = newestRuleAt(root.right, rank, next);\n return next;\n}\nfunction runHeight(node) {\n return node?.height ?? 0;\n}\nfunction makeRunNode(selected, length, left = null, right = null) {\n return Object.freeze({\n selected,\n length,\n left,\n right,\n height: Math.max(runHeight(left), runHeight(right)) + 1,\n totalLength: length + (left?.totalLength ?? 0) + (right?.totalLength ?? 0),\n selectedCount: (selected ? length : 0) +\n (left?.selectedCount ?? 0) +\n (right?.selectedCount ?? 0),\n });\n}\nfunction singletonRun(selected, length) {\n return length === 0 ? null : makeRunNode(selected, length);\n}\nfunction joinRunTrees(left, middle, right) {\n if (runHeight(left) > runHeight(right) + 1 && left !== null) {\n return makeRunNode(left.selected, left.length, left.left, joinRunTrees(left.right, middle, right));\n }\n if (runHeight(right) > runHeight(left) + 1 && right !== null) {\n return makeRunNode(right.selected, right.length, joinRunTrees(left, middle, right.left), right.right);\n }\n return makeRunNode(middle.selected, middle.length, left, right);\n}\nfunction extractMinimumRun(root) {\n if (root.left === null)\n return [root, root.right];\n const [minimum, left] = extractMinimumRun(root.left);\n return [minimum, makeRunNode(root.selected, root.length, left, root.right)];\n}\nfunction concatRunTreesRaw(left, right) {\n if (left === null)\n return right;\n if (right === null)\n return left;\n const [minimum, remaining] = extractMinimumRun(right);\n return joinRunTrees(left, minimum, remaining);\n}\nfunction splitRunTree(root, index) {\n if (root === null)\n return [null, null];\n const leftLength = root.left?.totalLength ?? 0;\n if (index < leftLength) {\n const [left, right] = splitRunTree(root.left, index);\n return [\n left,\n joinRunTrees(right, makeRunNode(root.selected, root.length), root.right),\n ];\n }\n if (index > leftLength + root.length) {\n const [left, right] = splitRunTree(root.right, index - leftLength - root.length);\n return [\n joinRunTrees(root.left, makeRunNode(root.selected, root.length), left),\n right,\n ];\n }\n const ownOffset = index - leftLength;\n const leftOwn = singletonRun(root.selected, ownOffset);\n const rightOwn = singletonRun(root.selected, root.length - ownOffset);\n return [\n concatRunTreesRaw(root.left, leftOwn),\n concatRunTreesRaw(rightOwn, root.right),\n ];\n}\nfunction assignRunRange(root, start, end, selected) {\n const [left, rest] = splitRunTree(root, start);\n const [, right] = splitRunTree(rest, Math.max(0, end - start));\n return concatRunTreesRaw(concatRunTreesRaw(left, singletonRun(selected, Math.max(0, end - start))), right);\n}\nfunction removeRunAt(root, index) {\n const [left, rest] = splitRunTree(root, index);\n const [, right] = splitRunTree(rest, 1);\n return concatRunTreesRaw(left, right);\n}\nfunction insertRunAt(root, index, selected) {\n const [left, right] = splitRunTree(root, index);\n return concatRunTreesRaw(concatRunTreesRaw(left, singletonRun(selected, 1)), right);\n}\nconst rowSelectionPrograms = new WeakMap();\nfunction attachRowSelectionProgram(rows, program) {\n rowSelectionPrograms.set(rows, program);\n return rows;\n}\nfunction semanticRowSelected(program, rowId) {\n let sequence = 0;\n let selected = program.baseSelected;\n const point = getPointRule(program.points, rowId);\n if (point !== undefined) {\n sequence = point.sequence;\n selected = point.selected;\n }\n for (const layer of program.layers) {\n const rank = layer.snapshot.dataIndexOf(dataRef(rowId));\n if (rank < 0)\n continue;\n const rangeSequence = newestRuleAt(layer.rules, rank, sequence);\n if (rangeSequence > sequence) {\n sequence = rangeSequence;\n selected = true;\n }\n }\n return selected;\n}\nfunction buildProjection(program, snapshot) {\n // This is the explicit reset path: arbitrary replacement/permutation has no\n // sublinear intersection answer in the public snapshot contract. Stream the\n // target once into compressed runs; never allocate the selected ID set.\n if (program.sequence === 0) {\n return Object.freeze({\n snapshot,\n runs: singletonRun(program.baseSelected, snapshot.visibleDataRowCount),\n });\n }\n let runs = null;\n let currentValue;\n let currentLength = 0;\n const flush = () => {\n if (currentValue !== undefined && currentLength > 0)\n runs = concatRunTreesRaw(runs, singletonRun(currentValue, currentLength));\n };\n for (let index = 0; index < snapshot.visibleDataRowCount; index += 1) {\n const row = snapshot.dataRowAt(index);\n if (row === undefined)\n continue;\n const selected = semanticRowSelected(program, row.rowId);\n if (selected === currentValue)\n currentLength += 1;\n else {\n flush();\n currentValue = selected;\n currentLength = 1;\n }\n }\n flush();\n return Object.freeze({ snapshot, runs });\n}\nfunction projectionFor(program, snapshot) {\n return program.projection?.snapshot === snapshot\n ? program.projection\n : buildProjection(program, snapshot);\n}\nfunction addSemanticRange(program, snapshot, lo, hi, sequence) {\n const layerIndex = program.layers.findIndex((layer) => layer.snapshot === snapshot);\n const layers = Array.from(program.layers);\n if (layerIndex < 0) {\n layers.push(Object.freeze({\n snapshot,\n rules: assignRuleRange(null, lo, hi, sequence),\n }));\n }\n else {\n const layer = layers[layerIndex];\n layers[layerIndex] = Object.freeze({\n snapshot,\n rules: assignRuleRange(layer.rules, lo, hi, sequence),\n });\n }\n return Object.freeze({\n ...program,\n sequence,\n layers: Object.freeze(layers),\n });\n}\nfunction rowSelectionProgram(selection, snapshot) {\n const existing = rowSelectionPrograms.get(selection.rows);\n if (existing !== undefined)\n return existing;\n let program = Object.freeze({\n baseSelected: selection.rows.kind === \"all\",\n sequence: 0,\n points: null,\n layers: Object.freeze([]),\n });\n if (selection.rows.kind === \"explicit\") {\n for (const rowId of selection.rows.rowIds) {\n const sequence = program.sequence + 1;\n program = Object.freeze({\n ...program,\n sequence,\n points: setPointRule(program.points, {\n rowId,\n sequence,\n selected: true,\n }),\n });\n }\n for (const range of selection.rows.ranges ?? []) {\n const resolved = resolvedRowRange(range, snapshot);\n if (resolved === undefined)\n continue;\n program = addSemanticRange(program, snapshot, resolved.lo, resolved.hi, program.sequence + 1);\n }\n }\n for (const range of selection.rows.excludedRanges ?? []) {\n for (const rowId of [range.startRowId, range.endRowId]) {\n const sequence = program.sequence + 1;\n program = Object.freeze({\n ...program,\n sequence,\n points: setPointRule(program.points, {\n rowId,\n sequence,\n selected: false,\n }),\n });\n }\n }\n rowSelectionPrograms.set(selection.rows, program);\n return program;\n}\nfunction cloneRowsWithProgram(rows, program) {\n const clone = rows.kind === \"explicit\"\n ? Object.freeze({\n kind: \"explicit\",\n rowIds: rows.rowIds,\n ...(rows.ranges === undefined ? {} : { ranges: rows.ranges }),\n ...(rows.excludedRanges === undefined\n ? {}\n : { excludedRanges: rows.excludedRanges }),\n })\n : Object.freeze({\n kind: \"all\",\n ...(rows.excludedRanges === undefined\n ? {}\n : { excludedRanges: rows.excludedRanges }),\n });\n return attachRowSelectionProgram(clone, program);\n}\n/** @internal Preserves the semantic row-selection program across defensive copies. */\nexport function preserveIndexedRowSelectionProgram(source, target) {\n const program = rowSelectionPrograms.get(source);\n if (program !== undefined)\n rowSelectionPrograms.set(target, program);\n}\n/** @internal Releases snapshot bases retained only by a disposed grid state. */\nexport function releaseIndexedRowSelectionProgram(rows) {\n rowSelectionPrograms.delete(rows);\n}\n/** @internal Distinguishes identical public projections with different semantic histories. */\nexport function sameIndexedRowSelectionProgram(left, right) {\n const leftProgram = rowSelectionPrograms.get(left);\n const rightProgram = rowSelectionPrograms.get(right);\n if (leftProgram === rightProgram)\n return true;\n const canonical = (rows, program) => {\n if (program === undefined)\n return true;\n const kind = rows.kind;\n return (program.sequence === 0 &&\n program.points === null &&\n program.layers.length === 0 &&\n program.baseSelected === (kind === \"all\"));\n };\n return canonical(left, leftProgram) && canonical(right, rightProgram);\n}\nfunction countPointRules(root) {\n return root === null\n ? 0\n : 1 + countPointRules(root.left) + countPointRules(root.right);\n}\nfunction countRangeRules(root) {\n return root === null\n ? 0\n : 1 + countRangeRules(root.left) + countRangeRules(root.right);\n}\nfunction countRuns(root) {\n return root === null ? 0 : 1 + countRuns(root.left) + countRuns(root.right);\n}\n/** @internal Retention diagnostics for semantic-selection regression tests. */\nexport function getIndexedRowSelectionProgramDiagnostics(rows) {\n const program = rowSelectionPrograms.get(rows);\n return Object.freeze({\n pointRuleCount: countPointRules(program?.points ?? null),\n rangeRuleCount: (program?.layers ?? []).reduce((count, layer) => count + countRangeRules(layer.rules), 0),\n snapshotBasisCount: program?.layers.length ?? 0,\n projectionRunCount: countRuns(program?.projection?.runs ?? null),\n });\n}\nconst exclusionIndexes = new WeakSet();\nfunction makeExclusionIndex(revision, root) {\n const index = new IndexedRowRangeIndex(revision, root);\n exclusionIndexes.add(index);\n return index;\n}\nfunction resolvedRowRange(range, snapshot) {\n const startRank = snapshot.dataIndexOf(dataRef(range.startRowId));\n const endRank = snapshot.dataIndexOf(dataRef(range.endRowId));\n if (startRank < 0 || endRank < 0)\n return undefined;\n return startRank <= endRank\n ? {\n lo: startRank,\n hi: endRank,\n loId: range.startRowId,\n hiId: range.endRowId,\n }\n : {\n lo: endRank,\n hi: startRank,\n loId: range.endRowId,\n hiId: range.startRowId,\n };\n}\nfunction insertResolvedRange(index, next) {\n let root = index.root;\n let merged = next;\n for (;;) {\n const overlap = findOverlappingRange(root, merged.lo, merged.hi);\n if (overlap === undefined)\n break;\n root = removeRangeNode(root, overlap.lo);\n merged = {\n lo: Math.min(merged.lo, overlap.lo),\n hi: Math.max(merged.hi, overlap.hi),\n loId: overlap.lo < merged.lo ? overlap.loId : merged.loId,\n hiId: overlap.hi > merged.hi ? overlap.hiId : merged.hiId,\n };\n }\n return new IndexedRowRangeIndex(index.revision, insertRangeNode(root, merged));\n}\nfunction createRangeIndex(ranges, snapshot) {\n let index = new IndexedRowRangeIndex(snapshot.revision, null);\n for (const range of ranges ?? []) {\n const resolved = resolvedRowRange(range, snapshot);\n if (resolved !== undefined)\n index = insertResolvedRange(index, resolved);\n }\n return index;\n}\nfunction currentRangeIndex(ranges, snapshot) {\n return ranges instanceof IndexedRowRangeIndex &&\n !exclusionIndexes.has(ranges) &&\n ranges.revision === snapshot.revision\n ? ranges\n : createRangeIndex(ranges, snapshot);\n}\nfunction createExclusionIndex(ranges, snapshot) {\n let index = makeExclusionIndex(snapshot.revision, null);\n for (const range of ranges ?? []) {\n for (const rowId of [range.startRowId, range.endRowId]) {\n const point = resolvedRowRange({ startRowId: rowId, endRowId: rowId }, snapshot);\n if (point !== undefined && !rangeTreeContains(index.root, point.lo))\n index = makeExclusionIndex(snapshot.revision, insertRangeNode(index.root, point));\n }\n }\n return index;\n}\nfunction currentExclusionIndex(ranges, snapshot) {\n return ranges instanceof IndexedRowRangeIndex &&\n exclusionIndexes.has(ranges) &&\n ranges.revision === snapshot.revision\n ? ranges\n : createExclusionIndex(ranges, snapshot);\n}\nfunction insertExcludedPoint(index, point) {\n if (rangeTreeContains(index.root, point.lo))\n return index;\n return makeExclusionIndex(index.revision, insertRangeNode(index.root, point));\n}\nfunction removeExcludedSpan(index, removed) {\n if (findIntersectingRange(index.root, removed.lo, removed.hi) === undefined)\n return index;\n const [left, fromLo] = splitRangeTree(index.root, removed.lo);\n const [, right] = splitRangeTree(fromLo, removed.hi + 1);\n return makeExclusionIndex(index.revision, concatenateRangeTrees(left, right));\n}\nexport function selectIndexedRowRange(selection, startRowId, endRowId, snapshot) {\n const nextRange = { startRowId, endRowId };\n const resolvedNext = resolvedRowRange(nextRange, snapshot);\n if (resolvedNext === undefined)\n return selection;\n const program = rowSelectionProgram(selection, snapshot);\n const sequence = program.sequence + 1;\n const projection = projectionFor(program, snapshot);\n const nextProgram = Object.freeze({\n ...addSemanticRange(program, snapshot, resolvedNext.lo, resolvedNext.hi, sequence),\n projection: Object.freeze({\n snapshot: snapshot,\n runs: assignRunRange(projection.runs, resolvedNext.lo, resolvedNext.hi + 1, true),\n }),\n });\n if (selection.rows.kind === \"all\") {\n const excludedRanges = removeExcludedSpan(currentExclusionIndex(selection.rows.excludedRanges, snapshot), resolvedNext);\n const rows = attachRowSelectionProgram(Object.freeze({\n kind: \"all\",\n ...(excludedRanges.size === 0 ? {} : { excludedRanges }),\n }), nextProgram);\n return Object.freeze({\n ...selection,\n rows,\n });\n }\n const ranges = insertResolvedRange(currentRangeIndex(selection.rows.ranges, snapshot), resolvedNext);\n const excludedRanges = removeExcludedSpan(currentExclusionIndex(selection.rows.excludedRanges, snapshot), resolvedNext);\n const rows = attachRowSelectionProgram(Object.freeze({\n kind: \"explicit\",\n rowIds: selection.rows.rowIds,\n ranges,\n ...(excludedRanges.size === 0 ? {} : { excludedRanges }),\n }), nextProgram);\n return Object.freeze({\n ...selection,\n rows,\n });\n}\nexport function isIndexedRowSelected(selection, ref, snapshot) {\n if (ref.kind !== \"data\" || snapshot.indexOf(ref) < 0)\n return false;\n return semanticRowSelected(rowSelectionProgram(selection, snapshot), ref.rowId);\n}\n/**\n * Build the engine's row-checkbox slice from the shape a consumer can write.\n *\n * Deliberately assembled out of the same primitives a USER's gestures go\n * through — `selectAllVisibleRows`, `toggleIndexedRowSelection`,\n * `selectIndexedRowRange` — rather than by hand-rolling a second constructor\n * for the semantic program. A hand-rolled one would be a second definition of\n * what a selection means, free to drift from the gesture path it is supposed to\n * be interchangeable with, and it would have to reproduce the incremental\n * projection maintenance that keeps each of these sublinear.\n *\n * Cost is therefore O(k log n) in the SIZE OF THE REQUEST, never in the row\n * count: `{ kind: \"all\" }` alone runs one `selectAllVisibleRows`, which records\n * \"everything\" as a single run and visits no rows at all.\n *\n * Ids the current snapshot does not show are dropped, because that is what\n * ticking them by hand would do — the same rule `state.focus` and the cell\n * ranges already follow.\n */\nexport function createIndexedRowSelection(requested, snapshot) {\n let selection = createEmptyIndexedSelection();\n if (requested.kind === \"all\") {\n selection = selectAllVisibleRows(selection, snapshot);\n }\n else {\n // A Set because `toggleIndexedRowSelection` toggles: a repeated id would\n // tick the row and then untick it again.\n for (const rowId of new Set(requested.rowIds)) {\n selection = toggleIndexedRowSelection(selection, rowId, snapshot);\n }\n for (const range of requested.ranges ?? []) {\n selection = selectIndexedRowRange(selection, range.startRowId, range.endRowId, snapshot);\n }\n }\n for (const rowId of new Set(requested.excludedRowIds)) {\n // Only rows the request actually selected can be excluded from it. Without\n // this guard the toggle would SELECT an unselected id, turning \"everything\n // except row 7\" into \"everything, plus row 7\" the moment row 7 was not\n // covered in the first place.\n if (!isIndexedRowSelected(selection, dataRef(rowId), snapshot))\n continue;\n selection = toggleIndexedRowSelection(selection, rowId, snapshot);\n }\n return selection.rows;\n}\n/**\n * Render the engine's row-checkbox slice as the shape a consumer can write\n * back — the inverse of {@link createIndexedRowSelection}.\n *\n * Sparse in, sparse out. A symbolic \"all\" stays two words, and a shift-checked\n * 100k-row span stays its two endpoint ids; nothing here walks a population.\n *\n * @public\n */\nexport function describeRowSelection(rows) {\n // Exclusions are stored as degenerate ranges — `insertExcludedPoint` is the\n // only thing that ever adds one — so reading both endpoints costs nothing and\n // survives any future widening rather than silently halving it.\n const excluded = new Set();\n for (const range of rows.excludedRanges ?? []) {\n excluded.add(range.startRowId);\n excluded.add(range.endRowId);\n }\n const excludedRowIds = excluded.size === 0 ? {} : { excludedRowIds: Object.freeze([...excluded]) };\n if (rows.kind === \"all\") {\n return Object.freeze({ kind: \"all\", ...excludedRowIds });\n }\n const ranges = [...(rows.ranges ?? [])].map((range) => Object.freeze({ startRowId: range.startRowId, endRowId: range.endRowId }));\n return Object.freeze({\n kind: \"explicit\",\n rowIds: Object.freeze([...rows.rowIds]),\n ...(ranges.length === 0 ? {} : { ranges: Object.freeze(ranges) }),\n ...excludedRowIds,\n });\n}\n/**\n * @internal Structural equality for the row-checkbox slice, ignoring the\n * semantic program attached to it.\n *\n * `sameSelection` cannot answer this question: it short-circuits on\n * `sameIndexedRowSelectionProgram`, which compares HISTORIES and so calls two\n * independently-built selections different even when they tick the same rows.\n * That is the right answer for a gesture (an \"all\"-derived selection and an\n * identical explicit one behave differently as rows arrive) and the wrong one\n * for an idempotence check, where the question is only whether applying this\n * value would change anything a reader can see.\n */\nexport function sameIndexedRowSelectionValue(left, right) {\n if (left === right)\n return true;\n if (left.kind !== right.kind)\n return false;\n if (!sameRowRangeIndex(left.excludedRanges, right.excludedRanges))\n return false;\n if (left.kind !== \"explicit\" || right.kind !== \"explicit\")\n return true;\n if (left.rowIds.size !== right.rowIds.size)\n return false;\n for (const rowId of left.rowIds) {\n if (!right.rowIds.has(rowId))\n return false;\n }\n return sameRowRangeIndex(left.ranges, right.ranges);\n}\nfunction sameRowRangeIndex(left, right) {\n if (left === right)\n return true;\n if ((left?.size ?? 0) !== (right?.size ?? 0))\n return false;\n const leftRanges = [...(left ?? [])];\n const rightRanges = [...(right ?? [])];\n return leftRanges.every((range, index) => {\n const other = rightRanges[index];\n return (other !== undefined &&\n sameRowId(range.startRowId, other.startRowId) &&\n sameRowId(range.endRowId, other.endRowId));\n });\n}\nexport function getIndexedSelectionSummary(selection, snapshot) {\n const visibleCount = snapshot.visibleDataRowCount;\n const selectedCount = projectionFor(rowSelectionProgram(selection, snapshot), snapshot).runs?.selectedCount ?? 0;\n return Object.freeze({\n state: selectedCount === 0\n ? \"none\"\n : selectedCount === visibleCount\n ? \"all\"\n : \"some\",\n selectedCount,\n visibleCount,\n });\n}\nfunction columnIndex(columns, columnId) {\n for (let index = 0; index < columns.length; index += 1) {\n if (columns[index] === columnId)\n return index;\n }\n return -1;\n}\n/**\n * `rowId`'s absolute DATASET position, or `-1` when the row is not loaded.\n *\n * With `loadedWindow` null this is the plain data-only rank every\n * pre-eviction caller already compared against, so a local-mode grid keeps\n * arithmetic that is byte-for-byte what it was. With a window it is the rank\n * shifted into dataset coordinates, which is the only space in which a span\n * still means something once its rows are gone.\n *\n * Data-only rank, not `indexOf`: group headers occupy visible indices but no\n * dataset position, and the window is a dataset span. The two orderings agree\n * on data rows — both are monotonic in visible order — so containment answers\n * identically for the cells this function is ever asked about.\n */\nfunction datasetPosition(snapshot, rowId, loadedWindow) {\n const rank = snapshot.dataIndexOf(dataRef(rowId));\n if (rank < 0)\n return -1;\n return (loadedWindow?.start ?? 0) + rank;\n}\n/**\n * Whether `span`'s remembered positions may be read against `window`.\n *\n * FAIL-CLOSED, and deliberately so. Matching keys mean the same population,\n * so the positions still name the same rows. A different key means a re-sort\n * or a filter change has re-filled those positions with other rows entirely.\n * And an ABSENT key on either side is not a match — it is the absence of any\n * evidence about the population, which is the same situation as a mismatch\n * and must be refused for the same reason.\n *\n * Treating \"no key on both sides\" as agreement fails OPEN, and the failure is\n * not a downgraded number, it is wrong paint: a windowed consumer who simply\n * never heard of `datasetKey` (it is optional, and nothing in the type says it\n * is load-bearing) re-sorts, one endpoint survives at a new position, and\n * `indexedRangeContainsCell` — which returns a bare boolean and has no\n * `verified` channel to downgrade through — reports `true` for rows the user\n * never selected. Measured: selection `row-10..row-40` under window\n * `[0, 100)`, re-sorted to `[30, 130)`, painted a row that had never been in\n * the selection.\n *\n * The cost of closing it is that a windowed consumer publishing no\n * `datasetKey` loses span survival across eviction and degrades to\n * loaded-rows-only — visibly, in the `verified` flag and the count, rather\n * than invisibly, in the wrong cells. `warnMissingDatasetKey` tells them.\n *\n * Local mode is untouched: with no window there is no span to read in the\n * first place (see `endpointPositions`).\n *\n * ## The population is a second question, and the key does not answer it\n *\n * `datasetKey` identifies the QUERY. `lifecycle.mdx` tells consumers to keep\n * it stable while they page within one result, so an insert or a delete made\n * upstream of an evicted selection leaves the key matching while re-filling\n * the remembered positions with entirely different rows. Measured:\n * `row-1..row-8` selected and evicted, five rows prepended to the same\n * result, and the returning window painted four rows that did not exist when\n * the user selected — while the eight they did select painted nothing.\n *\n * So the size of the population is compared too, and it fails closed the same\n * way. `provenDeletions` is the one allowance: rows this very call has\n * PROVEN gone are a population change the engine observed, so a total short\n * by exactly that many is fully accounted for rather than unexplained. Only\n * {@link narrowDeletedEndpoints} passes a non-zero value; every reader that\n * merely wants to trust a remembered position uses the strict form.\n */\nfunction spanReadableInWindow(span, window, provenDeletions = 0) {\n return (window.datasetKey !== undefined &&\n span.datasetKey === window.datasetKey &&\n span.datasetTotal !== undefined &&\n window.datasetTotal === span.datasetTotal - provenDeletions);\n}\n/**\n * Whether `window` can carry dataset spans at all. A window with no\n * `datasetKey` cannot: anything stamped under it could never be read back\n * (see {@link spanReadableInWindow}), so stamping one would only emit a\n * number through `onSelectionChange` that the engine itself refuses.\n */\nfunction windowCarriesSpans(window) {\n return window !== null && window.datasetKey !== undefined;\n}\n/**\n * Where `range`'s endpoints sit in the dataset, per endpoint, preferring what\n * the snapshot can confirm right now over what the range remembers.\n *\n * `undefined` for an endpoint means neither source could answer.\n */\nfunction endpointPositions(range, snapshot, loadedWindow) {\n const liveStart = datasetPosition(snapshot, range.start.rowId, loadedWindow);\n const liveEnd = datasetPosition(snapshot, range.end.rowId, loadedWindow);\n const bothLive = liveStart >= 0 && liveEnd >= 0;\n if (bothLive)\n return { start: liveStart, end: liveEnd, bothLive };\n // Pre-eviction callers never carry a span and never supply a window. With\n // no window there is no dataset coordinate system to remember positions in,\n // so a half-resolved range answers nothing at all — byte-for-byte what it\n // did before eviction existed.\n if (loadedWindow === null)\n return { start: undefined, end: undefined, bothLive };\n const remembered = range.datasetRowSpan !== undefined &&\n spanReadableInWindow(range.datasetRowSpan, loadedWindow)\n ? range.datasetRowSpan\n : undefined;\n return {\n start: liveStart >= 0 ? liveStart : remembered?.start,\n end: liveEnd >= 0 ? liveEnd : remembered?.end,\n bothLive,\n };\n}\n/**\n * The dataset positions `range` covers, ordered.\n *\n * The remembered half is the whole point of eviction: an endpoint that is\n * merely evicted still has a dataset position recorded on the range, and\n * `hi - lo + 1` over it is answerable with zero rows loaded. It is flagged\n * unverified because a row deleted server-side WHILE evicted leaves no trace\n * anywhere the engine can read.\n *\n * A range with ONE endpoint resolvable resolves to the union of what it does\n * know — the live survivor plus the absentee's remembered position, or just\n * the survivor when nothing is remembered. This is the sliding-window case:\n * an ordinary incremental scroll retires one endpoint many revisions before\n * the other, and treating that as \"unanswerable\" would under-report every\n * scrolled selection by the whole span but one row.\n *\n * `undefined` — neither endpoint resolvable and nothing usable remembered —\n * is genuinely unanswerable, which is different from zero.\n */\nfunction rangeDatasetSpan(range, snapshot, loadedWindow) {\n const { start, end, bothLive } = endpointPositions(range, snapshot, loadedWindow);\n const low = start ?? end;\n const high = end ?? start;\n if (low === undefined || high === undefined)\n return undefined;\n return {\n lo: Math.min(low, high),\n hi: Math.max(low, high),\n // Both endpoints present is not on its own enough to call the extent\n // proven. Under a window that CAN carry spans, a range without one has no\n // positional identity: reconciliation stripped it, which it only does\n // when it could not locate the range in the current population. The rows\n // it still names really are selected — so it paints — but the extent it\n // reports is a remnant, not what the user chose, and saying otherwise is\n // the same \"silent under-count wearing a verified flag\" this whole\n // design exists to remove.\n verified: bothLive &&\n (!windowCarriesSpans(loadedWindow) || range.datasetRowSpan !== undefined),\n };\n}\n/**\n * Data rows covered by the CELL-RANGE slice (`selection.ranges`), by\n * arithmetic over spans rather than by visiting rows — so a 4,901-row\n * selection with 30 rows loaded still counts 4,901.\n *\n * Not to be confused with {@link getIndexedSelectionSummary}, which counts\n * the separate sparse row-selection program the checkbox column drives.\n *\n * `loadedWindow` is the same honesty-gated span `reconcileIndexedSelection`\n * takes; omitting it (local mode) restricts the count to what the snapshot\n * can resolve, exactly as before eviction existed.\n *\n * @internal Re-exported by `@pretable/core` as\n * `ɵgetIndexedCellSelectionSummary`.\n */\nexport function getIndexedCellSelectionSummary(selection, snapshot, loadedWindow) {\n const window = loadedWindow ?? null;\n const spans = [];\n let verified = true;\n for (const range of selection.ranges) {\n const span = rangeDatasetSpan(range, snapshot, window);\n if (span === undefined) {\n // Selects at least one row, at a position nothing can supply. Adding a\n // guess would be the lie; contributing nothing and saying the total is\n // unverified is the most this can honestly do.\n verified = false;\n continue;\n }\n if (!span.verified)\n verified = false;\n spans.push(span);\n }\n // Union, so two ranges over the same rows report those rows once. Sorting a\n // handful of spans is still O(ranges) in the sense that matters: nothing\n // here scales with how many rows are selected.\n spans.sort((left, right) => left.lo - right.lo);\n let rowCount = 0;\n let covered = null;\n for (const span of spans) {\n const lo = covered === null || span.lo > covered ? span.lo : covered + 1;\n if (span.hi >= lo)\n rowCount += span.hi - lo + 1;\n if (covered === null || span.hi > covered)\n covered = span.hi;\n }\n return Object.freeze({ rowCount, verified });\n}\n/**\n * Whether a cell range covers `ref` / `columnId`, resolved against the drawn\n * column order.\n *\n * @internal Re-exported by `@pretable/core` as `ɵindexedRangeContainsCell`.\n */\nexport function indexedRangeContainsCell(range, ref, columnId, snapshot, columns, \n/**\n * The loaded span, when the honesty gate is passing. Supplying it is what\n * lets a rendered row in the MIDDLE of a range paint while the range's own\n * endpoints are evicted — the case that previously painted nothing at all,\n * because resolving both endpoints was a precondition.\n */\nloadedWindow) {\n if (ref.kind !== \"data\")\n return false;\n const currentColumnIndex = columnIndex(columns, columnId);\n const startColumnIndex = columnIndex(columns, range.start.columnId);\n const endColumnIndex = columnIndex(columns, range.end.columnId);\n if (currentColumnIndex < 0 ||\n startColumnIndex < 0 ||\n endColumnIndex < 0 ||\n currentColumnIndex < Math.min(startColumnIndex, endColumnIndex) ||\n currentColumnIndex > Math.max(startColumnIndex, endColumnIndex)) {\n return false;\n }\n const window = loadedWindow ?? null;\n const rowPosition = datasetPosition(snapshot, ref.rowId, window);\n if (rowPosition < 0)\n return false;\n const span = rangeDatasetSpan(range, snapshot, window);\n if (span === undefined)\n return false;\n return rowPosition >= span.lo && rowPosition <= span.hi;\n}\nfunction visibleAddress(address, snapshot) {\n return isVisibleData(snapshot, address.rowId);\n}\nfunction sameRowId(left, right) {\n return left === right || (left !== left && right !== right);\n}\n/** @internal Projects the visible rank cache from exact row-model deltas. */\nexport function projectIndexedSelection(selection, previousSnapshot, snapshot, sequence) {\n const program = rowSelectionProgram(selection, previousSnapshot);\n let projection;\n if (sequence.kind === \"reset\" ||\n sequence.fromRevision !== previousSnapshot.revision ||\n sequence.toRevision !== snapshot.revision) {\n projection = buildProjection(program, snapshot);\n }\n else {\n // Routine revisions touch only structural data refs. Removing their old\n // ranks then inserting their final ranks preserves every untouched run and\n // makes work proportional to the journal delta, not ranges or exclusions.\n let runs = projectionFor(program, previousSnapshot).runs;\n const touched = new Map();\n for (const change of sequence.changes) {\n for (const operation of change.operations) {\n if (operation.ref.kind === \"data\" && operation.kind !== \"update\")\n touched.set(operation.ref.rowId, true);\n }\n }\n const removals = [];\n const insertions = [];\n for (const rowId of touched.keys()) {\n const previousRank = previousSnapshot.dataIndexOf(dataRef(rowId));\n if (previousRank >= 0)\n removals.push({ rank: previousRank, rowId });\n const rank = snapshot.dataIndexOf(dataRef(rowId));\n if (rank >= 0)\n insertions.push({ rank, rowId });\n }\n removals.sort((left, right) => right.rank - left.rank);\n for (const removal of removals)\n runs = removeRunAt(runs, removal.rank);\n insertions.sort((left, right) => left.rank - right.rank);\n for (const insertion of insertions)\n runs = insertRunAt(runs, insertion.rank, semanticRowSelected(program, insertion.rowId));\n if ((runs?.totalLength ?? 0) !== snapshot.visibleDataRowCount) {\n projection = buildProjection(program, snapshot);\n }\n else {\n projection = Object.freeze({\n snapshot: snapshot,\n runs,\n });\n }\n }\n const nextProgram = Object.freeze({ ...program, projection });\n const rows = cloneRowsWithProgram(selection.rows, nextProgram);\n return Object.freeze({ ...selection, rows });\n}\n/**\n * Whether `rowId`'s disappearance from `snapshot` is provably a deletion\n * rather than an eviction. Proof requires knowing where the row sat in\n * dataset terms the last time it *was* loaded — `previous.snapshot`'s\n * data-only rank, converted to an absolute position via `previous.window`,\n * the window that was active for that snapshot. Falling inside\n * `loadedWindow` (the window active NOW) means the current window covers\n * where the row used to be, yet the row is gone — nothing but deletion\n * explains that. Falling outside — or the position simply being unknown,\n * because `previous` was not supplied or never resolved the row — is NOT\n * proof of deletion, so the row is presumed evicted: it may simply be\n * sitting in the unloaded remainder the window admits exists.\n *\n * @internal Exported for `reconcileIndexedFocus`, which must reach the same\n * verdict about a row as the selection does — never re-implemented there.\n */\nexport function provenDeletedRow(rowId, loadedWindow, previous) {\n if (previous === undefined || previous.window == null)\n return false;\n const previousRank = previous.snapshot.dataIndexOf(dataRef(rowId));\n if (previousRank < 0)\n return false;\n const previousAbsolute = previous.window.start + previousRank;\n return (previousAbsolute >= loadedWindow.start &&\n previousAbsolute < loadedWindow.start + loadedWindow.length);\n}\n/**\n * The row that now holds dataset position `position`, addressed in `column`.\n *\n * `undefined` when the position is outside the loaded window, which is the\n * only honest answer: naming a row is naming an identity, and the engine\n * cannot name one it has not loaded.\n */\nfunction addressAtDatasetPosition(snapshot, position, column, loadedWindow) {\n const rank = position - loadedWindow.start;\n if (rank < 0 || rank >= loadedWindow.length)\n return undefined;\n const row = snapshot.dataRowAt(rank);\n if (row === undefined)\n return undefined;\n return Object.freeze({ rowId: row.rowId, columnId: column });\n}\n/**\n * Narrows `range` by the endpoints that are PROVEN deleted, instead of\n * discarding it.\n *\n * The spec states the eviction rule per ROW: an absent row inside the loaded\n * span is deleted and prunes, one outside it is evicted and survives. Applied\n * per RANGE — drop the whole range if either endpoint is proven deleted — one\n * genuinely removed row took every merely-evicted row between the endpoints\n * with it, which is the silent under-selection this design exists to remove.\n *\n * The arithmetic is one rule for every shape. A deletion removes a row from\n * the dataset, so everything after it shifts down one; whether the deleted\n * endpoint is the low one or the high one, the surviving rows end up at\n * `lo … hi - 1`:\n *\n * | Deleted endpoint | Survivors, old positions | …after the shift |\n * | ---------------- | ------------------------ | ---------------- |\n * | the LOW end | `lo + 1 … hi` | `lo … hi - 1` |\n * | the HIGH end | `lo … hi - 1` | `lo … hi - 1` |\n *\n * So the HIGH field loses one position per proven deletion and the low field\n * does not move — and a surviving endpoint that is loaded reports its live\n * position instead, which already carries the shift and also absorbs any\n * deletion the engine could not prove.\n *\n * Returns `undefined` — meaning \"drop the range\", the pre-narrowing answer —\n * when there is no readable span to narrow, when nothing is left of the span,\n * or when the narrowed boundary lands on a row that is not loaded and so\n * cannot be named. Fail-closed in every case: the range is discarded rather\n * than left holding a position it cannot justify.\n */\nfunction narrowDeletedEndpoints(range, snapshot, loadedWindow, deleted) {\n const span = range.datasetRowSpan;\n const count = (deleted.start ? 1 : 0) + (deleted.end ? 1 : 0);\n // No positional identity, so there is nothing to narrow BY. A windowed grid\n // that publishes no `datasetKey` lands here on every range, deliberately:\n // its spans are refused everywhere else too (see `spanReadableInWindow`).\n //\n // `count` is passed as the proven-deletion allowance: a deletion IS a\n // population change, so the strict read would refuse every span the moment\n // it had something to narrow. Requiring the total to be short by exactly\n // the rows this call proved gone keeps the check meaningful — a revision\n // that also inserted, or that deleted a third row elsewhere, does not add\n // up and is refused, which drops the range rather than moving it to a\n // position the engine cannot justify.\n if (span === undefined || !spanReadableInWindow(span, loadedWindow, count))\n return undefined;\n const startIsHigh = span.start >= span.end;\n let nextStart = startIsHigh ? span.start - count : span.start;\n let nextEnd = startIsHigh ? span.end : span.end - count;\n if (!deleted.start) {\n const live = datasetPosition(snapshot, range.start.rowId, loadedWindow);\n if (live >= 0)\n nextStart = live;\n }\n if (!deleted.end) {\n const live = datasetPosition(snapshot, range.end.rowId, loadedWindow);\n if (live >= 0)\n nextEnd = live;\n }\n // Empty: the deletions consumed the whole span. `nextStart`/`nextEnd` can\n // cross only when `count` exceeded the span's width, which is exactly that.\n if (startIsHigh ? nextStart < nextEnd : nextEnd < nextStart)\n return undefined;\n const start = deleted.start\n ? addressAtDatasetPosition(snapshot, nextStart, range.start.columnId, loadedWindow)\n : range.start;\n const end = deleted.end\n ? addressAtDatasetPosition(snapshot, nextEnd, range.end.columnId, loadedWindow)\n : range.end;\n if (start === undefined || end === undefined)\n return undefined;\n return Object.freeze({\n start,\n end,\n datasetRowSpan: Object.freeze({\n start: nextStart,\n end: nextEnd,\n datasetKey: span.datasetKey,\n // The CURRENT total, not the span's. These positions have just been\n // rewritten to describe the post-deletion population, so stamping the\n // pre-deletion size would leave the range permanently unreadable the\n // instant after it was successfully narrowed.\n datasetTotal: loadedWindow.datasetTotal,\n }),\n });\n}\nfunction sameSpan(left, right) {\n if (left === right)\n return true;\n if (left === undefined || right === undefined)\n return false;\n // Plain value equality, NOT `spanReadableInWindow`: this asks whether two\n // spans say the same thing, not whether either may be trusted.\n return (left.start === right.start &&\n left.end === right.end &&\n left.datasetKey === right.datasetKey &&\n left.datasetTotal === right.datasetTotal);\n}\nfunction withoutDatasetRowSpan(range) {\n if (range.datasetRowSpan === undefined)\n return range;\n return Object.freeze({ start: range.start, end: range.end });\n}\n/**\n * Records where `range`'s endpoints sit in the dataset, so the span outlives\n * the rows.\n *\n * Positions come from the snapshot where it can answer and from the range's\n * own memory where it cannot, which is what lets a gesture extending from an\n * already-EVICTED anchor still produce a countable range. A stamp is written\n * only when BOTH endpoints resolve that way: a half-known range keeps\n * whatever it had, so a moment of partial knowledge cannot overwrite a\n * complete span with a narrower one.\n *\n * Returns `range` itself when there is nothing to record — no window, or a\n * span identical to the one already on it — so reconciliation stays a no-op\n * in local mode and does not republish the selection on every revision.\n *\n * A window with no `datasetKey` records nothing and clears whatever was\n * there: such a span could never be read back (see\n * {@link spanReadableInWindow}), so keeping one would put a number the engine\n * itself refuses in front of a consumer, who might well persist it.\n */\nfunction stampDatasetRowSpan(range, snapshot, loadedWindow) {\n // No window: nothing to record, and nothing to correct. A span already on\n // the range is left alone rather than dropped — it is inert here (with no\n // window, `endpointPositions` never reads a remembered position), and the\n // window is routinely absent for a moment BEFORE the first revision is\n // observed. Dropping it there would destroy a selection restored through\n // the controlled `state` prop on the very render that restores it.\n if (loadedWindow === null)\n return range;\n if (!windowCarriesSpans(loadedWindow))\n return withoutDatasetRowSpan(range);\n const { start, end } = endpointPositions(range, snapshot, loadedWindow);\n if (start === undefined || end === undefined) {\n return range.datasetRowSpan === undefined ||\n spanReadableInWindow(range.datasetRowSpan, loadedWindow)\n ? range\n : withoutDatasetRowSpan(range);\n }\n const next = Object.freeze({\n start,\n end,\n datasetKey: loadedWindow.datasetKey,\n datasetTotal: loadedWindow.datasetTotal,\n });\n if (sameSpan(range.datasetRowSpan, next))\n return range;\n return Object.freeze({ ...range, datasetRowSpan: next });\n}\n/**\n * Fills in `datasetRowSpan` for ranges a GESTURE just built.\n *\n * Every selection gesture — shift-click, keyboard extension, marquee,\n * select-all, an echo through the controlled `state` prop — hands the engine\n * brand-new range objects carrying nothing but row ids. Left alone those\n * ranges are born spanless, so the count collapses to whatever happens to be\n * loaded the moment the window next moves. Stamping them here, on the single\n * public write path, is what makes the span the range's identity rather than\n * a memo reconciliation occasionally attaches.\n *\n * `replaced` is the selection being written over. It is read as a\n * rowId → dataset-position map, which is how an extension anchored on an\n * evicted row still knows where its anchor is: the range that anchor came\n * from is right there, and it remembers.\n */\nexport function adoptIndexedCellRangeSpans(ranges, replaced, snapshot, loadedWindow) {\n // No window, or one that cannot carry spans: `stampDatasetRowSpan` is the\n // whole of the behaviour, and there is nothing to recall from.\n if (!windowCarriesSpans(loadedWindow))\n return ranges.map((range) => stampDatasetRowSpan(range, snapshot, loadedWindow));\n const remembered = new Map();\n for (const range of replaced) {\n const span = range.datasetRowSpan;\n if (span === undefined)\n continue;\n if (!spanReadableInWindow(span, loadedWindow))\n continue;\n if (!remembered.has(range.start.rowId))\n remembered.set(range.start.rowId, span.start);\n if (!remembered.has(range.end.rowId))\n remembered.set(range.end.rowId, span.end);\n }\n return ranges.map((range) => {\n // Per endpoint, best source first: what the snapshot can see now, then\n // what this range already carries, then what the selection it replaces\n // remembers about that same row id.\n const own = endpointPositions(range, snapshot, loadedWindow);\n const start = own.start ?? remembered.get(range.start.rowId);\n const end = own.end ?? remembered.get(range.end.rowId);\n if (start === undefined || end === undefined)\n return stampDatasetRowSpan(range, snapshot, loadedWindow);\n const next = Object.freeze({\n start,\n end,\n datasetKey: loadedWindow.datasetKey,\n datasetTotal: loadedWindow.datasetTotal,\n });\n if (sameSpan(range.datasetRowSpan, next))\n return range;\n return Object.freeze({ ...range, datasetRowSpan: next });\n });\n}\n/**\n * The window absence may be judged AGAINST, which is not always the window\n * that was supplied.\n *\n * A new `datasetKey` is a new population: the dataset positions every span\n * remembers now hold different rows, and no row id can be presumed merely\n * evicted rather than gone. Retention is switched off for that revision — the\n * pre-eviction rules apply, which is what the spec means by \"a new datasetKey\n * resets everything, as today\".\n *\n * @internal Shared with `reconcileIndexedFocus`: the cursor and the selection\n * must switch retention off on the same revisions, or a population change\n * drops the selection while the cursor sits on a row from the old one.\n */\nexport function evictionRetentionWindow(eviction) {\n const suppliedWindow = eviction?.window ?? null;\n const previousWindow = eviction?.previous?.window;\n const populationChanged = suppliedWindow !== null &&\n previousWindow != null &&\n // Value comparison, not `spanReadableInWindow`: two keyless windows are\n // not evidence of a change. A keyless consumer gets no span trust at all\n // (see `windowCarriesSpans`), so there is nothing here to invalidate.\n previousWindow.datasetKey !== suppliedWindow.datasetKey;\n return populationChanged ? null : suppliedWindow;\n}\n/**\n * Whether this revision's window is UNKNOWN rather than absent.\n *\n * A null window is two entirely different situations and they want opposite\n * answers. In LOCAL mode the consumer hands over the whole result on every\n * `setRows`, so an absent row really has been deleted and pruning is correct.\n * In a WINDOWED grid whose honesty gate did not pass this revision — an\n * in-flight count query, a backend that estimates past 10k, one revision of\n * engine-side sort — the engine has been told nothing at all about which rows\n * exist. Dropping a selection there is the engine ASSERTING a deletion it\n * cannot have observed, from inputs that are every one of them transient\n * properties of a single render. Measured: one such revision destroyed an\n * eight-row selection AND the cursor permanently, and restoring the exact\n * total afterwards brought neither back, because the span was already gone.\n *\n * So: absent proof of deletion, retain. The same rule the rest of this file\n * already follows, applied to the case where the proof is not merely missing\n * but unobtainable.\n *\n * NOT the same question as {@link evictionRetentionWindow}, which also\n * returns null on a POPULATION CHANGE — a new `datasetKey`, where the engine\n * has been told plenty and what it was told is \"everything you remember is\n * about a different table\". That still resets, as the spec says it must.\n *\n * @internal Shared with `reconcileIndexedFocus`: the cursor and the selection\n * must reach the same verdict on the same revisions, or a grid retains a\n * selection under a cursor that moved.\n */\nexport function evictionWindowUnknown(eviction) {\n return (eviction?.windowed ?? false) && (eviction?.window ?? null) === null;\n}\nexport function reconcileIndexedSelection(selection, snapshot, eviction) {\n const suppliedWindow = eviction?.window ?? null;\n const previous = eviction?.previous;\n // STAMPING still runs against `suppliedWindow` on a population change, which\n // is the difference between this and simply passing `null` everywhere: a\n // range whose two endpoints are both present in the NEW population is fully\n // locatable there, so it is re-stamped in the new population's coordinates.\n // Passing `null` for that too would leave the old key sitting on the range,\n // refused by every reader but still emitted through `onSelectionChange`\n // and liable to be persisted by a consumer.\n const retentionWindow = evictionRetentionWindow(eviction);\n let changed = false;\n rowSelectionProgram(selection, snapshot);\n // The window is unknown this revision, so nothing below has anything to\n // reason FROM: absence is not evidence of deletion, and a position stamped\n // against no window would be a position in no coordinate system. A\n // reconciliation that learned nothing changes nothing. Returned after the\n // `rowSelectionProgram` call above, which rebuilds the visible-rank cache\n // and is required on every revision regardless of what this decides.\n //\n // Local mode never reaches this line — see `evictionWindowUnknown`.\n if (evictionWindowUnknown(eviction))\n return selection;\n const ranges = [];\n for (const range of selection.ranges) {\n const startVisible = visibleAddress(range.start, snapshot);\n const endVisible = visibleAddress(range.end, snapshot);\n if (startVisible && endVisible) {\n // Both endpoints are here, so this is the moment the span is knowable\n // first-hand. Record it; every later revision that cannot see them\n // reads it back.\n const stamped = stampDatasetRowSpan(range, snapshot, suppliedWindow);\n if (stamped !== range)\n changed = true;\n ranges.push(stamped);\n }\n else if (startVisible || endVisible) {\n const survivor = startVisible ? range.start : range.end;\n const absentee = startVisible ? range.end : range.start;\n // ONE endpoint gone is what an ordinary incremental scroll looks like:\n // the window slides past the range's start many revisions before it\n // reaches the end. Collapsing to the survivor there rewrites the\n // selection — and, because the collapsed range is stamped in turn,\n // overwrites the span that recorded how big it really was, so the\n // truth does not come back when the row does. Only a PROVEN deletion\n // earns the collapse; mere absence keeps the range whole, with the\n // survivor's position refreshed live and the absentee's read back\n // from the span.\n const absenteeDeleted = retentionWindow !== null &&\n provenDeletedRow(absentee.rowId, retentionWindow, previous);\n // A proven deletion prunes ONE ROW, not the range around it. The rows\n // between the endpoints are still selected — most of them loaded and\n // painted, in this branch — so the range narrows past the deleted\n // endpoint rather than collapsing onto the survivor and reporting a\n // selection of one.\n const narrowed = absenteeDeleted && retentionWindow !== null\n ? narrowDeletedEndpoints(range, snapshot, retentionWindow, {\n start: !startVisible,\n end: !endVisible,\n })\n : undefined;\n if (narrowed !== undefined) {\n ranges.push(narrowed);\n changed = true;\n }\n else if (retentionWindow === null || absenteeDeleted) {\n ranges.push(stampDatasetRowSpan(Object.freeze({ start: survivor, end: survivor }), snapshot, \n // `retentionWindow`, not `suppliedWindow`. On a population change\n // this is null, so the collapsed range gets NO span — which is\n // the whole point: it is a remnant of a selection the engine\n // could not locate in the new population, and a span would let\n // the summary call its one surviving row a proven extent. See\n // `rangeDatasetSpan`, which reads a missing span under a\n // span-carrying window as exactly that doubt.\n retentionWindow));\n changed = true;\n }\n else {\n const retained = stampDatasetRowSpan(range, snapshot, retentionWindow);\n if (retained !== range)\n changed = true;\n ranges.push(retained);\n }\n }\n else if (retentionWindow != null) {\n // Pruning requires POSITIVE proof of deletion for at least one\n // endpoint. Neither being provable does not retain \"half\" the row the\n // way partial visibility above does — the row is a single identity\n // that is either loaded or not, so an unprovable pair keeps the whole\n // range verbatim, letting a returning row come back selected.\n const startDeleted = provenDeletedRow(range.start.rowId, retentionWindow, previous);\n const endDeleted = provenDeletedRow(range.end.rowId, retentionWindow, previous);\n if (startDeleted || endDeleted) {\n changed = true;\n // Same rule as the branch above: the proven-deleted ROWS go, the span\n // around them stays. Dropping the range here is what took an evicted\n // 80-row selection down with a single deleted endpoint.\n const narrowed = narrowDeletedEndpoints(range, snapshot, retentionWindow, { start: startDeleted, end: endDeleted });\n if (narrowed !== undefined)\n ranges.push(narrowed);\n }\n else {\n ranges.push(range);\n }\n }\n else {\n changed = true;\n }\n }\n let anchor = selection.anchor;\n if (anchor !== null &&\n !visibleAddress(anchor, snapshot) &&\n // The anchor is the fixed end of the NEXT gesture —\n // `extendRangeFromAnchor` builds its range straight from this address —\n // so it is an identity, not a cursor into the loaded rows. Reassigning it\n // on visibility alone flips which end of an upward selection is fixed\n // (and, with several ranges, jumps it into a range the user never\n // anchored on): the next shift-click then extends from the wrong end and\n // deselects what they had. Only a PROVEN deletion earns the reassignment,\n // for the same reason it is what earns collapsing a range.\n (retentionWindow === null ||\n provenDeletedRow(anchor.rowId, retentionWindow, previous))) {\n anchor = ranges[0]?.start ?? null;\n changed = true;\n }\n if (!changed)\n return selection;\n return Object.freeze({\n ...selection,\n ranges: Object.freeze(ranges),\n anchor,\n });\n}\n","import { scrollTopToReveal, } from \"@pretable-internal/layout-core\";\nimport { evictionRetentionWindow, evictionWindowUnknown, provenDeletedRow, } from \"./indexed-selection\";\n/**\n * The one header address there is.\n *\n * Frozen and shared so identity comparison short-circuits — `sameRef` in\n * `create-grid-ui-core` still compares structurally, because a consumer may\n * hand in its own `{kind: \"header\"}` literal through `setFocus`.\n *\n * @internal Re-exported by `@pretable/core` as `ɵHEADER_FOCUS_REF`.\n */\nexport const HEADER_FOCUS_REF = Object.freeze({\n kind: \"header\",\n});\nfunction refOf(row) {\n return row.kind === \"data\"\n ? { kind: \"data\", rowId: row.rowId }\n : { kind: \"group\", groupId: row.groupId };\n}\nfunction emptyFocus() {\n return Object.freeze({\n ref: null,\n columnId: null,\n });\n}\nfunction focusAt(snapshot, index, columnId) {\n const row = snapshot.rowAt(index);\n return row === undefined\n ? undefined\n : Object.freeze({ ref: refOf(row), columnId });\n}\n/**\n * Where the cursor sits once `snapshot` has replaced the one it was placed\n * against.\n *\n * An absent focused row is TWO different situations, and the window is what\n * tells them apart — the same discriminator `reconcileIndexedSelection` uses,\n * reached through the same `provenDeletedRow`:\n *\n * - **Evicted** (absent, outside the loaded window): the row is coming back,\n * so the cursor is RETAINED. Re-seating here is what made a scroll away and\n * back move the user's cursor silently; Excel and AG Grid both keep it where\n * it was left and scroll it back into view. The spec's §5 rule — \"re-seat to\n * the nearest surviving row\" — was written before this distinction existed,\n * when an absent row could only mean a deleted one.\n * - **Deleted, hidden or unprovable-under-no-window** (absent from a span that\n * IS loaded): re-seat to the nearest survivor, exactly as before.\n *\n * With no window — local mode — this is byte-for-byte the pre-eviction\n * function: `retentionWindow` is null, so every absent row re-seats.\n */\nexport function reconcileIndexedFocus(focus, snapshot, eviction) {\n if (focus.ref === null || focus.columnId === null)\n return emptyFocus();\n // The header strip is not a row. The row model cannot evict it, delete it or\n // re-seat it, so a header cursor survives every snapshot byte-identical.\n // Falling through would be actively wrong rather than merely wasteful:\n // `indexOf` would report -1 for an address that is perfectly valid, and the\n // re-seat below would silently move the cursor onto a data row on the first\n // streaming patch.\n if (focus.ref.kind === \"header\")\n return focus;\n if (snapshot.indexOf(focus.ref) >= 0)\n return focus;\n // The window is unknown this revision, so this absence proves nothing — the\n // same verdict `reconcileIndexedSelection` reaches through the same\n // predicate, on the same revisions, which is the point of sharing it. A\n // group ref is excluded for the reason it is excluded below: it has no\n // dataset position, so no window could ever have said anything about it.\n if (focus.ref.kind === \"data\" && evictionWindowUnknown(eviction))\n return focus;\n const retentionWindow = evictionRetentionWindow(eviction);\n if (retentionWindow !== null &&\n // Group refs are not dataset rows: they have no data-only rank to convert\n // into a dataset position, so eviction can never be proven or disproven\n // for one. A collapsed or regrouped header re-seats to its ancestor as it\n // always did.\n focus.ref.kind === \"data\" &&\n !provenDeletedRow(focus.ref.rowId, retentionWindow, eviction?.previous)) {\n return focus;\n }\n const nearest = snapshot.nearestVisibleRef(focus.ref);\n if (nearest === undefined || snapshot.indexOf(nearest) < 0)\n return emptyFocus();\n return Object.freeze({ ref: nearest, columnId: focus.columnId });\n}\nexport function moveIndexedFocus(input) {\n const { snapshot, columns, movement } = input;\n if (columns.length === 0)\n return emptyFocus();\n // Reconciled FIRST, and WITH the eviction context, so every branch below\n // reasons about where the cursor actually is rather than where the caller\n // last saw it. In local mode this is the pre-eviction call verbatim: with no\n // window nothing is ever retained, so `current` is always either a loaded\n // row, the header, or nothing.\n const current = reconcileIndexedFocus(input.focus, snapshot, input.eviction);\n const headerColumnId = current.ref !== null &&\n current.ref.kind === \"header\" &&\n current.columnId !== null\n ? current.columnId\n : null;\n // Resolved ONCE and reused all the way down: this function is held to a\n // bounded number of row-model calls per keystroke, and a second `indexOf`\n // for the same address would break that budget.\n //\n // A negative answer for a ROW cursor means the row is not loaded and\n // reconciliation kept it anyway — it was EVICTED, and the row model is going\n // to get it back.\n const rowIndex = current.ref === null ||\n current.columnId === null ||\n current.ref.kind === \"header\"\n ? -1\n : snapshot.indexOf(current.ref);\n const unloadedCursor = current.ref !== null && current.ref.kind !== \"header\" && rowIndex < 0;\n // A grid with no rows still has a header, and a cursor already parked on it\n // stays there. Only the row-addressed cursors collapse — and not one held\n // over an evicted row, or releasing the whole window at once would drop the\n // cursor the moment the user pressed a key.\n if (snapshot.visibleRowCount === 0 &&\n headerColumnId === null &&\n !unloadedCursor)\n return emptyFocus();\n const lastColumnIndex = columns.length - 1;\n if (headerColumnId !== null) {\n const columnIndex = Math.max(0, columns.indexOf(headerColumnId));\n const onHeader = (index) => Object.freeze({\n ref: HEADER_FOCUS_REF,\n columnId: columns[Math.max(0, Math.min(lastColumnIndex, index))],\n });\n const intoBody = () => focusAt(snapshot, 0, headerColumnId) ?? onHeader(columnIndex);\n // Exhaustive on purpose, with no `default:`. Every movement in\n // `PretableIndexedFocusMovement` states what it does on a header cell here,\n // so adding a movement later is a compile error rather than a silent\n // fall-through onto a row-addressed code path that would call `indexOf`\n // with a header ref.\n switch (movement) {\n case \"left\":\n return onHeader(columnIndex - 1);\n case \"right\":\n return onHeader(columnIndex + 1);\n // The header is one row, so a vertical edge jump has nowhere to go and\n // the only edge it can mean is a column edge. `home` / `end` and the\n // explicitly horizontal pair therefore coincide here, and only here.\n case \"home\":\n case \"first-column\":\n return onHeader(0);\n case \"end\":\n case \"last-column\":\n return onHeader(lastColumnIndex);\n // The header is the top. `up` and `page-up` have nowhere further to go,\n // and consuming them is what stops an ArrowUp streak from popping focus\n // out of the grid entirely.\n case \"up\":\n case \"page-up\":\n return onHeader(columnIndex);\n // A header cell has no parent group — `parentGroupOf` would need a row.\n case \"parent\":\n return onHeader(columnIndex);\n case \"down\":\n case \"page-down\":\n return intoBody();\n // The header reads as the row above row 0 for a wrap walk: forward off\n // the last header column lands on the first body cell. Backward off the\n // first column returns unchanged, which is the same top-left corner\n // `shift-tab` already reports for row 0 — the surface releases there\n // rather than clamping, so this cannot become a keyboard trap.\n case \"tab\":\n return columnIndex === lastColumnIndex\n ? (focusAt(snapshot, 0, columns[0]) ?? onHeader(columnIndex))\n : onHeader(columnIndex + 1);\n case \"shift-tab\":\n return onHeader(columnIndex - 1);\n }\n }\n // Keyed off the CALLER's focus, not the reconciled one. \"No cursor at all\"\n // seeds a cursor at one corner of the grid; \"a cursor whose row is gone\"\n // clears it. Reconciliation turns the second into the first, so reading\n // `current` here would silently promote every absent cursor into a seed at\n // row 0 — the pre-eviction local-mode answer is `emptyFocus`, and it stays\n // that way.\n if (input.focus.ref === null || input.focus.columnId === null) {\n const reverseRow = movement === \"up\" || movement === \"end\" || movement === \"shift-tab\";\n const reverseColumn = movement === \"left\" ||\n movement === \"shift-tab\" ||\n movement === \"last-column\";\n return (focusAt(snapshot, reverseRow ? snapshot.visibleRowCount - 1 : 0, columns[reverseColumn ? lastColumnIndex : 0]) ?? emptyFocus());\n }\n // Reconciliation cleared a cursor the caller did supply: the row is gone and\n // there was no survivor to re-seat onto.\n if (current.ref === null || current.columnId === null)\n return current;\n // Unreachable in practice — the header block above returned for every header\n // cursor, and `reconcileIndexedFocus` cannot manufacture one. It is written\n // as a real branch rather than a cast so that the compiler narrows `ref` to a\n // ROW ref for the whole rest of this function: everything below indexes into\n // the row model, and an address the row model has never heard of must not be\n // able to reach it even if a future edit reorders these blocks.\n if (current.ref.kind === \"header\")\n return current;\n let columnIndex = columns.indexOf(current.columnId);\n if (columnIndex < 0)\n columnIndex = 0;\n // The two COLUMN-axis moves are answered before the row is required: they\n // read the column list and the cursor's own column, and neither needs to\n // know where the row sits — or whether it is loaded at all.\n if (movement === \"left\" || movement === \"right\") {\n const delta = movement === \"left\" ? -1 : 1;\n const nextColumn = columns[Math.max(0, Math.min(lastColumnIndex, columnIndex + delta))];\n return nextColumn === current.columnId\n ? current\n : Object.freeze({ ref: current.ref, columnId: nextColumn });\n }\n // The horizontal edges. Same row, opposite ends of it — the counterpart of\n // `home` / `end` below, which move along the other axis.\n if (movement === \"first-column\" || movement === \"last-column\") {\n const nextColumn = columns[movement === \"first-column\" ? 0 : lastColumnIndex];\n return nextColumn === current.columnId\n ? current\n : Object.freeze({ ref: current.ref, columnId: nextColumn });\n }\n // Everything past here reads the cursor's position AMONG THE LOADED ROWS,\n // and an evicted cursor has none.\n //\n // The move is REFUSED rather than redirected. The alternatives were: jump to\n // the nearest loaded row — which teleports the cursor across however many\n // rows were released, silently relocating a selection anchor the user set\n // deliberately; or move to the adjacent DATASET position and let the\n // consumer fetch it — which this state cannot even express, because\n // `PretableIndexedFocusRef` addresses a cursor by row identity and the\n // engine cannot name a row it has never loaded. Holding still keeps the\n // spec's guarantee that focus never falls to `<body>`, keeps the cursor\n // where the user left it, and leaves the positional-cursor question open\n // rather than answering it with a guess.\n //\n // In local mode this line is unreachable: with no window nothing is\n // retained, so `reconcileIndexedFocus` has already re-seated or cleared any\n // absent cursor and `rowIndex` cannot be negative here.\n if (rowIndex < 0)\n return current;\n if (movement === \"parent\") {\n const parent = snapshot.parentGroupOf(current.ref);\n return parent === undefined\n ? current\n : Object.freeze({\n ref: { kind: \"group\", groupId: parent.groupId },\n columnId: current.columnId,\n });\n }\n if (movement === \"tab\" || movement === \"shift-tab\") {\n const delta = movement === \"tab\" ? 1 : -1;\n if ((delta > 0 &&\n rowIndex === snapshot.visibleRowCount - 1 &&\n columnIndex === lastColumnIndex) ||\n (delta < 0 && rowIndex === 0 && columnIndex === 0)) {\n return current;\n }\n let nextRow = rowIndex;\n let nextColumn = columnIndex + delta;\n if (nextColumn > lastColumnIndex) {\n nextColumn = 0;\n nextRow += 1;\n }\n else if (nextColumn < 0) {\n nextColumn = lastColumnIndex;\n nextRow -= 1;\n }\n nextRow = Math.max(0, Math.min(snapshot.visibleRowCount - 1, nextRow));\n return focusAt(snapshot, nextRow, columns[nextColumn]) ?? current;\n }\n // Up off the first row lands on that column's HEADER cell, which is the only\n // way into the header now that its controls are out of the tab order. Before\n // this, ArrowUp on row 0 was a silent no-op.\n //\n // Deliberately `up` only. `page-up` still clamps at row 0: a page step is a\n // scroll-sized jump through rows, and having it fall off the top into a\n // single header cell would make \"page up twice\" mean two different things.\n if (movement === \"up\" && rowIndex === 0) {\n return Object.freeze({\n ref: HEADER_FOCUS_REF,\n columnId: current.columnId,\n });\n }\n const pageRows = Number.isSafeInteger(input.pageRows) && (input.pageRows ?? 0) > 0\n ? input.pageRows\n : 10;\n const nextRow = movement === \"home\"\n ? 0\n : movement === \"end\"\n ? snapshot.visibleRowCount - 1\n : Math.max(0, Math.min(snapshot.visibleRowCount - 1, rowIndex +\n (movement === \"up\"\n ? -1\n : movement === \"down\"\n ? 1\n : movement === \"page-up\"\n ? -pageRows\n : pageRows)));\n return nextRow === rowIndex\n ? current\n : (focusAt(snapshot, nextRow, current.columnId) ?? current);\n}\nexport function getScrollTopForIndexedFocus(input) {\n // The header is sticky: it is on screen at every scroll offset, so there is\n // nothing to reveal. `null` is this function's existing \"already resolved,\n // do not write a scrollTop\" answer — the same one an in-view row gets — and\n // is what stops a move onto the header from yanking the body to row 0.\n if (input.ref.kind === \"header\")\n return null;\n const targetIndex = input.snapshot.indexOf(input.ref);\n if (targetIndex < 0)\n return null;\n return scrollTopToReveal({\n rowMetrics: input.rowMetrics,\n targetIndex,\n scrollTop: input.scrollTop,\n viewportHeight: input.viewportHeight,\n });\n}\n","// The engine's stored default for a column that declares no `widthPx` —\n// layout-core's single source of truth, shared with renderer-dom's drawing\n// fallback so the stored width and the drawn width agree for a never-resized\n// column (see column-defaults.ts for the decision note).\nimport { DEFAULT_COLUMN_WIDTH_PX } from \"@pretable-internal/layout-core\";\nimport { moveIndexedFocus, reconcileIndexedFocus } from \"./indexed-focus\";\nimport { adoptIndexedCellRangeSpans, createEmptyIndexedSelection, createIndexedRowSelection, getIndexedCellSelectionSummary, getIndexedSelectionSummary, isIndexedRowSelected, preserveIndexedRowSelectionProgram, projectIndexedSelection, reconcileIndexedSelection, releaseIndexedRowSelectionProgram, sameIndexedRowSelectionProgram, sameIndexedRowSelectionValue, selectAllVisibleRows, selectIndexedRowRange, toImmutableIndexedSet, toggleIndexedRowSelection, } from \"./indexed-selection\";\nexport class PretableGridUiError extends Error {\n code;\n cause;\n constructor(code, message, cause) {\n super(message);\n this.name = \"PretableGridUiError\";\n this.code = code;\n this.cause = cause;\n }\n}\nconst EMPTY_VIEWPORT = Object.freeze({\n scrollTop: 0,\n scrollLeft: 0,\n height: 0,\n width: 0,\n});\nfunction sameValueZero(left, right) {\n return left === right || (left !== left && right !== right);\n}\nfunction sameRef(left, right) {\n if (left === right)\n return true;\n if (left === null || right === null || left.kind !== right.kind)\n return false;\n // Two header refs are the same address: the kind IS the whole address, since\n // the column lives on the focus state beside the ref. The compiler could not\n // have caught this one — the chain below is a boolean expression, not an\n // exhaustive switch, so a widened union just makes it silently return\n // `false` for every header/header pair. That would publish a \"changed\" focus\n // on every no-op `setFocus`, and re-render the surface on every arrow key\n // that did not actually move.\n if (left.kind === \"header\" && right.kind === \"header\")\n return true;\n return left.kind === \"data\" && right.kind === \"data\"\n ? sameValueZero(left.rowId, right.rowId)\n : left.kind === \"group\" &&\n right.kind === \"group\" &&\n left.groupId === right.groupId;\n}\nfunction sameViewport(left, right) {\n return (left.scrollTop === right.scrollTop &&\n left.scrollLeft === right.scrollLeft &&\n left.height === right.height &&\n left.width === right.width);\n}\nfunction normalizeViewport(viewport) {\n if (!Number.isFinite(viewport.scrollTop) ||\n !Number.isFinite(viewport.scrollLeft) ||\n !Number.isFinite(viewport.height) ||\n !Number.isFinite(viewport.width) ||\n viewport.height < 0 ||\n viewport.width < 0) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"Grid UI viewport values must be finite with non-negative dimensions.\");\n }\n return Object.freeze({ ...viewport });\n}\nfunction normalizeColumns(columns) {\n const ids = new Set();\n const normalized = columns.map((column) => {\n if (ids.has(column.id)) {\n throw new PretableGridUiError(\"invalid-ui-state\", `Duplicate visual column id: ${column.id}`);\n }\n const widthPx = column.widthPx ?? DEFAULT_COLUMN_WIDTH_PX;\n if (!Number.isFinite(widthPx) || widthPx <= 0) {\n throw new PretableGridUiError(\"invalid-ui-state\", `Visual column width must be positive for: ${column.id}`);\n }\n ids.add(column.id);\n return Object.freeze({\n id: column.id,\n widthPx,\n ...(column.pinned === undefined ? {} : { pinned: column.pinned }),\n // Strip-when-false, matching `setColumnVisible`: a visible entry never\n // carries the key, so the two ways of arriving at \"visible\" are\n // byte-identical.\n ...(column.hidden === true ? { hidden: true } : {}),\n });\n });\n return Object.freeze(orderPinnedColumns(normalized));\n}\nfunction orderPinnedColumns(columns) {\n return [\n ...columns.filter((column) => column.pinned === \"left\"),\n ...columns.filter((column) => column.pinned === undefined),\n ...columns.filter((column) => column.pinned === \"right\"),\n ];\n}\n/**\n * The still-visible column nearest to `hiddenIndex` in layout order: every\n * column to its left is tried first, nearest outward, then every column to\n * its right — `null` when every other column is hidden too.\n */\nfunction nearestVisibleColumnId(layout, hiddenIndex) {\n for (let index = hiddenIndex - 1; index >= 0; index -= 1) {\n if (layout[index].hidden !== true)\n return layout[index].id;\n }\n for (let index = hiddenIndex + 1; index < layout.length; index += 1) {\n if (layout[index].hidden !== true)\n return layout[index].id;\n }\n return null;\n}\nfunction copySelection(selection, \n/**\n * What this write replaces, plus the coordinates to express the result in.\n * A gesture hands over ranges built from row ids alone, so this is where\n * their dataset spans come from — see `adoptIndexedCellRangeSpans`. Absent\n * `loadedWindow` (local mode, the honesty gate not passing, or simply no\n * revision observed yet) is the pre-eviction path: no span is derived, and\n * one already present is carried through untouched rather than dropped,\n * because it is inert without a window and the window is legitimately\n * absent on the render that restores a persisted selection.\n */\ncontext) {\n const rows = selection.rows.kind === \"explicit\"\n ? Object.freeze({\n kind: \"explicit\",\n rowIds: toImmutableIndexedSet(selection.rows.rowIds),\n ...(selection.rows.ranges === undefined\n ? {}\n : { ranges: selection.rows.ranges }),\n ...(selection.rows.excludedRanges === undefined\n ? {}\n : { excludedRanges: selection.rows.excludedRanges }),\n })\n : Object.freeze({\n kind: \"all\",\n ...(selection.rows.excludedRanges === undefined\n ? {}\n : { excludedRanges: selection.rows.excludedRanges }),\n });\n preserveIndexedRowSelectionProgram(selection.rows, rows);\n return Object.freeze({\n rows,\n ranges: Object.freeze(adoptIndexedCellRangeSpans(selection.ranges.map((range) => Object.freeze({\n start: Object.freeze({ ...range.start }),\n end: Object.freeze({ ...range.end }),\n // Copied, not rebuilt from ids: this is the only public write\n // path, so dropping the span here un-counts every retained range\n // in the selection — including the ones the gesture never\n // touched.\n ...(range.datasetRowSpan === undefined\n ? {}\n : { datasetRowSpan: Object.freeze({ ...range.datasetRowSpan }) }),\n })), context.replaced, context.snapshot, context.loadedWindow)),\n anchor: selection.anchor === null ? null : Object.freeze({ ...selection.anchor }),\n });\n}\nfunction sameFocus(left, right) {\n return sameRef(left.ref, right.ref) && left.columnId === right.columnId;\n}\nfunction sameSet(left, right) {\n if (left.size !== right.size)\n return false;\n for (const value of left) {\n if (!right.has(value))\n return false;\n }\n return true;\n}\nfunction sameRowRanges(left, right) {\n if (left === right)\n return true;\n if (left?.size !== right?.size)\n return false;\n const leftIterator = left?.[Symbol.iterator]();\n const rightIterator = right?.[Symbol.iterator]();\n if (leftIterator === undefined || rightIterator === undefined)\n return false;\n for (;;) {\n const leftNext = leftIterator.next();\n const rightNext = rightIterator.next();\n if (leftNext.done || rightNext.done)\n return leftNext.done === rightNext.done;\n if (!sameValueZero(leftNext.value.startRowId, rightNext.value.startRowId) ||\n !sameValueZero(leftNext.value.endRowId, rightNext.value.endRowId))\n return false;\n }\n}\nfunction sameDatasetRowSpan(left, right) {\n if (left === right)\n return true;\n if (left === undefined || right === undefined)\n return false;\n return (left.start === right.start &&\n left.end === right.end &&\n left.datasetKey === right.datasetKey &&\n left.datasetTotal === right.datasetTotal);\n}\nfunction sameSelection(left, right) {\n if (left.rows.kind !== right.rows.kind)\n return false;\n if (!sameIndexedRowSelectionProgram(left.rows, right.rows))\n return false;\n let sameRows = false;\n if (left.rows.kind === \"explicit\" && right.rows.kind === \"explicit\") {\n const leftRows = left.rows;\n const rightRows = right.rows;\n sameRows =\n sameSet(leftRows.rowIds, rightRows.rowIds) &&\n sameRowRanges(leftRows.excludedRanges, rightRows.excludedRanges) &&\n sameRowRanges(leftRows.ranges, rightRows.ranges);\n }\n else if (left.rows.kind === \"all\" && right.rows.kind === \"all\") {\n sameRows = sameRowRanges(left.rows.excludedRanges, right.rows.excludedRanges);\n }\n if (!sameRows || left.ranges.length !== right.ranges.length)\n return false;\n for (let index = 0; index < left.ranges.length; index += 1) {\n const leftRange = left.ranges[index];\n const rightRange = right.ranges[index];\n if (!sameValueZero(leftRange.start.rowId, rightRange.start.rowId) ||\n leftRange.start.columnId !== rightRange.start.columnId ||\n !sameValueZero(leftRange.end.rowId, rightRange.end.rowId) ||\n leftRange.end.columnId !== rightRange.end.columnId ||\n // The span is part of a range's identity, not decoration on it: while\n // the rows are evicted it is the ONLY thing that says how large the\n // selection is, and two ranges over the same ids with different spans\n // select different numbers of rows. Comparing it is safe precisely\n // because `copySelection` recovers a missing span from the selection\n // being replaced — so a controlled `state` echo that drops the field\n // still compares equal, and the effect stays the no-op it has to be.\n !sameDatasetRowSpan(leftRange.datasetRowSpan, rightRange.datasetRowSpan)) {\n return false;\n }\n }\n if (left.anchor === null || right.anchor === null) {\n return left.anchor === right.anchor;\n }\n return (sameValueZero(left.anchor.rowId, right.anchor.rowId) &&\n left.anchor.columnId === right.anchor.columnId);\n}\n/**\n * Creates the framework-independent indexed UI store.\n *\n * @internal Re-exported by `@pretable/core` as `ɵcreateGridUiCore` for\n * `@pretable/react`, which must reach the engine through the same declaration\n * emission `@pretable/core` publishes rather than through this package\n * directly. See the note on that re-export in `packages/core/src/public_api.ts`.\n */\nexport function createGridUiCore(options) {\n const listeners = new Set();\n const queuedActions = [];\n const columnLayout = normalizeColumns(options.columns);\n const initialColumnIds = Object.freeze(columnLayout.map((column) => column.id));\n let cachedNavigationLayout = columnLayout;\n let cachedNavigationColumnIds = initialColumnIds;\n let disposed = false;\n let notifying = false;\n let draining = false;\n let projecting = false;\n let activeProjectionToken;\n // The snapshot as of the last successful reconciliation, paired with the\n // window that was active for it — a single binding rather than two `let`s\n // updated adjacently, so the pairing a later reconciliation converts\n // data-only ranks through (see `provenDeletedRow` in\n // `indexed-selection.ts`) cannot desynchronize.\n let observed;\n let state = Object.freeze({\n viewport: options.viewport\n ? normalizeViewport(options.viewport)\n : EMPTY_VIEWPORT,\n focus: Object.freeze({ ref: null, columnId: null }),\n selection: createEmptyIndexedSelection(),\n editing: null,\n columnLayout,\n // Absent, not `false`, when unsupplied — see the field's doc comment.\n ...(options.hideGroupedColumns === undefined\n ? {}\n : { hideGroupedColumns: options.hideGroupedColumns }),\n // Always present, and empty until a pane writes one: an absent key means\n // \"no override\", which an empty map already says. See the field's doc.\n columnAggregates: Object.freeze({}),\n observedRowModelRevision: null,\n });\n const assertActive = () => {\n if (disposed) {\n throw new PretableGridUiError(\"disposed-grid-ui\", \"The grid UI store has been disposed.\");\n }\n };\n const drain = () => {\n if (notifying || draining || projecting || disposed)\n return;\n draining = true;\n try {\n while (queuedActions.length > 0 && !disposed) {\n try {\n queuedActions.shift().action();\n }\n catch {\n // Reentrant commands have no synchronous error channel after listener return.\n }\n }\n }\n finally {\n draining = false;\n }\n };\n const notify = () => {\n notifying = true;\n try {\n for (const listener of Array.from(listeners)) {\n try {\n listener();\n }\n catch {\n // One external-store subscriber cannot block the remaining listeners.\n }\n }\n }\n finally {\n notifying = false;\n }\n drain();\n };\n const publish = (next) => {\n if (next === state)\n return;\n state = Object.freeze(next);\n notify();\n };\n const command = (action) => {\n assertActive();\n if (notifying || draining || projecting) {\n queuedActions.push({\n action,\n ...(projecting && activeProjectionToken !== undefined\n ? { projectionToken: activeProjectionToken }\n : {}),\n });\n return;\n }\n action();\n };\n const discardProjectionActions = (token) => {\n for (let index = queuedActions.length - 1; index >= 0; index -= 1) {\n if (queuedActions[index].projectionToken === token) {\n queuedActions.splice(index, 1);\n }\n }\n };\n const observationError = (message, cause) => cause instanceof PretableGridUiError &&\n cause.code === \"row-model-observation-failed\"\n ? cause\n : new PretableGridUiError(\"row-model-observation-failed\", message, cause);\n const snapshotForInteraction = () => {\n try {\n return observed?.snapshot ?? options.rowModel.getState().snapshot;\n }\n catch (cause) {\n throw new PretableGridUiError(\"row-model-observation-failed\", \"The row-model snapshot could not be read for a UI interaction.\", cause);\n }\n };\n /**\n * The snapshot an interaction must express dataset positions in, paired\n * with the window those positions are offsets into.\n *\n * Both come from `observed` — the single binding `observeRowModelRevision`\n * commits atomically — and never from a fresh `getSelectionWindow()` read\n * against a snapshot from some other moment. That combination is a\n * chimera, and it is not hypothetical: the react surface publishes the\n * window from `resultMeta` in an insertion effect, while the matching rows\n * reach the row model through `setRows`, which settles across cooperative\n * slices. In between, the window says \"the loaded rows start at 5\" and the\n * snapshot still holds the rows that start at 0 — so every loaded row\n * resolves to a position five rows too high, and a selection written in\n * that instant records a span five rows off, permanently.\n *\n * With nothing observed yet there is no committed pairing at all, so the\n * window is reported as absent rather than guessed: no span is derived,\n * which is exactly the pre-eviction behaviour.\n */\n const interactionContext = () => observed ?? {\n snapshot: snapshotForInteraction(),\n window: null,\n windowed: false,\n };\n const navigationColumnIds = () => {\n if (cachedNavigationLayout !== state.columnLayout) {\n cachedNavigationLayout = state.columnLayout;\n // Drawn columns only: keyboard movement over the full layout would let\n // an arrow key land focus on a hidden column — exactly the state\n // `setColumnVisible` repairs its way out of.\n cachedNavigationColumnIds = Object.freeze(state.columnLayout\n .filter((column) => column.hidden !== true)\n .map((column) => column.id));\n }\n return cachedNavigationColumnIds;\n };\n const performDispose = () => {\n if (disposed)\n return;\n disposed = true;\n activeProjectionToken = undefined;\n observed = undefined;\n releaseIndexedRowSelectionProgram(state.selection.rows);\n queuedActions.length = 0;\n const captured = Array.from(listeners);\n listeners.clear();\n for (const listener of captured) {\n try {\n listener();\n }\n catch {\n // Disposal still detaches every listener after a hostile callback.\n }\n }\n };\n const grid = {\n rowModel: options.rowModel,\n getState: () => state,\n subscribe(listener) {\n if (disposed)\n return () => undefined;\n listeners.add(listener);\n let active = true;\n return () => {\n if (!active)\n return;\n active = false;\n listeners.delete(listener);\n };\n },\n setViewport(viewport) {\n const next = normalizeViewport(viewport);\n command(() => {\n if (sameViewport(state.viewport, next))\n return;\n publish({ ...state, viewport: next });\n });\n },\n setFocus(focus) {\n const next = Object.freeze({\n ref: focus.ref === null ? null : Object.freeze({ ...focus.ref }),\n columnId: focus.columnId,\n });\n command(() => {\n if (sameFocus(state.focus, next))\n return;\n publish({ ...state, focus: next });\n });\n },\n moveFocus(movement, moveOptions) {\n command(() => {\n let next;\n try {\n const context = interactionContext();\n next = moveIndexedFocus({\n snapshot: context.snapshot,\n columns: navigationColumnIds(),\n focus: state.focus,\n movement,\n pageRows: moveOptions?.pageRows,\n // The same window the reconcile path judges absence against, so a\n // keystroke and a revision cannot disagree about whether the\n // cursor's row was evicted or deleted.\n //\n // No `previous`: the only committed snapshot/window pairing at\n // interaction time is this one, so nothing here could prove a\n // deletion anyway — and nothing needs to. A row deleted since the\n // last revision was already reconciled out of `state.focus` when\n // that revision was observed; what is left absent is either\n // evicted or an address a consumer handed to `setFocus`, and\n // holding the cursor is the right answer to both.\n eviction: { window: context.window, windowed: context.windowed },\n });\n }\n catch (cause) {\n throw observationError(\"Indexed focus navigation could not be completed atomically.\", cause);\n }\n if (sameFocus(state.focus, next))\n return;\n publish({ ...state, focus: next });\n });\n },\n setSelection(selection) {\n let next;\n try {\n const context = interactionContext();\n next = copySelection(selection, {\n replaced: state.selection.ranges,\n snapshot: context.snapshot,\n loadedWindow: context.window,\n });\n }\n catch (cause) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"The supplied selection could not be captured atomically.\", cause);\n }\n command(() => {\n if (sameSelection(state.selection, next))\n return;\n publish({ ...state, selection: next });\n });\n },\n setRowSelection(rows) {\n command(() => {\n let nextRows;\n try {\n nextRows = createIndexedRowSelection(rows, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"The supplied row selection could not be applied atomically.\", cause);\n }\n // Value equality, not `sameSelection`: a rebuilt slice never shares the\n // original's semantic program, so `sameSelection` would call every\n // re-application a change and a controlled caller pushing on each\n // render would publish forever.\n if (sameIndexedRowSelectionValue(state.selection.rows, nextRows))\n return;\n publish({\n ...state,\n selection: Object.freeze({ ...state.selection, rows: nextRows }),\n });\n });\n },\n toggleRowSelection(rowId) {\n command(() => {\n let next;\n try {\n next = toggleIndexedRowSelection(state.selection, rowId, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"Indexed selection could not be updated atomically.\", cause);\n }\n if (next === state.selection)\n return;\n publish({ ...state, selection: next });\n });\n },\n selectRowRange(startRowId, endRowId) {\n command(() => {\n let next;\n try {\n next = selectIndexedRowRange(state.selection, startRowId, endRowId, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"Indexed row range selection could not be updated atomically.\", cause);\n }\n if (next === state.selection)\n return;\n publish({ ...state, selection: next });\n });\n },\n isRowSelected(rowId) {\n try {\n return isIndexedRowSelected(state.selection, { kind: \"data\", rowId }, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"Indexed row selection could not be observed atomically.\", cause);\n }\n },\n getSelectionSummary() {\n try {\n return getIndexedSelectionSummary(state.selection, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"Indexed row selection summary could not be observed atomically.\", cause);\n }\n },\n getCellSelectionSummary() {\n try {\n const context = interactionContext();\n return getIndexedCellSelectionSummary(state.selection, context.snapshot, context.window);\n }\n catch (cause) {\n throw observationError(\"Indexed cell selection summary could not be observed atomically.\", cause);\n }\n },\n selectAllVisibleRows() {\n command(() => {\n let next;\n try {\n next = selectAllVisibleRows(state.selection, snapshotForInteraction());\n }\n catch (cause) {\n throw observationError(\"Indexed select-all could not be updated atomically.\", cause);\n }\n if (next === state.selection)\n return;\n publish({ ...state, selection: next });\n });\n },\n clearSelection() {\n command(() => {\n const next = createEmptyIndexedSelection();\n if (state.selection.rows.kind === \"explicit\" &&\n state.selection.rows.rowIds.size === 0 &&\n state.selection.ranges.length === 0 &&\n state.selection.anchor === null) {\n return;\n }\n publish({ ...state, selection: next });\n });\n },\n beginEdit(input) {\n const editing = Object.freeze({\n rowId: input.rowId,\n columnId: input.columnId,\n value: input.value,\n status: input.status ?? \"editing\",\n });\n command(() => {\n const snapshot = observed?.snapshot;\n let visible = false;\n try {\n visible =\n snapshot !== undefined &&\n snapshot.indexOf({ kind: \"data\", rowId: input.rowId }) >= 0;\n }\n catch (cause) {\n throw observationError(\"The edit target could not be resolved atomically.\", cause);\n }\n // Widened to `string` by assignment (not asserted): `TEditColumnId`\n // ranges over the SCHEMA ids and `columnLayout` over the DRAWN ones,\n // and the question being asked is precisely whether this schema\n // column is among the drawn ones — which no relation between the two\n // parameters can answer, because a presentation layer is free to omit\n // a schema column. So it is answered at runtime, over the one\n // vocabulary both sides provably share.\n const editColumnId = input.columnId;\n if (!visible ||\n !state.columnLayout.some(\n // A hidden column has no cell on screen to host an editor, so it\n // is no more editable than a column outside the layout.\n (column) => column.id === editColumnId && column.hidden !== true)) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"Editing requires a visible data row and visual column from the observed layout.\");\n }\n publish({ ...state, editing });\n });\n },\n setEditDraft(value) {\n command(() => {\n if (state.editing === null || Object.is(state.editing.value, value))\n return;\n publish({\n ...state,\n editing: Object.freeze({\n ...state.editing,\n value,\n status: \"editing\",\n error: undefined,\n }),\n });\n });\n },\n setEditStatus(status, error) {\n command(() => {\n if (state.editing === null)\n return;\n if (state.editing.status === status && state.editing.error === error)\n return;\n publish({\n ...state,\n editing: Object.freeze({\n ...state.editing,\n status,\n ...(error === undefined ? { error: undefined } : { error }),\n }),\n });\n });\n },\n cancelEdit() {\n command(() => {\n if (state.editing === null)\n return;\n publish({ ...state, editing: null });\n });\n },\n setColumns(columns) {\n const nextLayout = normalizeColumns(columns);\n command(() => {\n const same = nextLayout.length === state.columnLayout.length &&\n nextLayout.every((column, index) => {\n const current = state.columnLayout[index];\n return (current?.id === column.id &&\n current.widthPx === column.widthPx &&\n current.pinned === column.pinned &&\n current.hidden === column.hidden);\n });\n if (same)\n return;\n // `Set<string>`, not `Set<TColumnId>`: `editing.columnId` below is a\n // SCHEMA id, and the drawn vocabulary is a different parameter, so\n // membership is answerable only over `string`. This set is LAYOUT\n // membership — hidden entries included — which is what focus and\n // selection repair against; editing repairs against the stricter\n // drawn set below.\n const ids = new Set(nextLayout.map((column) => column.id));\n const focus = state.focus.columnId === null || ids.has(state.focus.columnId)\n ? state.focus\n : Object.freeze({ ref: null, columnId: null });\n const ranges = state.selection.ranges.filter((range) => ids.has(range.start.columnId) && ids.has(range.end.columnId));\n const anchor = state.selection.anchor !== null &&\n ids.has(state.selection.anchor.columnId)\n ? state.selection.anchor\n : null;\n const selection = ranges === state.selection.ranges && anchor === state.selection.anchor\n ? state.selection\n : Object.freeze({ ...state.selection, ranges, anchor });\n // Editing is stricter than focus and selection: `beginEdit` demands a\n // DRAWN column, so a column the incoming config hides cancels the\n // session exactly like one it removes — the same repair\n // `setColumnVisible` applies.\n const drawnIds = new Set(nextLayout.flatMap((column) => column.hidden === true ? [] : [column.id]));\n // Overrides for columns this config drops go with them. Not because\n // they would be unreachable — re-adding the column reaches them again\n // — but because that is the hazard: a stale override would silently\n // resurrect the moment the column came back, with no user action in\n // between. `ids`, so a column merely marked `hidden` keeps its\n // override; it is still in the layout, like its width and pin.\n const retainedAggregates = Object.fromEntries(Object.entries(state.columnAggregates).filter(([id]) => ids.has(id)));\n // Reuse the existing object when nothing was pruned. `setColumns`\n // publishes regardless (`columnLayout` changed), so this branch buys\n // nothing but referential stability — which is the whole input to a\n // downstream memo over the overrides.\n const columnAggregates = Object.keys(retainedAggregates).length ===\n Object.keys(state.columnAggregates).length\n ? state.columnAggregates\n : Object.freeze(retainedAggregates);\n publish({\n ...state,\n columnLayout: nextLayout,\n columnAggregates,\n focus,\n selection,\n editing: state.editing !== null && drawnIds.has(state.editing.columnId)\n ? state.editing\n : null,\n });\n });\n },\n setColumnWidth(columnId, width) {\n if (!Number.isFinite(width) || width <= 0) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"Visual column width must be positive.\");\n }\n command(() => {\n const index = state.columnLayout.findIndex((column) => column.id === columnId);\n if (index < 0 || state.columnLayout[index].widthPx === width)\n return;\n const next = state.columnLayout.slice();\n next[index] = Object.freeze({ ...next[index], widthPx: width });\n publish({\n ...state,\n columnLayout: Object.freeze(orderPinnedColumns(next)),\n });\n });\n },\n setColumnPinned(columnId, pinned) {\n command(() => {\n const index = state.columnLayout.findIndex((column) => column.id === columnId);\n const current = state.columnLayout[index];\n if (current === undefined || (current.pinned ?? null) === pinned)\n return;\n const next = state.columnLayout.slice();\n // Clearing rebuilds the entry to strip `pinned` (never writes\n // `pinned: undefined`), but every OTHER optional key must survive the\n // rebuild — unpinning a hidden column must not reveal it.\n next[index] = Object.freeze(pinned === null\n ? {\n id: current.id,\n widthPx: current.widthPx,\n ...(current.hidden === true ? { hidden: true } : {}),\n }\n : { ...current, pinned });\n publish({\n ...state,\n columnLayout: Object.freeze(orderPinnedColumns(next)),\n });\n });\n },\n setColumnVisible(columnId, visible) {\n command(() => {\n const index = state.columnLayout.findIndex((column) => column.id === columnId);\n const current = state.columnLayout[index];\n if (current === undefined || (current.hidden !== true) === visible)\n return;\n const next = state.columnLayout.slice();\n next[index] = Object.freeze(visible\n ? {\n id: current.id,\n widthPx: current.widthPx,\n ...(current.pinned === undefined\n ? {}\n : { pinned: current.pinned }),\n }\n : { ...current, hidden: true });\n // Visibility does not reorder — hidden entries hold their place so\n // re-showing restores it — so `orderPinnedColumns` need not re-run.\n const columnLayout = Object.freeze(next);\n if (visible) {\n publish({ ...state, columnLayout });\n return;\n }\n // The cursor and the anchor cannot keep addressing a hidden column:\n // re-seat each onto the nearest still-visible neighbor in layout\n // order, left first, then right — inside this same command so the\n // layout change and its repairs publish as one wake.\n const neighbor = nearestVisibleColumnId(next, index);\n const focus = state.focus.columnId !== columnId\n ? state.focus\n : neighbor === null\n ? Object.freeze({ ref: null, columnId: null })\n : Object.freeze({ ref: state.focus.ref, columnId: neighbor });\n const anchor = state.selection.anchor !== null &&\n state.selection.anchor.columnId === columnId\n ? neighbor === null\n ? null\n : Object.freeze({ ...state.selection.anchor, columnId: neighbor })\n : state.selection.anchor;\n const selection = anchor === state.selection.anchor\n ? state.selection\n : Object.freeze({ ...state.selection, anchor });\n // An open edit session on the hidden column loses its cell, so it is\n // cancelled — the same repair `setColumns` applies when the edited\n // column leaves the layout entirely.\n const editing = state.editing !== null &&\n state.editing.columnId === columnId\n ? null\n : state.editing;\n publish({ ...state, columnLayout, focus, selection, editing });\n });\n },\n setColumnOrder(nextColumnIds) {\n command(() => {\n if (nextColumnIds.length !== state.columnLayout.length) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"Column order must contain every column in the layout, hidden included, exactly once.\");\n }\n const byId = new Map(state.columnLayout.map((column) => [column.id, column]));\n const next = nextColumnIds.map((columnId) => {\n const column = byId.get(columnId);\n if (column === undefined) {\n throw new PretableGridUiError(\"invalid-ui-state\", `Unknown or repeated visual column id: ${columnId}`);\n }\n byId.delete(columnId);\n return column;\n });\n if (byId.size > 0) {\n throw new PretableGridUiError(\"invalid-ui-state\", \"Column order must contain every column in the layout, hidden included, exactly once.\");\n }\n const ordered = orderPinnedColumns(next);\n if (ordered.every((column, index) => column === state.columnLayout[index]))\n return;\n publish({ ...state, columnLayout: Object.freeze(ordered) });\n });\n },\n setHideGroupedColumns(value) {\n command(() => {\n if (state.hideGroupedColumns === value)\n return;\n publish({ ...state, hideGroupedColumns: value });\n });\n },\n setColumnAggregate(columnId, aggregate) {\n command(() => {\n // LAYOUT membership, hidden entries included — not the drawn set: a\n // hidden column takes an override exactly as it takes a width or a\n // pin. An id the layout does not hold at all is a no-op, matching\n // `setColumnPinned`/`setColumnWidth`: an override is not geometry, but\n // one recorded for an id the layout never holds has nothing to evict\n // it.\n if (!state.columnLayout.some((column) => column.id === columnId))\n return;\n const present = columnId in state.columnAggregates;\n if (aggregate === undefined) {\n // Strip-when-clearing, never `{ [columnId]: undefined }`: a present\n // key is what marks a column as pane-chosen, so writing the key back\n // as undefined would pin the column to \"no aggregate\" instead of\n // returning it to the one declared on the prop.\n if (!present)\n return;\n const next = { ...state.columnAggregates };\n delete next[columnId];\n publish({ ...state, columnAggregates: Object.freeze(next) });\n return;\n }\n // No `present &&` guard: `aggregate` is non-`undefined` here, so a\n // matching `===` already implies the key is present.\n if (state.columnAggregates[columnId] === aggregate)\n return;\n publish({\n ...state,\n columnAggregates: Object.freeze({\n ...state.columnAggregates,\n [columnId]: aggregate,\n }),\n });\n });\n },\n observeRowModelRevision(revision) {\n command(() => {\n const token = {};\n activeProjectionToken = token;\n projecting = true;\n let committed = false;\n try {\n const modelState = options.rowModel.getState();\n const snapshot = modelState.snapshot;\n const capturedRevision = snapshot.revision;\n if (!Number.isSafeInteger(capturedRevision) || capturedRevision < 0) {\n throw new TypeError(\"The row-model snapshot revision must be a non-negative safe integer.\");\n }\n if (capturedRevision !== revision ||\n state.observedRowModelRevision === revision) {\n return;\n }\n // ONE read of the window channel per revision, into one object:\n // windowed-ness and the window itself must describe the same\n // instant or the engine can conclude \"local mode\" from a windowed\n // grid's momentary gate closure.\n const windowing = options.getWindowing?.() ?? null;\n const selectionWindow = windowing?.window ?? null;\n // `observed` is read here, before the sole reassignment below (at\n // the end of this same block, after every read), so it still\n // holds the snapshot/window pairing from the LAST successful\n // commit — the only pairing a data-only rank recorded against\n // `observed.snapshot` is valid for.\n //\n // The cursor and the selection are handed the SAME context, from\n // the same two reads: they have to reach the same verdict about a\n // row, or a grid retains a selection under a cursor that moved.\n const eviction = {\n window: selectionWindow,\n windowed: windowing !== null,\n previous: observed,\n };\n const focus = reconcileIndexedFocus(state.focus, snapshot, eviction);\n const selection = reconcileIndexedSelection(observed === undefined\n ? state.selection\n : projectIndexedSelection(state.selection, observed.snapshot, snapshot, options.rowModel.changesSince(observed.snapshot.revision)), snapshot, eviction);\n let editing = state.editing;\n if (editing !== null &&\n snapshot.indexOf({ kind: \"data\", rowId: editing.rowId }) < 0) {\n editing = null;\n }\n if (disposed || activeProjectionToken !== token)\n return;\n const currentModelState = options.rowModel.getState();\n const currentSnapshot = currentModelState.snapshot;\n const currentRevision = currentSnapshot.revision;\n if (currentSnapshot !== snapshot ||\n currentRevision !== capturedRevision ||\n currentRevision !== revision) {\n throw new Error(\"The row-model snapshot changed during atomic UI reconciliation.\");\n }\n if (disposed || activeProjectionToken !== token)\n return;\n observed = {\n snapshot,\n window: selectionWindow,\n windowed: windowing !== null,\n };\n committed = true;\n publish({\n ...state,\n focus,\n selection,\n editing,\n observedRowModelRevision: revision,\n });\n }\n catch (cause) {\n if (disposed || activeProjectionToken !== token)\n return;\n throw observationError(\"The row-model revision could not be observed atomically.\", cause);\n }\n finally {\n if (!committed)\n discardProjectionActions(token);\n if (activeProjectionToken === token) {\n activeProjectionToken = undefined;\n }\n projecting = false;\n drain();\n }\n });\n },\n dispose() {\n if (disposed)\n return;\n if (projecting && !notifying) {\n performDispose();\n return;\n }\n if (notifying || draining) {\n queuedActions.push({ action: performDispose });\n return;\n }\n performDispose();\n },\n };\n return grid;\n}\n","/** Id of the synthetic visual column that carries grouped row labels. @public */\nexport const GROUP_COLUMN_ID = \"__pretable_group__\";\n","import { createGridUiCore } from \"@pretable-internal/grid-core\";\nimport type {\n CreateGridUiCoreOptions,\n PretableGridUiCore,\n} from \"@pretable-internal/grid-core\";\nimport type { PretableRowId } from \"@pretable-internal/row-model\";\n\n/**\n * Create a framework-independent UI-state grid over an explicit indexed row\n * model. Data, queries, grouping, aggregation, and expansion remain owned by\n * `rowModel`; this handle owns only focus, selection, editing, viewport, and\n * visual column layout.\n *\n * @public\n */\nexport function createGrid<\n TRow extends object,\n TRowId extends PretableRowId,\n TColumns,\n>(\n options: CreateGridUiCoreOptions<TRow, TRowId, TColumns>,\n): PretableGridUiCore<TRow, TRowId, TColumns> {\n return createGridUiCore(options);\n}\n","/** @public */\nexport function createColumnHelper() {\n return {\n accessor(id, accessorOrOptions, maybeOptions) {\n const isFunctionAccessor = typeof accessorOrOptions === \"function\";\n const accessor = isFunctionAccessor\n ? accessorOrOptions\n : (row) => row[id];\n const options = isFunctionAccessor ? maybeOptions : accessorOrOptions;\n return {\n ...options,\n id,\n accessorKey: isFunctionAccessor\n ? undefined\n : id,\n accessor,\n value: accessor,\n };\n },\n };\n}\n/**\n * Narrows one filter-tree node to a group. Checked positively on the group's\n * own fields, so an unknown shape fails closed rather than being treated as a\n * branch with no children.\n * @public\n */\nexport function isPretableFilterGroup(node) {\n return (typeof node === \"object\" &&\n node !== null &&\n \"children\" in node &&\n (node.op === \"and\" ||\n node.op === \"or\"));\n}\n","export const MIN_DATE_VALUE = \"0000-01-01\";\nexport const MAX_DATE_VALUE = \"9999-12-31\";\nconst DATE_VALUE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst MS_PER_DAY = 86_400_000;\nconst DAYS_PER_GREGORIAN_CYCLE = 146_097;\nconst MAX_YEAR = 9_999;\nconst MONTHS_PER_YEAR = 12;\nconst MAX_MONTH_INDEX = MAX_YEAR * MONTHS_PER_YEAR + 11;\nconst ASCII_ZERO = 48;\nconst ASCII_NINE = 57;\nconst ASCII_HYPHEN = 45;\nconst isLeapYear = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\nconst getDaysInMonth = (year, month) => {\n if (month === 2)\n return isLeapYear(year) ? 29 : 28;\n if (month === 4 || month === 6 || month === 9 || month === 11)\n return 30;\n return 31;\n};\nconst isAsciiDigitAt = (value, index) => {\n const code = value.charCodeAt(index);\n return code >= ASCII_ZERO && code <= ASCII_NINE;\n};\nconst hasDateValueShape = (value) => value.length === 10 &&\n isAsciiDigitAt(value, 0) &&\n isAsciiDigitAt(value, 1) &&\n isAsciiDigitAt(value, 2) &&\n isAsciiDigitAt(value, 3) &&\n value.charCodeAt(4) === ASCII_HYPHEN &&\n isAsciiDigitAt(value, 5) &&\n isAsciiDigitAt(value, 6) &&\n value.charCodeAt(7) === ASCII_HYPHEN &&\n isAsciiDigitAt(value, 8) &&\n isAsciiDigitAt(value, 9);\nconst readTwoDigits = (value, offset) => (value.charCodeAt(offset) - ASCII_ZERO) * 10 +\n value.charCodeAt(offset + 1) -\n ASCII_ZERO;\nconst readFourDigits = (value) => (value.charCodeAt(0) - ASCII_ZERO) * 1_000 +\n (value.charCodeAt(1) - ASCII_ZERO) * 100 +\n (value.charCodeAt(2) - ASCII_ZERO) * 10 +\n value.charCodeAt(3) -\n ASCII_ZERO;\nconst hasValidDateParts = (year, month, day) => month >= 1 && month <= 12 && day >= 1 && day <= getDaysInMonth(year, month);\nconst formatDateValue = (year, month, day) => `${year.toString().padStart(4, \"0\")}-${month\n .toString()\n .padStart(2, \"0\")}-${day.toString().padStart(2, \"0\")}`;\nexport function parseDateValue(value) {\n if (typeof value !== \"string\")\n return null;\n const match = DATE_VALUE_PATTERN.exec(value);\n if (match === null)\n return null;\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n if (!hasValidDateParts(year, month, day))\n return null;\n return { year, month, day };\n}\n/** @public */\nexport function isValidDateValue(value) {\n if (typeof value !== \"string\" || !hasDateValueShape(value))\n return false;\n const year = readFourDigits(value);\n const month = readTwoDigits(value, 5);\n const day = readTwoDigits(value, 8);\n return hasValidDateParts(year, month, day);\n}\nexport function dateValueToUtcMs(value) {\n if (typeof value !== \"string\" || !hasDateValueShape(value)) {\n return Number.NaN;\n }\n const year = readFourDigits(value);\n const month = readTwoDigits(value, 5);\n const day = readTwoDigits(value, 8);\n if (!hasValidDateParts(year, month, day))\n return Number.NaN;\n if (year < 100) {\n return (Date.UTC(year + 400, month - 1, day) -\n DAYS_PER_GREGORIAN_CYCLE * MS_PER_DAY);\n }\n return Date.UTC(year, month - 1, day);\n}\nexport function compareDateValues(left, right) {\n if (left < right)\n return -1;\n if (left > right)\n return 1;\n return 0;\n}\nexport function addDateValueDays(value, days) {\n const timestamp = dateValueToUtcMs(value);\n if (Number.isNaN(timestamp) || Number.isNaN(days))\n return value;\n const wholeDays = Math.trunc(days);\n const minimumTimestamp = dateValueToUtcMs(MIN_DATE_VALUE);\n const maximumTimestamp = dateValueToUtcMs(MAX_DATE_VALUE);\n const destinationTimestamp = timestamp + wholeDays * MS_PER_DAY;\n if (destinationTimestamp <= minimumTimestamp)\n return MIN_DATE_VALUE;\n if (destinationTimestamp >= maximumTimestamp)\n return MAX_DATE_VALUE;\n const destination = new Date(destinationTimestamp);\n return formatDateValue(destination.getUTCFullYear(), destination.getUTCMonth() + 1, destination.getUTCDate());\n}\nexport function addDateValueMonths(value, months) {\n const parsed = parseDateValue(value);\n if (parsed === null || Number.isNaN(months))\n return value;\n const destinationMonthIndex = parsed.year * MONTHS_PER_YEAR + parsed.month - 1 + Math.trunc(months);\n if (destinationMonthIndex < 0)\n return MIN_DATE_VALUE;\n if (destinationMonthIndex > MAX_MONTH_INDEX)\n return MAX_DATE_VALUE;\n const year = Math.floor(destinationMonthIndex / MONTHS_PER_YEAR);\n const month = (destinationMonthIndex % MONTHS_PER_YEAR) + 1;\n const day = Math.min(parsed.day, getDaysInMonth(year, month));\n return formatDateValue(year, month, day);\n}\n","import { isValidDateValue } from \"@pretable-internal/calendar-date\";\nfunction calendarDateExtremum(kind) {\n return Object.freeze({\n init: () => null,\n accumulate: (accumulator, value) => {\n if (!isValidDateValue(value))\n return accumulator;\n if (accumulator === null)\n return value;\n return kind === \"min\"\n ? value < accumulator\n ? value\n : accumulator\n : value > accumulator\n ? value\n : accumulator;\n },\n merge: (left, right) => {\n if (left === null)\n return right;\n if (right === null)\n return left;\n return kind === \"min\"\n ? left < right\n ? left\n : right\n : left > right\n ? left\n : right;\n },\n finalize: (accumulator) => accumulator,\n });\n}\nconst calendarDateMin = calendarDateExtremum(\"min\");\nconst calendarDateMax = calendarDateExtremum(\"max\");\nexport function lowerCalendarDateAggregate(columnType, aggregate) {\n if (columnType !== \"date\")\n return aggregate;\n if (aggregate === \"min\") {\n return calendarDateMin;\n }\n if (aggregate === \"max\") {\n return calendarDateMax;\n }\n return aggregate;\n}\nexport function isCalendarDateAggregate(aggregate) {\n return aggregate === calendarDateMin || aggregate === calendarDateMax;\n}\n","/** @public */\nexport class PretableRowModelError extends Error {\n name = \"PretableRowModelError\";\n code;\n operation;\n rowId;\n columnId;\n constructor(code, message, context) {\n super(message, { cause: context.cause });\n this.code = code;\n this.operation = context.operation;\n this.rowId = context.rowId;\n this.columnId = context.columnId;\n }\n}\n/** @public */\nexport class PretableDisposedModelError extends PretableRowModelError {\n name = \"PretableDisposedModelError\";\n constructor(operation) {\n super(\"disposed-model\", \"The row model has been disposed.\", { operation });\n }\n}\n/** @public */\nexport class PretableReentrantMutationError extends PretableRowModelError {\n activeOperation;\n name = \"PretableReentrantMutationError\";\n constructor(operation, activeOperation) {\n super(\"reentrant-mutation\", `Cannot run ${operation} while ${activeOperation} is preparing an atomic publication.`, { operation });\n this.activeOperation = activeOperation;\n }\n}\n/** Finds a nested guard failure through structured callback-error causes. */\nexport function findPretableReentrantMutationError(error) {\n const visited = new Set();\n let current = error;\n while (current !== null && typeof current === \"object\") {\n if (current instanceof PretableReentrantMutationError)\n return current;\n if (visited.has(current))\n return undefined;\n visited.add(current);\n current = \"cause\" in current ? current.cause : undefined;\n }\n return undefined;\n}\n/** @public */\nexport class PretableRowIdentityChangeError extends PretableRowModelError {\n nextRowId;\n name = \"PretableRowIdentityChangeError\";\n constructor(rowId, nextRowId, cause) {\n super(\"row-identity-change\", `An update for row ${String(rowId)} changed its configured identity.`, { operation: \"apply-transaction\", rowId, cause });\n this.nextRowId = nextRowId;\n }\n}\n/** @public */\nexport class PretableUnsupportedRowUpdateError extends PretableRowModelError {\n name = \"PretableUnsupportedRowUpdateError\";\n constructor(rowId, cause) {\n super(\"unsupported-row-update\", \"Partial updates require an ordinary object or null-prototype record; replace class and exotic rows with setRows instead.\", { operation: \"apply-transaction\", rowId, cause });\n }\n}\n/** @public */\nexport class PretableInvalidGroupKeyError extends PretableRowModelError {\n value;\n name = \"PretableInvalidGroupKeyError\";\n constructor(operation, rowId, columnId, value, cause = new TypeError(\"Group keys must be strings, numbers, bigints, booleans, null, or undefined.\")) {\n super(\"invalid-group-key\", `Column ${columnId} produced an unsupported group key.`, { operation, rowId, columnId, cause });\n this.value = value;\n }\n}\n/** Runtime complement to the wholly-assignable `PretableRowGroupFor` check. */\nexport function isPretableGroupKey(value) {\n if (value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n typeof value === \"boolean\") {\n return true;\n }\n return false;\n}\n/** @public */\nexport class PretableTransitionCancelledError extends Error {\n transitionId;\n reason;\n name = \"PretableTransitionCancelledError\";\n constructor(transitionId, reason) {\n super(`Row-model transition ${transitionId} was ${reason}.`);\n this.transitionId = transitionId;\n this.reason = reason;\n }\n}\n","function isRuntimeFilterGroup(node) {\n return \"children\" in node;\n}\nfunction readDateTimestamp(value) {\n try {\n return Date.prototype.getTime.call(value);\n }\n catch {\n return undefined;\n }\n}\nexport function isPlainObject(value) {\n if (value === null || typeof value !== \"object\")\n return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\nexport function semanticValueEqual(left, right) {\n if (Object.is(left, right))\n return true;\n if (Array.isArray(left) && Array.isArray(right)) {\n return (left.length === right.length &&\n left.every((value, index) => semanticValueEqual(value, right[index])));\n }\n if (left instanceof Date && right instanceof Date) {\n return Object.is(readDateTimestamp(left), readDateTimestamp(right));\n }\n if (isPlainObject(left) && isPlainObject(right)) {\n const leftKeys = Object.keys(left).sort();\n const rightKeys = Object.keys(right).sort();\n return (leftKeys.length === rightKeys.length &&\n leftKeys.every((key, index) => key === rightKeys[index] && semanticValueEqual(left[key], right[key])));\n }\n return false;\n}\nexport function orderingEqual(left, right) {\n return (left.length === right.length &&\n left.every((entry, index) => entry.columnId === right[index]?.columnId &&\n (entry.direction ?? \"asc\") === (right[index]?.direction ?? \"asc\") &&\n (entry.nulls ?? \"last\") === (right[index]?.nulls ?? \"last\")));\n}\nfunction filterNodeEqual(left, right) {\n if (isRuntimeFilterGroup(left) || isRuntimeFilterGroup(right)) {\n return (isRuntimeFilterGroup(left) &&\n isRuntimeFilterGroup(right) &&\n left.op === right.op &&\n filterNodeListEqual(left.children, right.children));\n }\n return (left.columnId === right.columnId &&\n left.operator === right.operator &&\n semanticValueEqual(left.value, right.value));\n}\nexport function filterNodeListEqual(left, right) {\n if (left.length !== right.length)\n return false;\n const used = new Set();\n return left.every((filter) => {\n const index = right.findIndex((candidate, candidateIndex) => !used.has(candidateIndex) && filterNodeEqual(filter, candidate));\n if (index < 0)\n return false;\n used.add(index);\n return true;\n });\n}\nexport function queryEqual(left, right) {\n return (filterNodeListEqual(left.filters, right.filters) &&\n orderingEqual(left.sort, right.sort) &&\n orderingEqual(left.rowGroups, right.rowGroups));\n}\n/** @internal Shared semantic query identity for renderer authority decisions. */\nexport function ɵqueriesSemanticallyEqual(left, right) {\n return queryEqual(left, right);\n}\n","import { compareDateValues, isValidDateValue, } from \"@pretable-internal/calendar-date\";\nimport { lowerCalendarDateAggregate } from \"./calendar-date-aggregates\";\nimport { PretableRowModelError } from \"./errors\";\nimport { filterNodeListEqual, isPlainObject, orderingEqual, queryEqual, semanticValueEqual, } from \"./query-equality\";\nexport class CompiledQueryValidationError extends TypeError {\n detail;\n path;\n columnId;\n name = \"CompiledQueryValidationError\";\n code = \"invalid-query\";\n constructor(detail, path, columnId, options) {\n super(`Invalid compiled query at ${path}: ${detail}`, options);\n this.detail = detail;\n this.path = path;\n this.columnId = columnId;\n }\n}\nexport class CompiledQueryComparatorError extends PretableRowModelError {\n rowIds;\n name = \"CompiledQueryComparatorError\";\n groupValues;\n constructor(message, rowIds, context) {\n super(\"comparator-failed\", message, {\n operation: context.operation ?? \"set-query\",\n rowId: rowIds?.[0],\n columnId: context.columnId,\n cause: context.cause,\n });\n this.rowIds = rowIds;\n this.groupValues = context.groupValues;\n }\n}\n/**\n * The internal twin of `isPretableFilterGroup`, deliberately WEAKER: the\n * public guard re-checks `op` because it runs on whatever a caller hands it,\n * whereas capture has already rejected any node carrying `children` without a\n * valid `op`. Over a captured tree the presence of `children` is therefore\n * decisive on its own. Never call this on un-captured input.\n */\nfunction isRuntimeFilterGroup(node) {\n return \"children\" in node;\n}\n/**\n * The leaves of a filter tree, in depth-first order — the tree's COLUMN\n * DEPENDENCY set, flattened deliberately. Join operators are irrelevant here:\n * a column is read if any leaf anywhere in the tree mentions it, whatever\n * joins that leaf to its siblings. Evaluation does NOT go through this — see\n * `compileFilterNodes`.\n */\nfunction filterLeavesOf(nodes) {\n const leaves = [];\n const visit = (node) => {\n if (isRuntimeFilterGroup(node))\n node.children.forEach(visit);\n else\n leaves.push(node);\n };\n nodes.forEach(visit);\n return leaves;\n}\n/*\n * Its own const rather than the `FilterPredicate` twin a thousand lines down:\n * the two are structurally identical and tsc would accept either, but a\n * predicate answers about a VALUE and a matcher about a ROW, and borrowing\n * one for the other is a pun a reader has to unpick.\n */\nconst alwaysMatches = () => true;\n/**\n * Compiles a sibling list joined by `op` into a single matcher. Used for\n * groups and for the query's root list alike — the roots are an `and`, which\n * is exactly what a top-level filter list has always meant.\n *\n * The join loops are indexed rather than `every`/`some`, which is not a style\n * preference: a callback join allocates a closure per group PER ROW, on the\n * hottest loop in the package. Deliberately unquantified — two harnesses\n * measured the gap differently enough to disagree, and a figure pasted here\n * would rot where no reader could re-derive it. Measure it yourself on an\n * isolated verdict loop; a whole-model benchmark cannot resolve it.\n *\n * Both operators are written once here, so there is one implementation of\n * `and` and one of `or` whatever shape the tree has.\n */\nfunction compileFilterNodes(nodes, op, byId) {\n /*\n * An EMPTY list is TRUE under BOTH joins — it constrains nothing, so it\n * removes nothing. The branch is not decoration: the `or` loop below falls\n * through to `false` on no children, which would make a half-built `or`\n * group in a builder UI blank the grid the instant a user adds it and\n * before they fill it in.\n */\n if (nodes.length === 0)\n return alwaysMatches;\n const matchers = nodes.map((node) => {\n if (isRuntimeFilterGroup(node))\n return compileFilterNodes(node.children, node.op, byId);\n const { columnId } = node;\n const predicate = compileFilterPredicate(node, byId.get(columnId));\n return (valueOf) => predicate(valueOf(columnId));\n });\n if (op === \"and\")\n return (valueOf) => {\n for (let index = 0; index < matchers.length; index += 1)\n if (!matchers[index](valueOf))\n return false;\n return true;\n };\n return (valueOf) => {\n for (let index = 0; index < matchers.length; index += 1)\n if (matchers[index](valueOf))\n return true;\n return false;\n };\n}\nconst internals = Symbol(\"compiled-query-internals\");\nconst collator = new Intl.Collator(undefined, {\n numeric: true,\n sensitivity: \"base\",\n});\nexport const FILTER_OPERATORS = {\n text: new Set([\n \"contains\",\n \"notContains\",\n \"equals\",\n \"notEquals\",\n \"startsWith\",\n \"endsWith\",\n \"isEmpty\",\n \"isNotEmpty\",\n ]),\n number: new Set([\n \"equals\",\n \"notEquals\",\n \"gt\",\n \"gte\",\n \"lt\",\n \"lte\",\n \"between\",\n \"isEmpty\",\n \"isNotEmpty\",\n ]),\n date: new Set([\n \"on\",\n \"before\",\n \"after\",\n \"dateBetween\",\n \"isEmpty\",\n \"isNotEmpty\",\n ]),\n enum: new Set([\"isAnyOf\", \"isNoneOf\", \"isEmpty\", \"isNotEmpty\"]),\n boolean: new Set([\"isAnyOf\", \"isNoneOf\", \"isEmpty\", \"isNotEmpty\"]),\n};\nconst BUILTIN_AGGREGATES = new Set([\"sum\", \"avg\", \"min\", \"max\", \"count\"]);\nconst NUMBER_ONLY_AGGREGATES = new Set([\"sum\", \"avg\"]);\nconst EXTREMA_AGGREGATES = new Set([\"min\", \"max\"]);\nconst COLUMN_TYPES = new Set([\"text\", \"number\", \"date\", \"enum\", \"boolean\"]);\nfunction captureCompileInput(input) {\n const rawColumns = captureProperty(input, \"derivations\", \"input.derivations\");\n const rawQuery = captureProperty(input, \"query\", \"input.query\");\n const previous = captureProperty(input, \"previous\", \"input.previous\");\n const rawAuthority = captureProperty(input, \"filterAuthority\", \"input.filterAuthority\");\n const rawSortAuthority = captureProperty(input, \"sortAuthority\", \"input.sortAuthority\");\n if (rawQuery === null || typeof rawQuery !== \"object\")\n fail(\"query must be an object\", \"input.query\");\n if (rawAuthority !== undefined &&\n rawAuthority !== \"engine\" &&\n rawAuthority !== \"external\")\n fail('filterAuthority must be \"engine\" or \"external\"', \"input.filterAuthority\");\n if (rawSortAuthority !== undefined &&\n rawSortAuthority !== \"engine\" &&\n rawSortAuthority !== \"external\")\n fail('sortAuthority must be \"engine\" or \"external\"', \"input.sortAuthority\");\n return {\n columns: captureColumns(rawColumns),\n query: captureQuery(rawQuery),\n previous: previous,\n filterAuthority: (rawAuthority ?? \"engine\"),\n sortAuthority: (rawSortAuthority ?? \"engine\"),\n };\n}\nfunction captureColumns(rawColumns) {\n return captureDenseArray(rawColumns, \"derivations\", \"derivations must be an array\", (rawColumn, index) => {\n const path = `derivations[${index}]`;\n if (rawColumn === null || typeof rawColumn !== \"object\")\n fail(\"a derivation is not an object\", path);\n const id = captureProperty(rawColumn, \"id\", `${path}.id`);\n const columnId = typeof id === \"string\" ? id : undefined;\n const type = captureProperty(rawColumn, \"type\", `${path}.type`, columnId);\n const accessor = captureProperty(rawColumn, \"accessor\", `${path}.accessor`, columnId);\n const value = captureProperty(rawColumn, \"value\", `${path}.value`, columnId);\n const compare = captureProperty(rawColumn, \"compare\", `${path}.compare`, columnId);\n const rawAggregate = captureProperty(rawColumn, \"aggregate\", `${path}.aggregate`, columnId);\n const aggregate = rawAggregate !== null && typeof rawAggregate === \"object\"\n ? captureAggregator(rawAggregate, `${path}.aggregate`, columnId)\n : rawAggregate;\n return Object.freeze({\n id,\n type,\n accessor,\n value,\n compare,\n aggregate,\n });\n });\n}\nfunction captureAggregator(source, path, columnId) {\n let keys;\n try {\n keys = Object.keys(source);\n if (Object.getOwnPropertySymbols(source).length > 0)\n fail(\"symbol-keyed aggregate options are not supported\", path, columnId);\n }\n catch (cause) {\n if (cause instanceof CompiledQueryValidationError)\n throw cause;\n throw new CompiledQueryValidationError(\"aggregate property discovery threw while compiling\", path, columnId, { cause });\n }\n const required = [\"init\", \"accumulate\", \"merge\", \"finalize\"];\n const allKeys = [...new Set([...keys, ...required, \"snapshotAccumulator\"])];\n const clone = {};\n for (const key of allKeys) {\n const captured = captureProperty(source, key, `${path}.${key}`, columnId);\n clone[key] = required.includes(key)\n ? captured\n : cloneOwnedValue(captured, `${path}.${key}`, new WeakSet(), columnId);\n }\n return Object.freeze(clone);\n}\nfunction captureQuery(source) {\n const rawFilters = captureProperty(source, \"filters\", \"query.filters\");\n const rawSort = captureProperty(source, \"sort\", \"query.sort\");\n const rawRowGroups = captureProperty(source, \"rowGroups\", \"query.rowGroups\");\n return Object.freeze({\n filters: captureDenseArray(rawFilters, \"query.filters\", \"filters must be an array\", (entry, index) => captureFilterNode(entry, `query.filters[${index}]`)),\n sort: captureDenseArray(rawSort, \"query.sort\", \"sort must be an array\", (entry, index) => captureOrdering(entry, \"sort\", index)),\n rowGroups: captureDenseArray(rawRowGroups, \"query.rowGroups\", \"rowGroups must be an array\", (entry, index) => captureOrdering(entry, \"rowGroups\", index)),\n });\n}\nfunction captureDenseArray(source, path, notArrayDetail, captureEntry) {\n let isArray;\n try {\n isArray = Array.isArray(source);\n }\n catch (cause) {\n throw new CompiledQueryValidationError(\"array brand check threw while compiling\", path, undefined, { cause });\n }\n if (!isArray)\n fail(notArrayDetail, path);\n const array = source;\n const length = captureProperty(array, \"length\", `${path}.length`);\n if (typeof length !== \"number\" ||\n !Number.isInteger(length) ||\n length < 0 ||\n length > 0xffff_ffff) {\n fail(\"array length is invalid\", `${path}.length`);\n }\n const captured = [];\n for (let index = 0; index < length; index += 1) {\n const entryPath = `${path}[${index}]`;\n let hasOwnIndex;\n try {\n hasOwnIndex = Object.prototype.hasOwnProperty.call(array, index);\n }\n catch (cause) {\n throw new CompiledQueryValidationError(\"array index presence check threw while compiling\", entryPath, undefined, { cause });\n }\n if (!hasOwnIndex)\n fail(\"array index is missing\", entryPath);\n const entry = captureProperty(array, index, entryPath);\n captured.push(captureEntry(entry, index));\n }\n return Object.freeze(captured);\n}\n/*\n * The deepest a captured filter tree may nest, counting root nodes as depth 0.\n *\n * Capture is the chokepoint: validation, snapshotting, descriptor keys, leaf\n * collection, structural equality and per-row evaluation all recurse over a\n * tree only AFTER it has been captured, so bounding it here bounds every one\n * of them at once. Without the bound the failure mode was not merely a deep\n * tree — measured against this file's pre-bound revision, a 1000-level tree\n * CAPTURED cleanly and then overflowed the stack in `filterNodeListEqual` on\n * the next recompile, so the `RangeError` surfaced from a later `setQuery` on\n * a plan the engine had already accepted; at 2000 `compileQuery` threw a raw\n * `RangeError` instead of this module's validation error.\n *\n * 64 is chosen as far beyond any tree a human or a builder UI produces (real\n * filter trees nest a handful of levels) while sitting an order of magnitude\n * below the depth at which any of the downstream recursions is at risk.\n */\nconst MAX_FILTER_TREE_DEPTH = 64;\n/**\n * One node of the filter tree. A node carrying `children` is a group and is\n * captured recursively, breadcrumbed as `<path>.children[i]`; anything else is\n * captured as a leaf. Every level is frozen on the way out, so the captured\n * tree is owned by the plan rather than aliasing the caller's objects.\n *\n * `depth` is the node's own nesting level and is bounded — see\n * `MAX_FILTER_TREE_DEPTH` for why the bound lives here and nowhere else.\n */\nfunction captureFilterNode(raw, path, depth = 0) {\n if (depth > MAX_FILTER_TREE_DEPTH)\n fail(`filter group nesting exceeds ${MAX_FILTER_TREE_DEPTH} levels`, path);\n if (raw === null || typeof raw !== \"object\")\n fail(\"filter entry is not an object\", path);\n const children = captureProperty(raw, \"children\", `${path}.children`);\n if (children === undefined)\n return captureFilter(raw, path);\n const op = captureProperty(raw, \"op\", `${path}.op`);\n if (op !== \"and\" && op !== \"or\")\n fail(\"filter group must join with and or or\", `${path}.op`);\n return Object.freeze({\n op,\n children: captureDenseArray(children, `${path}.children`, \"filter group children must be an array\", (entry, index) => captureFilterNode(entry, `${path}.children[${index}]`, depth + 1)),\n });\n}\nfunction captureFilter(raw, path) {\n const columnId = captureProperty(raw, \"columnId\", `${path}.columnId`);\n const contextId = typeof columnId === \"string\" ? columnId : undefined;\n const operator = captureProperty(raw, \"operator\", `${path}.operator`, contextId);\n const value = captureProperty(raw, \"value\", `${path}.value`, contextId);\n return Object.freeze({\n columnId,\n operator,\n value: cloneOwnedValue(value, `${path}.value`, new WeakSet(), contextId),\n });\n}\nfunction captureOrdering(raw, area, index) {\n const path = `query.${area}[${index}]`;\n if (raw === null || typeof raw !== \"object\")\n fail(`${area} entry is not an object`, path);\n const columnId = captureProperty(raw, \"columnId\", `${path}.columnId`);\n const contextId = typeof columnId === \"string\" ? columnId : undefined;\n const direction = captureProperty(raw, \"direction\", `${path}.direction`, contextId);\n const nulls = captureProperty(raw, \"nulls\", `${path}.nulls`, contextId);\n return Object.freeze({\n columnId,\n direction,\n nulls,\n });\n}\nfunction fail(message, path = \"query\", columnId) {\n throw new CompiledQueryValidationError(message, path, columnId);\n}\nfunction captureProperty(source, property, path, columnId) {\n try {\n return Reflect.get(source, property);\n }\n catch (cause) {\n throw new CompiledQueryValidationError(\"property getter threw while compiling\", path, columnId, { cause });\n }\n}\nfunction validateDerivations(columns) {\n const ids = new Set();\n for (let index = 0; index < columns.length; index += 1) {\n const column = columns[index];\n const path = `derivations[${index}]`;\n if (!column || typeof column !== \"object\")\n fail(\"a derivation is not an object\", path);\n if (typeof column.id !== \"string\" || column.id.length === 0)\n fail(\"a derivation has no column ID\", `${path}.id`);\n if (ids.has(column.id))\n fail(`duplicate derivation column ID ${column.id}`, `${path}.id`, column.id);\n ids.add(column.id);\n if (!COLUMN_TYPES.has(column.type))\n fail(`column has invalid type ${column.type}`, `${path}.type`, column.id);\n if (typeof column.accessor !== \"function\" ||\n typeof column.value !== \"function\") {\n fail(\"column has no accessor\", `${path}.accessor`, column.id);\n }\n if (column.compare !== undefined && typeof column.compare !== \"function\") {\n fail(\"column has an invalid comparator\", `${path}.compare`, column.id);\n }\n validateAggregate(column, `${path}.aggregate`);\n }\n}\nfunction validateAggregate(column, path) {\n const aggregate = column.aggregate;\n if (aggregate === undefined)\n return;\n if (typeof aggregate === \"string\") {\n if (!BUILTIN_AGGREGATES.has(aggregate))\n fail(`unknown aggregate ${aggregate}`, path, column.id);\n if (NUMBER_ONLY_AGGREGATES.has(aggregate) && column.type !== \"number\") {\n fail(`numeric aggregate ${aggregate} requires a number column`, path, column.id);\n }\n if (EXTREMA_AGGREGATES.has(aggregate) &&\n column.type !== \"number\" &&\n column.type !== \"date\") {\n fail(`aggregate ${aggregate} requires a number or date column`, path, column.id);\n }\n return;\n }\n if (!aggregate || typeof aggregate !== \"object\")\n fail(\"aggregate must be a built-in name or object\", path, column.id);\n for (const operation of [\n \"init\",\n \"accumulate\",\n \"merge\",\n \"finalize\",\n ]) {\n if (typeof aggregate[operation] !== \"function\")\n fail(`aggregate has no ${operation}`, `${path}.${operation}`, column.id);\n }\n if (aggregate.snapshotAccumulator !== undefined &&\n typeof aggregate.snapshotAccumulator !== \"function\") {\n fail(\"aggregate has an invalid snapshotAccumulator\", `${path}.snapshotAccumulator`, column.id);\n }\n}\nfunction resolveColumn(columns, columnId, area) {\n const column = columns.get(columnId);\n if (!column)\n fail(`references unknown column ${columnId}`, area, columnId);\n return column;\n}\nfunction validateOrdering(entry, columns, area, index) {\n const path = `query.${area}[${index}]`;\n if (!entry || typeof entry !== \"object\")\n fail(`${area} entry is not an object`, path);\n resolveColumn(columns, entry.columnId, `${path}.columnId`);\n const direction = entry.direction ?? \"asc\";\n if (direction !== \"asc\" && direction !== \"desc\")\n fail(`invalid direction ${direction}`, `${path}.direction`, entry.columnId);\n if (entry.nulls !== undefined &&\n entry.nulls !== \"first\" &&\n entry.nulls !== \"last\") {\n fail(`invalid null placement ${entry.nulls}`, `${path}.nulls`, entry.columnId);\n }\n}\nfunction validateFilterNode(node, columns, path) {\n if (isRuntimeFilterGroup(node)) {\n node.children.forEach((child, index) => validateFilterNode(child, columns, `${path}.children[${index}]`));\n return;\n }\n validateFilter(node, columns, path);\n}\nfunction validateFilter(filter, columns, path) {\n if (!filter || typeof filter !== \"object\")\n fail(\"filter entry is not an object\", path);\n const column = resolveColumn(columns, filter.columnId, `${path}.columnId`);\n const operators = FILTER_OPERATORS[column.type];\n if (!operators?.has(filter.operator))\n fail(`column cannot use operator ${filter.operator}`, `${path}.operator`, filter.columnId);\n if (filter.operator === \"isEmpty\" || filter.operator === \"isNotEmpty\")\n return;\n if (filter.value === undefined || filter.value === null)\n fail(\"filter is missing its operand\", `${path}.value`, filter.columnId);\n validateFilterOperand(column, filter, `${path}.value`);\n}\nfunction validateFilterOperand(column, filter, path) {\n const value = filter.value;\n if (column.type === \"number\") {\n const values = filter.operator === \"between\" ? value : [value];\n if (!Array.isArray(values) ||\n (filter.operator === \"between\" && values.length !== 2) ||\n values.some((entry) => typeof entry !== \"number\" || Number.isNaN(entry))) {\n fail(filter.operator === \"between\"\n ? \"number range must contain exactly two non-NaN numbers\"\n : \"number operand must be a non-NaN number\", path, column.id);\n }\n return;\n }\n if (column.type === \"date\") {\n if (filter.operator === \"dateBetween\") {\n if (!Array.isArray(value) ||\n value.length !== 2 ||\n value.some((entry) => typeof entry !== \"string\")) {\n fail(\"date range must contain exactly two strings\", path, column.id);\n }\n }\n else if (typeof value !== \"string\") {\n fail(\"date operand must be a string\", path, column.id);\n }\n return;\n }\n if (column.type === \"text\") {\n if (typeof value !== \"string\")\n fail(\"text operand must be a string\", path, column.id);\n return;\n }\n if (!Array.isArray(value))\n fail(\"selection operand must be an array\", path, column.id);\n if (column.type === \"boolean\") {\n // A boolean column's operand must match what `booleanValue()` treats as\n // one of the two states AND what the docs promise the funnel can send:\n // real booleans, or the string literals \"true\"/\"false\" (the only values\n // a column's `options` are allowed to relabel to, per\n // content/docs/grid/filtering.mdx). Deliberately excludes 1/0/\"1\"/\"0\" —\n // `booleanValue()` also coerces those, but the docs never promise them,\n // so accepting them here would be validator-only drift ahead of the\n // documented contract instead of behind it.\n if (value.some((entry) => typeof entry !== \"boolean\" && entry !== \"true\" && entry !== \"false\")) {\n fail('boolean selection must contain only boolean values or the strings \"true\"/\"false\"', path, column.id);\n }\n return;\n }\n if (value.some((entry) => typeof entry !== \"string\")) {\n fail(`${column.type} selection must contain only string values`, path, column.id);\n }\n}\nfunction validateQuery(query, columns) {\n if (!query || typeof query !== \"object\")\n fail(\"query is not an object\");\n if (!Array.isArray(query.filters) ||\n !Array.isArray(query.sort) ||\n !Array.isArray(query.rowGroups)) {\n fail(\"filters, sort, and rowGroups must be arrays\");\n }\n const byId = new Map(columns.map((column) => [column.id, column]));\n query.filters.forEach((node, index) => validateFilterNode(node, byId, `query.filters[${index}]`));\n query.sort.forEach((entry, index) => validateOrdering(entry, byId, \"sort\", index));\n query.rowGroups.forEach((entry, index) => validateOrdering(entry, byId, \"rowGroups\", index));\n}\n/*\n * Nodes are matched STRUCTURALLY, never by a serialized key: the descriptor\n * key is raw concatenation over unframed user operands, so a filter value can\n * forge the separators and impersonate a sibling — harmless for the ordering\n * job the key exists for, a wrong-results bug as an identity test (the plan\n * would be reused and the incoming query silently discarded).\n *\n * Groups match when their join operators match and their children match as an\n * unordered multiset, recursively — the same used-set shape the node list one\n * level up uses, for the same reason: both joins are commutative.\n */\n/*\n * `filterLeaves` is the caller's own `#filterLeaves`, passed rather than\n * re-derived: this runs on every recompile check (`semanticallyMatches`, so\n * every `setQuery`), and walking the tree here would allocate a fresh leaf\n * array per call for a set the plan already holds.\n */\nfunction derivationsEqualForPlan(left, right, query, filterLeaves) {\n if (left.length !== right.length)\n return false;\n const accessorIds = new Set();\n const comparatorIds = new Set();\n filterLeaves.forEach((entry) => accessorIds.add(entry.columnId));\n query.sort.forEach((entry) => {\n accessorIds.add(entry.columnId);\n comparatorIds.add(entry.columnId);\n });\n query.rowGroups.forEach((entry) => {\n accessorIds.add(entry.columnId);\n comparatorIds.add(entry.columnId);\n });\n return left.every((column, index) => {\n const other = right[index];\n if (column.id !== other.id || column.type !== other.type)\n return false;\n if (!semanticValueEqual(column.aggregate, other.aggregate))\n return false;\n if (column.aggregate !== undefined)\n accessorIds.add(column.id);\n if (accessorIds.has(column.id) && column.accessor !== other.accessor)\n return false;\n if (comparatorIds.has(column.id) && column.compare !== other.compare)\n return false;\n return true;\n });\n}\nfunction cloneOwnedValue(value, path, seen, columnId) {\n if (value === null ||\n value === undefined ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"bigint\" ||\n typeof value === \"function\") {\n return value;\n }\n if (typeof value === \"symbol\")\n fail(\"symbols are not supported in compiled inputs\", path, columnId);\n let dateLike;\n try {\n dateLike = value instanceof Date;\n }\n catch (cause) {\n throw new CompiledQueryValidationError(\"value brand check threw while compiling\", path, columnId, { cause });\n }\n if (dateLike) {\n const timestamp = readDateTimestamp(value);\n if (timestamp === undefined)\n fail(\"value has an invalid Date brand\", path, columnId);\n return Object.freeze(new Date(timestamp));\n }\n if (typeof value !== \"object\")\n fail(\"unsupported compiled input value\", path, columnId);\n if (seen.has(value))\n fail(\"cyclic values are not supported\", path, columnId);\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n const captured = [];\n for (let index = 0; index < value.length; index += 1) {\n captured.push(cloneOwnedValue(captureProperty(value, index, `${path}[${index}]`, columnId), `${path}[${index}]`, seen, columnId));\n }\n return Object.freeze(captured);\n }\n if (!isPlainObject(value)) {\n fail(\"only Date, arrays, and plain objects are supported in compiled inputs\", path, columnId);\n }\n const clone = {};\n for (const key of Object.keys(value)) {\n clone[key] = cloneOwnedValue(captureProperty(value, key, `${path}.${key}`, columnId), `${path}.${key}`, seen, columnId);\n }\n return Object.freeze(clone);\n }\n finally {\n seen.delete(value);\n }\n}\nfunction readDateTimestamp(value) {\n try {\n return Date.prototype.getTime.call(value);\n }\n catch {\n return undefined;\n }\n}\nfunction snapshotColumns(columns, path) {\n return Object.freeze(columns.map((column, index) => {\n const aggregate = column.aggregate === undefined || typeof column.aggregate === \"string\"\n ? column.aggregate\n : snapshotAggregator(column.aggregate, `${path}[${index}].aggregate`, column.id);\n return Object.freeze({ ...column, aggregate });\n }));\n}\nfunction snapshotAggregator(aggregator, path, columnId) {\n const source = aggregator;\n const clone = {};\n const callbacks = new Set([\n \"init\",\n \"accumulate\",\n \"merge\",\n \"snapshotAccumulator\",\n \"finalize\",\n ]);\n try {\n if (Object.getOwnPropertySymbols(aggregator).length > 0) {\n fail(\"symbol-keyed aggregate options are not supported\", path, columnId);\n }\n for (const key of Object.keys(aggregator)) {\n if (!callbacks.has(key)) {\n clone[key] = cloneOwnedValue(source[key], `${path}.${key}`, new WeakSet());\n }\n }\n }\n catch (error) {\n if (error instanceof CompiledQueryValidationError &&\n error.columnId === undefined) {\n throw new CompiledQueryValidationError(error.detail, error.path, columnId);\n }\n throw error;\n }\n clone.init = aggregator.init;\n clone.accumulate = aggregator.accumulate;\n clone.merge = aggregator.merge;\n clone.snapshotAccumulator = aggregator.snapshotAccumulator;\n clone.finalize = aggregator.finalize;\n return Object.freeze(clone);\n}\nfunction snapshotQuery(query, path, canonicalFilters = false) {\n const snapshotNode = (node, nodePath) => isRuntimeFilterGroup(node)\n ? Object.freeze({\n op: node.op,\n children: Object.freeze(node.children.map((child, index) => snapshotNode(child, `${nodePath}.children[${index}]`))),\n })\n : Object.freeze({\n ...node,\n value: cloneOwnedValue(node.value, `${nodePath}.value`, new WeakSet()),\n });\n const filters = query.filters.map((node, index) => snapshotNode(node, `${path}.filters[${index}]`));\n if (canonicalFilters)\n filters.sort(compareFilterDescriptors);\n return Object.freeze({\n filters: Object.freeze(filters),\n sort: Object.freeze(query.sort.map((entry) => Object.freeze({ ...entry }))),\n rowGroups: Object.freeze(query.rowGroups.map((entry) => Object.freeze({ ...entry }))),\n });\n}\nconst EMPTY_FILTERS = Object.freeze([]);\nconst EMPTY_SORT = Object.freeze([]);\n/**\n * The query the plan APPLIES, as opposed to the one it reports. Filters are\n * sorted into a canonical order so plan identity survives a reordered filter\n * list — and dropped outright under external filter authority, which is the\n * single point where \"the caller already selected these records\" takes effect.\n *\n * Sort is the same idea one axis over: dropped under external sort authority,\n * which is where \"the caller already ranked these records\" takes effect. Note\n * that only `query.sort` goes — `rowGroups` keeps its own ordering, because\n * grouping is not in `PretableProcessingOptions` and a consumer who declared\n * external sort authority said nothing about it.\n */\nfunction canonicalRuntimeQuery(query, filterAuthority, sortAuthority) {\n return Object.freeze({\n filters: filterAuthority === \"external\"\n ? EMPTY_FILTERS\n : Object.freeze([...query.filters].sort(compareFilterDescriptors)),\n sort: sortAuthority === \"external\" ? EMPTY_SORT : query.sort,\n rowGroups: query.rowGroups,\n });\n}\nfunction compareFilterDescriptors(left, right) {\n return filterDescriptorKey(left).localeCompare(filterDescriptorKey(right));\n}\nfunction filterDescriptorKey(node) {\n if (isRuntimeFilterGroup(node)) {\n // Children are keyed then sorted for the same reason the roots are\n // sorted in `canonicalRuntimeQuery`: both joins are commutative, so a\n // reordered group is the same question and must reuse the same plan.\n return `group\\u0000${node.op}\\u0000[${node.children\n .map(filterDescriptorKey)\n .sort()\n .join(\"\\u0001\")}]`;\n }\n return `${node.columnId}\\u0000${node.operator}\\u0000${filterValueKey(node.value)}`;\n}\nfunction filterValueKey(value) {\n if (value instanceof Date)\n return `date:${String(readDateTimestamp(value))}`;\n if (Array.isArray(value))\n return `array:[${value.map(filterValueKey).join(\",\")}]`;\n if (typeof value === \"number\") {\n if (Object.is(value, -0))\n return \"number:-0\";\n return `number:${String(value)}`;\n }\n return `${typeof value}:${String(value)}`;\n}\nfunction isEmptyValue(value) {\n return (value === null ||\n value === undefined ||\n (typeof value === \"number\" && Number.isNaN(value)) ||\n (typeof value === \"string\" && value.trim() === \"\"));\n}\nfunction booleanValue(value) {\n if (typeof value === \"boolean\")\n return value;\n if (value === \"true\" || value === 1 || value === \"1\")\n return true;\n if (value === \"false\" || value === 0 || value === \"0\")\n return false;\n return Boolean(value);\n}\nconst alwaysTrue = () => true;\nconst alwaysFalse = () => false;\nfunction isNumberCell(value) {\n return typeof value === \"number\" && !Number.isNaN(value);\n}\nfunction textCell(value) {\n return String(value ?? \"\").toLocaleLowerCase();\n}\nfunction compileNumberPredicate(operator, operand) {\n if (operator === \"between\") {\n const range = operand;\n const a = range[0];\n const b = range[1];\n if (typeof a !== \"number\" || typeof b !== \"number\")\n return alwaysFalse;\n const lower = Math.min(a, b);\n const upper = Math.max(a, b);\n return (value) => isNumberCell(value) && value >= lower && value <= upper;\n }\n if (typeof operand !== \"number\" || Number.isNaN(operand))\n return alwaysFalse;\n switch (operator) {\n case \"equals\":\n return (value) => isNumberCell(value) && value === operand;\n case \"notEquals\":\n return (value) => isNumberCell(value) && value !== operand;\n case \"gt\":\n return (value) => isNumberCell(value) && value > operand;\n case \"gte\":\n return (value) => isNumberCell(value) && value >= operand;\n case \"lt\":\n return (value) => isNumberCell(value) && value < operand;\n default:\n return (value) => isNumberCell(value) && value <= operand;\n }\n}\nfunction compileDatePredicate(operator, operand) {\n if (operator === \"dateBetween\") {\n const range = operand;\n const a = range[0];\n const b = range[1];\n if (!isValidDateValue(a) || !isValidDateValue(b))\n return alwaysFalse;\n const [lower, upper] = compareDateValues(a, b) <= 0 ? [a, b] : [b, a];\n return (value) => isValidDateValue(value) &&\n compareDateValues(value, lower) >= 0 &&\n compareDateValues(value, upper) <= 0;\n }\n if (!isValidDateValue(operand))\n return alwaysFalse;\n if (operator === \"on\")\n return (value) => isValidDateValue(value) && compareDateValues(value, operand) === 0;\n if (operator === \"before\")\n return (value) => isValidDateValue(value) && compareDateValues(value, operand) < 0;\n return (value) => isValidDateValue(value) && compareDateValues(value, operand) > 0;\n}\nfunction compileSelectionPredicate(operator, operand, coerce) {\n const entries = operand;\n // An empty selection matches EVERYTHING, regardless of direction.\n if (entries.length === 0)\n return alwaysTrue;\n const included = new Set(entries.map((entry) => coerce(entry)));\n return operator === \"isAnyOf\"\n ? (value) => included.has(coerce(value))\n : (value) => !included.has(coerce(value));\n}\nfunction compileTextPredicate(operator, operand) {\n const search = String(operand).toLocaleLowerCase();\n switch (operator) {\n case \"contains\":\n return (value) => textCell(value).includes(search);\n case \"notContains\":\n return (value) => !textCell(value).includes(search);\n case \"equals\":\n return (value) => textCell(value) === search;\n case \"notEquals\":\n return (value) => textCell(value) !== search;\n case \"startsWith\":\n return (value) => textCell(value).startsWith(search);\n default:\n return (value) => textCell(value).endsWith(search);\n }\n}\n/**\n * The ONE home of filter-predicate semantics: resolves a validated runtime\n * filter's column type + operator into a monomorphic `(value) => boolean`\n * closure with operand normalization hoisted out of the row loop (between\n * bounds destructured and min/maxed once, date operands collapsed to UTC\n * day-ms once, text needles lowercased once, selection operands coerced into\n * a Set once). Called once per filter at plan construction; filters reaching\n * a plan have passed `validateFilter`, so the defensive `alwaysFalse` arms\n * for malformed operands are unreachable there and exist only to preserve the\n * legacy per-row semantics for direct callers. Predicates only ever read the\n * CELL value — a throwing accessor throws at the value source\n * (`#readColumnValue`), never here.\n */\nexport function compileFilterPredicate(filter, column) {\n if (filter.operator === \"isEmpty\")\n return isEmptyValue;\n if (filter.operator === \"isNotEmpty\")\n return (value) => !isEmptyValue(value);\n const operand = filter.value;\n switch (column.type) {\n case \"number\":\n return compileNumberPredicate(filter.operator, operand);\n case \"date\":\n return compileDatePredicate(filter.operator, operand);\n case \"enum\":\n return compileSelectionPredicate(filter.operator, operand, String);\n case \"boolean\":\n return compileSelectionPredicate(filter.operator, operand, booleanValue);\n default:\n return compileTextPredicate(filter.operator, operand);\n }\n}\nfunction isNullSortValue(value) {\n return (value === null ||\n value === undefined ||\n (typeof value === \"number\" && Number.isNaN(value)));\n}\nfunction compareValues(left, right, column, ordering) {\n if (!column.compare && column.type === \"date\") {\n const leftValid = isValidDateValue(left);\n const rightValid = isValidDateValue(right);\n if (leftValid || rightValid) {\n if (!leftValid)\n return 1;\n if (!rightValid)\n return -1;\n const result = compareDateValues(left, right);\n return ordering.direction === \"desc\" ? -result : result;\n }\n return 0;\n }\n const leftNull = isNullSortValue(left);\n const rightNull = isNullSortValue(right);\n if (leftNull || rightNull) {\n if (leftNull && rightNull)\n return 0;\n const nullResult = ordering.nulls === \"first\" ? -1 : 1;\n return leftNull ? nullResult : -nullResult;\n }\n let result;\n if (column.compare) {\n const customResult = column.compare(left, right);\n if (typeof customResult !== \"number\" || Number.isNaN(customResult)) {\n throw new TypeError(\"Custom comparators must return a number other than NaN.\");\n }\n result = customResult;\n }\n else if (column.type === \"number\" &&\n typeof left === \"number\" &&\n typeof right === \"number\") {\n result = left === right ? 0 : left < right ? -1 : 1;\n }\n else {\n result = collator.compare(String(left), String(right));\n }\n return ordering.direction === \"desc\" ? -result : result;\n}\nclass CompiledQueryPlan {\n activeColumnIds;\n #publicColumns;\n #publicQuery;\n #runtimeColumns;\n #runtimeQuery;\n #byId;\n /*\n * The LEAVES of `#runtimeQuery.filters`, depth-first — not the filter list\n * itself, which under a tree holds groups and has a different length. This\n * is a DEPENDENCY set (which columns the filters read), never the evaluation\n * order: joins are honoured by `#compiledFilterTree`.\n */\n #filterLeaves;\n /*\n * The whole filter tree as ONE closure, built at construction so no verdict\n * re-normalizes an operand, re-resolves a column, or reads a join per row.\n *\n * Built the same way for EVERY query, grouped or flat. A flat query briefly\n * had a second, separate predicate array and loop of its own; that bought a\n * real cost (a grouped query compiled every leaf predicate twice) and the\n * standing risk of two implementations of one semantics drifting apart,\n * catchable only after the fact. It bought no speed either: the flat loop\n * it saved allocated a closure per row of its own, so the single path is\n * measurably the FASTER of the two on an isolated verdict loop.\n */\n #compiledFilterTree;\n #active;\n #aggregateColumns;\n #operation;\n #filterAuthority;\n #sortAuthority;\n // Not `readonly`: `adoptEvaluationCache` repoints it at a previous plan's\n // map (by reference — no copy, no per-row work) on a filter-only change.\n #evaluationCache = new WeakMap();\n /*\n * The recompile cache compares against the PUBLIC query, not the runtime\n * one: under external authority the runtime query has no filters at all, so\n * comparing it would declare every filtered query a mismatch and rebuild on\n * every `setQuery`. Authority joins the comparison in its own right — it is\n * a render-time read on the React surface, never a memo dependency, so a\n * consumer really can flip it while a plan is alive, and reusing that plan\n * would leave suppression latched at whatever it was on the first compile.\n */\n [internals] = {\n semanticallyMatches: (derivations, query, filterAuthority, sortAuthority) => this.#filterAuthority === filterAuthority &&\n this.#sortAuthority === sortAuthority &&\n derivationsEqualForPlan(this.#runtimeColumns, derivations, this.#runtimeQuery, this.#filterLeaves) &&\n queryEqual(this.#publicQuery, query),\n };\n get derivations() {\n return snapshotColumns(this.#publicColumns, \"derivations\");\n }\n get query() {\n return snapshotQuery(this.#publicQuery, \"query\");\n }\n constructor(capturedColumns, capturedQuery, operation, filterAuthority, sortAuthority) {\n this.#publicColumns = capturedColumns;\n this.#publicQuery = capturedQuery;\n this.#runtimeColumns = capturedColumns;\n this.#filterAuthority = filterAuthority;\n this.#sortAuthority = sortAuthority;\n this.#runtimeQuery = canonicalRuntimeQuery(capturedQuery, filterAuthority, sortAuthority);\n this.#operation = operation;\n this.#byId = new Map(this.#runtimeColumns.map((column) => [column.id, column]));\n this.#filterLeaves = filterLeavesOf(this.#runtimeQuery.filters);\n this.#compiledFilterTree = compileFilterNodes(this.#runtimeQuery.filters, \"and\", this.#byId);\n const activeIds = new Set();\n this.#filterLeaves.forEach((entry) => activeIds.add(entry.columnId));\n this.#runtimeQuery.rowGroups.forEach((entry) => activeIds.add(entry.columnId));\n this.#runtimeQuery.sort.forEach((entry) => activeIds.add(entry.columnId));\n this.#aggregateColumns = this.#runtimeColumns.filter((column) => column.aggregate !== undefined);\n this.#aggregateColumns.forEach((column) => activeIds.add(column.id));\n this.#active = this.#runtimeColumns.filter((column) => activeIds.has(column.id));\n this.activeColumnIds = Object.freeze(this.#active.map((column) => column.id));\n }\n evaluate(input) {\n const cached = this.#evaluationCache.get(input.row);\n if (cached &&\n cached.metadata !== undefined &&\n Object.is(cached.rowId, input.rowId) &&\n cached.sourceOrder === input.sourceOrder) {\n return cached.metadata;\n }\n const values = new Map();\n for (const column of this.#active) {\n values.set(column.id, this.#readColumnValue(column, input.row, input.rowId));\n }\n const filterPasses = this.#filterVerdict((columnId) => values.get(columnId));\n const groupPath = Object.freeze(this.#runtimeQuery.rowGroups.map((entry) => Object.freeze({\n columnId: entry.columnId,\n value: values.get(entry.columnId),\n })));\n return this.#finalizeMetadata({\n rowId: input.rowId,\n row: input.row,\n sourceOrder: input.sourceOrder,\n filterPasses,\n groupPath,\n valueOf: (columnId) => values.get(columnId),\n });\n }\n /*\n * Tail of `evaluate`: writes the row's sort keys to the plan's store,\n * builds the dependency, aggregate leaves, and the frozen metadata from a\n * per-column value source, then seeds the evaluation cache. `valueOf` must\n * cover every sorted and aggregated column of THIS plan.\n *\n * `filterPasses` reaches the cache entry and nothing else: the metadata it\n * builds carries no verdict, because a verdict lives in the structure the\n * row lands in, not on the row.\n */\n #finalizeMetadata(input) {\n const sortKeys = Object.freeze(this.#runtimeQuery.sort.map((entry) => Object.freeze({\n columnId: entry.columnId,\n value: input.valueOf(entry.columnId),\n })));\n const dependency = Object.freeze({\n sourceOrder: input.sourceOrder,\n sortKeys,\n });\n const aggregateLeaves = Object.freeze(this.#aggregateColumns.map((column) => Object.freeze({\n columnId: column.id,\n aggregate: lowerCalendarDateAggregate(column.type, column.aggregate),\n allLeaf: Object.freeze({\n id: input.rowId,\n row: input.row,\n value: input.valueOf(column.id),\n dependency,\n }),\n })));\n const metadata = Object.freeze({\n rowId: input.rowId,\n row: input.row,\n sourceOrder: input.sourceOrder,\n groupPath: input.groupPath,\n aggregateLeaves,\n });\n const existing = this.#evaluationCache.get(input.row);\n if (existing === undefined) {\n this.#evaluationCache.set(input.row, {\n rowId: input.rowId,\n sourceOrder: input.sourceOrder,\n metadata,\n filterPasses: input.filterPasses,\n verdictPlan: this,\n sortKeys,\n });\n }\n else {\n // Upgrade a keys-only entry (or refresh a stale full one) in place —\n // no second WeakMap.set, so no second rehash risk.\n existing.rowId = input.rowId;\n existing.sourceOrder = input.sourceOrder;\n existing.metadata = metadata;\n existing.filterPasses = input.filterPasses;\n existing.verdictPlan = this;\n existing.sortKeys = sortKeys;\n }\n return metadata;\n }\n /*\n * The one accessor-read site: every column value this plan reads for\n * evaluation flows through here so the accessor-failed error shape cannot\n * fork between `evaluate` and the verdict-only path.\n */\n #readColumnValue(column, row, rowId) {\n try {\n return column.accessor(row);\n }\n catch (cause) {\n throw new PretableRowModelError(\"accessor-failed\", `Column ${column.id} accessor failed.`, {\n operation: this.#operation,\n rowId,\n columnId: column.id,\n cause,\n });\n }\n }\n /*\n * The ONE filter verdict, parameterized over the value source the same way\n * `#finalizeMetadata` is: `evaluate` supplies its collected value map, the\n * verdict-only path supplies live accessor reads. Predicate semantics live\n * in `compileFilterPredicate` and join semantics in `compileFilterNodes`,\n * both reached through the construction-time `#compiledFilterTree` — no\n * `#byId` lookup and no operand re-normalization per row.\n *\n * The ROOT list joins conjunctively, as it always has — a query's top-level\n * filters all have to hold. Below the roots, groups join by their own `op`.\n */\n #filterVerdict(valueOf) {\n return this.#compiledFilterTree(valueOf);\n }\n /**\n * The plan's OWN captured filter tree — the objects `captureFilterNode`\n * produced, not the re-frozen copy the `query` getter hands out.\n * @internal\n */\n static capturedFilterTreeForTesting(plan) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Captured filters require a compiled query plan.\");\n }\n return plan.#publicQuery.filters;\n }\n /**\n * This plan's filter verdict for one row — accessor reads over the runtime\n * filter columns only, no metadata construction, no cache writes. Error\n * semantics match `evaluate`: a throwing accessor surfaces the same\n * accessor-failed shape.\n *\n * A row this plan has already evaluated answers from the evaluation cache\n * under `evaluate`'s own guard, so `evaluate` + this call costs ONE\n * accessor pass, not two (the pinned per-row work budgets are exact). The\n * memo is exactly as fresh as the metadata `evaluate` would hand back for\n * the same input, and never answers for a DIFFERENT plan — old verdicts\n * come from root membership, not from here. The `verdictPlan` arm is what\n * makes that last clause true once a cache is SHARED: an adopted entry's\n * memo belongs to the plan that wrote it, so this plan re-reads accessors\n * rather than repeating a verdict its own filters never produced.\n */\n static filterVerdict(plan, input, instrumentation) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Filter verdicts require a compiled query plan.\");\n }\n const compiled = plan;\n if (instrumentation !== undefined)\n instrumentation.work.evaluationCacheLookups += 1;\n const cached = compiled.#evaluationCache.get(input.row);\n if (cached !== undefined &&\n cached.metadata !== undefined &&\n cached.filterPasses !== undefined &&\n cached.verdictPlan === compiled &&\n Object.is(cached.rowId, input.rowId) &&\n cached.sourceOrder === input.sourceOrder) {\n return cached.filterPasses;\n }\n return compiled.#filterVerdict((columnId) => compiled.#readColumnValue(compiled.#byId.get(columnId), input.row, input.rowId));\n }\n /**\n * Fused verdict + sort-key resolution for the ADOPTED identity-carry\n * sweep: ONE evaluation-cache read answers both questions\n * `filterVerdict` + `fillSortKeysFromPrevious` used to pay two reads for\n * (the verdict lookup discarded its entry, then the fill looked the same\n * key up again to hit its early return — one redundant get per survivor).\n *\n * Returns the row's sort keys when the row passes THIS plan's filters and\n * `undefined` when it does not; a rejected row's keys are never read, so\n * key resolution rides the verdict's single lookup for free.\n *\n * Precondition (CALLER-OWNED, exactly `adoptEvaluationCache`'s): this\n * plan's cache was adopted from the plan whose lineage evaluated\n * `input.row` — a filter-only change — so the cached `sortKeys` are the\n * ones this plan's accessors would produce (same orderings, same\n * accessors; see the adoption proof). The verdict is still recomputed\n * under this plan whenever the memo's `verdictPlan` is not this plan —\n * adopted entries always miss that guard, exactly as before the fusion.\n */\n static sortKeysIfPasses(plan, input, instrumentation) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Filter verdicts require a compiled query plan.\");\n }\n const compiled = plan;\n if (instrumentation !== undefined)\n instrumentation.work.evaluationCacheLookups += 1;\n const cached = compiled.#evaluationCache.get(input.row);\n const passes = cached !== undefined &&\n cached.metadata !== undefined &&\n cached.filterPasses !== undefined &&\n cached.verdictPlan === compiled &&\n Object.is(cached.rowId, input.rowId) &&\n cached.sourceOrder === input.sourceOrder\n ? cached.filterPasses\n : compiled.#filterVerdict((columnId) => compiled.#readColumnValue(compiled.#byId.get(columnId), input.row, input.rowId));\n if (!passes)\n return undefined;\n if (cached !== undefined) {\n // The same UNGUARDED read the carry fill's early return performs:\n // sort keys depend only on the row object and the (unchanged) sort\n // columns, so an entry from anywhere in the adopted lineage answers.\n return cached.sortKeys;\n }\n // A row the adopted lineage never evaluated: resolve keys by accessor\n // and seed a keys-only entry, mirroring the carry fill's miss arm with\n // nothing to carry (`metadata` absent, so a later `evaluate` upgrades).\n const sortKeys = Object.freeze(compiled.#runtimeQuery.sort.map((entry) => {\n const value = compiled.#readColumnValue(compiled.#byId.get(entry.columnId), input.row, input.rowId);\n if (instrumentation !== undefined)\n instrumentation.work.sortKeyEvaluations += 1;\n return Object.freeze({ columnId: entry.columnId, value });\n }));\n compiled.#evaluationCache.set(input.row, {\n rowId: input.rowId,\n sourceOrder: input.sourceOrder,\n metadata: undefined,\n filterPasses: undefined,\n verdictPlan: undefined,\n sortKeys,\n });\n return sortKeys;\n }\n /*\n * The single comparison loop behind `compareRecordRows`: per-ordering\n * `compareValues` over store-resolved keys, then the `sourceOrder`\n * tiebreak. Kept separate from key resolution so both sides resolve\n * before any comparison runs.\n */\n #compareBySortKeys(left, leftKeys, right, rightKeys) {\n for (let index = 0; index < this.#runtimeQuery.sort.length; index += 1) {\n const ordering = this.#runtimeQuery.sort[index];\n const column = this.#byId.get(ordering.columnId);\n try {\n const result = compareValues(leftKeys[index]?.value, rightKeys[index]?.value, column, ordering);\n if (result !== 0)\n return result;\n }\n catch (cause) {\n throw new CompiledQueryComparatorError(\"A compiled row comparator failed.\", [left.rowId, right.rowId], { columnId: ordering.columnId, cause, operation: this.#operation });\n }\n }\n return left.sourceOrder - right.sourceOrder;\n }\n #resolveSortKeys(input) {\n const keys = this.#evaluationCache.get(input.row)?.sortKeys;\n if (keys === undefined) {\n throw new Error(`Row ${String(input.rowId)} has no sort keys under this plan.`);\n }\n return keys;\n }\n /**\n * Orders two evaluated rows by the plan's own sort-key store. A missing\n * store entry is a defect — the fill points (`evaluate` and\n * `fillSortKeysFromPrevious`) are exhaustive — so resolution throws rather\n * than lazily re-running accessors.\n */\n static compareRecordRows(plan, left, right) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Record comparison requires a compiled query plan.\");\n }\n const compiled = plan;\n return compiled.#compareBySortKeys(left, compiled.#resolveSortKeys(left), right, compiled.#resolveSortKeys(right));\n }\n /**\n * Orders two rows by keys the CALLER already resolved — no store lookups.\n * Exists so O(n log n) sorts resolve keys once per row (decorate) instead\n * of once per comparison; `compareRecordRows` remains the general entry.\n * The comparison semantics are the same shared loop.\n */\n static compareWithSortKeys(plan, left, leftKeys, right, rightKeys) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Key comparison requires a compiled query plan.\");\n }\n return plan.#compareBySortKeys(left, leftKeys, right, rightKeys);\n }\n /**\n * Resolves one evaluated row's keys from the plan's own store. Same\n * fail-loud contract as `compareRecordRows`: a missing entry is a defect.\n */\n static sortKeysOf(plan, input) {\n if (!(plan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Sort-key resolution requires a compiled query plan.\");\n }\n return plan.#resolveSortKeys(input);\n }\n /**\n * Fills `nextPlan`'s store for one row from `previousPlan`'s: values carry\n * by columnId where the sort columns overlap, accessors run only for\n * newly-active sort columns. Precondition (caller-owned): the plan change\n * preserves every carried sort column's accessor semantics, so carried\n * values are the ones the next plan's accessors would produce — both\n * `isSortOnlyChange` and `isFilterOnlyChange` qualify. When instrumentation is\n * supplied, one counter is bumped per (row, sort column) entry — carry vs\n * accessor — and an already-filled row counts nothing.\n */\n static fillSortKeysFromPrevious(nextPlan, previousPlan, input, instrumentation) {\n if (!(nextPlan instanceof CompiledQueryPlan) ||\n !(previousPlan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Sort-key carryover requires compiled query plans.\");\n }\n const next = nextPlan;\n const previous = previousPlan;\n if (instrumentation !== undefined)\n instrumentation.work.evaluationCacheLookups += 1;\n const existing = next.#evaluationCache.get(input.row);\n if (existing !== undefined) {\n return existing.sortKeys;\n }\n if (instrumentation !== undefined)\n instrumentation.work.evaluationCacheLookups += 1;\n const carried = previous.#evaluationCache.get(input.row)?.sortKeys;\n const sortKeys = Object.freeze(next.#runtimeQuery.sort.map((entry) => {\n const previousKey = carried?.find((key) => key.columnId === entry.columnId);\n if (previousKey !== undefined) {\n if (instrumentation !== undefined)\n instrumentation.work.sortKeyCarries += 1;\n return Object.freeze({\n columnId: entry.columnId,\n value: previousKey.value,\n });\n }\n let value;\n try {\n value = next.#byId.get(entry.columnId).accessor(input.row);\n }\n catch (cause) {\n throw new PretableRowModelError(\"accessor-failed\", `Column ${entry.columnId} accessor failed.`, {\n operation: next.#operation,\n rowId: input.rowId,\n columnId: entry.columnId,\n cause,\n });\n }\n if (instrumentation !== undefined)\n instrumentation.work.sortKeyEvaluations += 1;\n return Object.freeze({ columnId: entry.columnId, value });\n }));\n // Keys-only entry: `metadata` stays absent, so a later `evaluate` for\n // this row misses the metadata guard and upgrades the entry in place.\n next.#evaluationCache.set(input.row, {\n rowId: input.rowId,\n sourceOrder: input.sourceOrder,\n metadata: undefined,\n filterPasses: undefined,\n verdictPlan: undefined,\n sortKeys,\n });\n return sortKeys;\n }\n /**\n * Points `nextPlan`'s evaluation cache at `previousPlan`'s — one reference\n * assignment for the whole store, no copy and no per-row work. Replaces the\n * per-row `fillSortKeysFromPrevious` walk on the filter fast path.\n *\n * Precondition (CALLER-OWNED, exactly like `fillSortKeysFromPrevious`):\n * `isFilterOnlyChange(previousPlan, nextPlan)`. Only the plan-shape check\n * is enforced here; passing a plan pair the classifier would reject\n * silently corrupts `nextPlan`'s reads, so callers assert first.\n *\n * Why every cached field survives, field by field — this is the safety\n * proof, and a filter-only delta is what each line spends:\n *\n * - `rowId` / `sourceOrder`: guard fields, not derived state. They record\n * the input the entry was written for, and both `evaluate` and\n * `filterVerdict` re-check them against the live input, so a drift\n * demotes to a miss under either plan.\n * - `row`: the WeakMap KEY. Adoption cannot change which row an entry\n * describes.\n * - `metadata.rowId` / `.row` / `.sourceOrder`: copies of the guarded\n * input, so they are correct under any plan that hits the guard.\n * - `metadata.groupPath`: one entry per `rowGroups` ordering, valued by\n * that column's accessor. `isFilterOnlyChange` requires\n * `!groupsChanged` (identical orderings) and `!derivationsChanged`,\n * which compares the accessor IDENTITY of every grouped column in BOTH\n * plans' queries. Same orderings + same accessors + same row object ⇒\n * the same path. (In practice the fast path also refuses grouped\n * queries outright.)\n * - `metadata.aggregateLeaves`: one entry per column with an `aggregate`,\n * carrying the aggregate spec, the row, the accessor value, and a\n * `dependency`. `derivationsEqualForPlan` compares column id, type and\n * ORDER positionally, requires `semanticValueEqual` on every\n * `aggregate`, and forces accessor identity for every aggregated\n * column — so the leaf set, its order, its specs and its values are all\n * identical.\n * - the leaves' `dependency` (`{ sourceOrder, sortKeys }`): guarded\n * `sourceOrder` plus the keys below.\n * - `sortKeys` (on the entry and inside the dependency): one value per\n * `sort` ordering. `isFilterOnlyChange` requires `!sortChanged`, and\n * `derivationsEqualForPlan` pins both the accessor and the comparator of\n * every sorted column. Identical orderings over identical accessors ⇒\n * value-identical keys, which is precisely why the per-row fill this\n * replaces reported 100% carries and zero evaluations.\n * - `filterPasses`: the ONE filter-dependent field, and the reason\n * `verdictPlan` exists. The memo is only read when `verdictPlan` is the\n * reading plan, so an adopted entry's verdict is invisible to the\n * adopter and it runs its own filters instead. Nothing stale leaks; the\n * adopter pays exactly the accessor pass it paid before this change.\n *\n * Sharing is symmetric-safe: the previous plan keeps reading the same map,\n * and anything the next plan writes into it is either value-identical\n * under the argument above or tagged with the writer (`verdictPlan`).\n */\n static adoptEvaluationCache(nextPlan, previousPlan) {\n if (!(nextPlan instanceof CompiledQueryPlan) ||\n !(previousPlan instanceof CompiledQueryPlan)) {\n throw new TypeError(\"Evaluation-cache adoption requires compiled query plans.\");\n }\n nextPlan.#evaluationCache = previousPlan.#evaluationCache;\n }\n compareGroupKeys(level, left, right) {\n const ordering = this.#runtimeQuery.rowGroups[level];\n if (!ordering)\n throw new RangeError(`Unknown row-group level ${level}.`);\n const column = this.#byId.get(ordering.columnId);\n try {\n return compareValues(left.value, right.value, column, ordering);\n }\n catch (cause) {\n throw new CompiledQueryComparatorError(\"A compiled group comparator failed.\", undefined, {\n columnId: ordering.columnId,\n cause,\n groupValues: [left.value, right.value],\n operation: this.#operation,\n });\n }\n }\n /**\n * Facet delta between two plans this module compiled. `undefined` means\n * \"treat as everything changed\" — a foreign object cannot be inspected, so\n * it never qualifies as a narrow change. Facets are compared on the RUNTIME\n * query, not the public one: under external sort authority the runtime\n * sort is `[]` on both sides, so a public-only sort change classifies as\n * `sortChanged: false` here, same as a true no-op.\n */\n static classifyDelta(previous, next) {\n if (!(previous instanceof CompiledQueryPlan) ||\n !(next instanceof CompiledQueryPlan))\n return undefined;\n // Both directions are required: a column active under only ONE side's\n // query (e.g. sorted in `next` but not in `previous`) would escape a\n // single-sided comparison, narrowing the conservatism guarantee.\n const derivationsChanged = !(derivationsEqualForPlan(previous.#runtimeColumns, next.#runtimeColumns, previous.#runtimeQuery, previous.#filterLeaves) &&\n derivationsEqualForPlan(previous.#runtimeColumns, next.#runtimeColumns, next.#runtimeQuery, next.#filterLeaves));\n const filtersChanged = !filterNodeListEqual(previous.#runtimeQuery.filters, next.#runtimeQuery.filters);\n const groupsChanged = !orderingEqual(previous.#runtimeQuery.rowGroups, next.#runtimeQuery.rowGroups);\n const sortChanged = !orderingEqual(previous.#runtimeQuery.sort, next.#runtimeQuery.sort);\n const authorityChanged = previous.#filterAuthority !== next.#filterAuthority ||\n previous.#sortAuthority !== next.#sortAuthority;\n return Object.freeze({\n derivationsChanged,\n filtersChanged,\n groupsChanged,\n sortChanged,\n authorityChanged,\n });\n }\n}\nexport function classifyQueryDelta(previous, next) {\n return CompiledQueryPlan.classifyDelta(previous, next);\n}\n/**\n * True only when the applied sort is the sole difference between the plans.\n */\nexport function isSortOnlyChange(previous, next) {\n const delta = classifyQueryDelta(previous, next);\n return (delta !== undefined &&\n delta.sortChanged &&\n !delta.derivationsChanged &&\n !delta.filtersChanged &&\n !delta.groupsChanged &&\n !delta.authorityChanged);\n}\n/**\n * True only when the applied filters are the sole difference between the\n * plans.\n */\nexport function isFilterOnlyChange(previous, next) {\n const delta = classifyQueryDelta(previous, next);\n return (delta !== undefined &&\n delta.filtersChanged &&\n !delta.derivationsChanged &&\n !delta.groupsChanged &&\n !delta.sortChanged &&\n !delta.authorityChanged);\n}\n/**\n * Orders two evaluated row records under `plan` via the plan's own sort-key\n * store. Both rows must already be in the store (`evaluate` or\n * `fillSortKeysFromPrevious`); a missing entry throws — it is a defect, not a\n * lazy-fill opportunity.\n */\nexport function compareRecordRows(plan, left, right) {\n return CompiledQueryPlan.compareRecordRows(plan, left, right);\n}\n/**\n * The plan's OWN captured filter tree — the objects `captureFilterNode`\n * produced, not the re-frozen copy the `query` getter hands out. Exists so\n * capture-level invariants (freezing, ownership) are assertable at all.\n * @internal\n */\nexport function getCapturedFilterTreeForTesting(plan) {\n return CompiledQueryPlan.capturedFilterTreeForTesting(plan);\n}\n/**\n * Orders two rows by keys the caller already resolved (via `sortKeysOf` or\n * `fillSortKeysFromPrevious`) — no store lookups. Exists so O(n log n) sorts\n * resolve keys once per row instead of once per comparison;\n * `compareRecordRows` remains the general entry with identical semantics.\n */\nexport function compareWithSortKeys(plan, left, leftKeys, right, rightKeys) {\n return CompiledQueryPlan.compareWithSortKeys(plan, left, leftKeys, right, rightKeys);\n}\n/**\n * Resolves one evaluated row's sort keys from `plan`'s own store. Both the\n * shape and the fail-loud contract match `compareRecordRows`: the row must\n * already be in the store, and a missing entry throws.\n */\nexport function sortKeysOf(plan, input) {\n return CompiledQueryPlan.sortKeysOf(plan, input);\n}\n/**\n * Fills `nextPlan`'s sort-key store for one row, carrying values from\n * `previousPlan`'s store where the sort columns overlap and running accessors\n * only for newly-active sort columns. Idempotent per row. Valid ONLY under a\n * plan change that preserves every carried sort column's accessor semantics\n * (`isSortOnlyChange` and `isFilterOnlyChange` both qualify) — the caller\n * owns that check.\n */\nexport function fillSortKeysFromPrevious(nextPlan, previousPlan, input, instrumentation) {\n return CompiledQueryPlan.fillSortKeysFromPrevious(nextPlan, previousPlan, input, instrumentation);\n}\n/**\n * Points `nextPlan` at `previousPlan`'s whole evaluation cache — sort keys\n * AND metadata — by reference. One assignment replaces a per-row fill, which\n * is why the filter fast path uses it instead of walking every row.\n *\n * Valid ONLY when `isFilterOnlyChange(previousPlan, nextPlan)` holds; the\n * caller owns that check. The field-by-field argument for why every cached\n * field survives such a change lives on\n * `CompiledQueryPlan.adoptEvaluationCache`.\n */\nexport function adoptEvaluationCache(nextPlan, previousPlan) {\n CompiledQueryPlan.adoptEvaluationCache(nextPlan, previousPlan);\n}\n/**\n * Computes `plan`'s filter verdict for one row: each runtime filter's column\n * accessor runs and its predicate is evaluated, with the same semantics and\n * accessor-failed error shape as `evaluate` — the predicate loop is shared,\n * not duplicated. No metadata is built and no cache entry is written.\n */\nexport function filterVerdict(plan, input, instrumentation) {\n return CompiledQueryPlan.filterVerdict(plan, input, instrumentation);\n}\n/**\n * Fused verdict + sort-key resolution under an ADOPTED evaluation cache —\n * one cache read instead of `filterVerdict` + `fillSortKeysFromPrevious`'s\n * two. Returns the keys when the row passes `plan`'s filters, `undefined`\n * when it does not. Valid ONLY after `adoptEvaluationCache(plan, previous)`\n * for the plan lineage that evaluated the row (a filter-only change); see\n * `CompiledQueryPlan.sortKeysIfPasses` for the semantics proof.\n */\nexport function sortKeysIfPasses(plan, input, instrumentation) {\n return CompiledQueryPlan.sortKeysIfPasses(plan, input, instrumentation);\n}\nexport function compileQuery(input) {\n const captured = captureCompileInput(input);\n validateDerivations(captured.columns);\n validateQuery(captured.query, captured.columns);\n const previous = captured.previous;\n if (previous?.[internals]?.semanticallyMatches(captured.columns, captured.query, captured.filterAuthority, captured.sortAuthority))\n return previous;\n return new CompiledQueryPlan(captured.columns, captured.query, input.operation ?? \"set-query\", captured.filterAuthority, captured.sortAuthority);\n}\n","/**\n * Membership bitsets: one bit per SLOT (see `slot-allocator`). A committed\n * root's verdict is its membership (the filter-membership invariant); the\n * bitset is a faster INDEX of that same structural answer for flat roots,\n * never a stored verdict. Grouped roots carry `EMPTY_MEMBERSHIP` and keep\n * answering from the group index.\n *\n * Mutable while a producer is building the next revision's set; frozen by\n * convention once a root captures it (no Object.freeze — typed arrays do not\n * support it; discipline is \"producers build fresh or clone, never write a\n * captured root's bitset\", the same convention every persistent structure\n * here relies on).\n *\n * Whole-copy on change is the point: 50k rows is 6.25KB, negligible per\n * commit (M0 measured ~1µs), so no COW machinery exists at this layer.\n */\n/** Shared sentinel for roots whose membership lives elsewhere (grouped). */\nexport const EMPTY_MEMBERSHIP = new Uint32Array(0);\nexport function createMembership(capacity) {\n return new Uint32Array((capacity + 31) >>> 5);\n}\n/** Clone, growing to `capacity` when it exceeds the source's words. */\nexport function cloneMembership(bits, capacity) {\n const words = Math.max(bits.length, (capacity + 31) >>> 5);\n const next = new Uint32Array(words);\n next.set(bits);\n return next;\n}\nexport function setMembershipBit(bits, slot) {\n bits[slot >>> 5] |= 1 << (slot & 31);\n}\nexport function clearMembershipBit(bits, slot) {\n bits[slot >>> 5] &= ~(1 << (slot & 31));\n}\n/** Out-of-range slots read as false — the EMPTY sentinel relies on this. */\nexport function testMembershipBit(bits, slot) {\n const word = bits[slot >>> 5];\n return word === undefined ? false : ((word >>> (slot & 31)) & 1) === 1;\n}\n","export class TransientEditToken {\n #editable = true;\n assertEditable() {\n if (!this.#editable) {\n throw new Error(\"Cannot mutate a frozen transient map.\");\n }\n }\n freeze() {\n this.#editable = false;\n }\n}\n","import { TransientEditToken } from \"./transient\";\nconst inspectPersistentPath = Symbol(\"inspectPersistentPath\");\nconst inspectTransientPath = Symbol(\"inspectTransientPath\");\nconst attachInstrumentation = Symbol(\"attachInstrumentation\");\nfunction hashString(value) {\n let hash = 0x811c9dc5;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n return hash >>> 0;\n}\nfunction hashKey(key) {\n return hashString(typeof key === \"string\" ? `s:${key}` : `n:${String(key)}`);\n}\nfunction sameKey(left, right) {\n return left === right || (left !== left && right !== right);\n}\nfunction fragment(hash, shift) {\n return (hash >>> shift) & 0b1_1111;\n}\nfunction bitPosition(hash, shift) {\n return 1 << fragment(hash, shift);\n}\nfunction populationCount(value) {\n let remaining = value >>> 0;\n remaining -= (remaining >>> 1) & 0x55555555;\n remaining = (remaining & 0x33333333) + ((remaining >>> 2) & 0x33333333);\n return (((remaining + (remaining >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24;\n}\nfunction childIndex(bitmap, bit) {\n return populationCount(bitmap & (bit - 1));\n}\nfunction createLeaf(edit, hash, key, value) {\n return { kind: \"leaf\", edit, hash, entries: [[key, value]] };\n}\nfunction editableLeaf(node, edit, instrumentation) {\n if (edit !== null && node.edit === edit)\n return node;\n if (instrumentation !== undefined)\n instrumentation.work.hamtNodesCopied += 1;\n return { ...node, edit, entries: node.entries.slice() };\n}\nfunction editableBranch(node, edit, instrumentation) {\n if (edit !== null && node.edit === edit)\n return node;\n if (instrumentation !== undefined)\n instrumentation.work.hamtNodesCopied += 1;\n return { ...node, edit, children: node.children.slice() };\n}\nfunction mergeLeaves(shift, left, right, edit) {\n const leftBit = bitPosition(left.hash, shift);\n const rightBit = bitPosition(right.hash, shift);\n if (leftBit === rightBit) {\n return {\n kind: \"branch\",\n edit,\n bitmap: leftBit,\n children: [mergeLeaves(shift + 5, left, right, edit)],\n };\n }\n return {\n kind: \"branch\",\n edit,\n bitmap: leftBit | rightBit,\n children: leftBit >>> 0 < rightBit >>> 0 ? [left, right] : [right, left],\n };\n}\nfunction setNode(node, shift, hash, key, value, edit, instrumentation) {\n if (node === null) {\n return {\n node: createLeaf(edit, hash, key, value),\n changed: true,\n sizeDelta: 1,\n };\n }\n if (node.kind === \"leaf\") {\n if (node.hash !== hash) {\n return {\n node: mergeLeaves(shift, node, createLeaf(edit, hash, key, value), edit),\n changed: true,\n sizeDelta: 1,\n };\n }\n const entryIndex = node.entries.findIndex(([entryKey]) => sameKey(entryKey, key));\n if (entryIndex >= 0) {\n if (Object.is(node.entries[entryIndex][1], value)) {\n return { node, changed: false, sizeDelta: 0 };\n }\n const updated = editableLeaf(node, edit, instrumentation);\n updated.entries[entryIndex] = [key, value];\n return { node: updated, changed: true, sizeDelta: 0 };\n }\n const updated = editableLeaf(node, edit, instrumentation);\n updated.entries.push([key, value]);\n return { node: updated, changed: true, sizeDelta: 1 };\n }\n const bit = bitPosition(hash, shift);\n const index = childIndex(node.bitmap, bit);\n if ((node.bitmap & bit) === 0) {\n const updated = editableBranch(node, edit, instrumentation);\n updated.bitmap |= bit;\n updated.children.splice(index, 0, createLeaf(edit, hash, key, value));\n return { node: updated, changed: true, sizeDelta: 1 };\n }\n const childChange = setNode(node.children[index], shift + 5, hash, key, value, edit, instrumentation);\n if (!childChange.changed)\n return { node, changed: false, sizeDelta: 0 };\n const updated = editableBranch(node, edit, instrumentation);\n updated.children[index] = childChange.node;\n return {\n node: updated,\n changed: true,\n sizeDelta: childChange.sizeDelta,\n };\n}\nfunction deleteNode(node, shift, hash, key, edit, instrumentation) {\n if (node === null)\n return { node, changed: false, sizeDelta: 0 };\n if (node.kind === \"leaf\") {\n if (node.hash !== hash)\n return { node, changed: false, sizeDelta: 0 };\n const entryIndex = node.entries.findIndex(([entryKey]) => sameKey(entryKey, key));\n if (entryIndex < 0)\n return { node, changed: false, sizeDelta: 0 };\n if (node.entries.length === 1) {\n return { node: null, changed: true, sizeDelta: -1 };\n }\n const updated = editableLeaf(node, edit, instrumentation);\n updated.entries.splice(entryIndex, 1);\n return { node: updated, changed: true, sizeDelta: -1 };\n }\n const bit = bitPosition(hash, shift);\n if ((node.bitmap & bit) === 0) {\n return { node, changed: false, sizeDelta: 0 };\n }\n const index = childIndex(node.bitmap, bit);\n const childChange = deleteNode(node.children[index], shift + 5, hash, key, edit, instrumentation);\n if (!childChange.changed)\n return { node, changed: false, sizeDelta: 0 };\n const updated = editableBranch(node, edit, instrumentation);\n if (childChange.node === null) {\n updated.bitmap &= ~bit;\n updated.children.splice(index, 1);\n if (updated.children.length === 0) {\n return { node: null, changed: true, sizeDelta: -1 };\n }\n }\n else {\n updated.children[index] = childChange.node;\n }\n if (updated.children.length === 1 && updated.children[0].kind === \"leaf\") {\n return { node: updated.children[0], changed: true, sizeDelta: -1 };\n }\n return { node: updated, changed: true, sizeDelta: -1 };\n}\nfunction lookupEntry(root, hash, key) {\n let node = root;\n let shift = 0;\n while (node !== null) {\n if (node.kind === \"leaf\") {\n if (node.hash !== hash)\n return undefined;\n return node.entries.find(([entryKey]) => sameKey(entryKey, key));\n }\n const bit = bitPosition(hash, shift);\n if ((node.bitmap & bit) === 0)\n return undefined;\n node = node.children[childIndex(node.bitmap, bit)];\n shift += 5;\n }\n return undefined;\n}\nfunction nodePath(root, hash) {\n const path = [];\n let node = root;\n let shift = 0;\n while (node !== null) {\n path.push(node);\n if (node.kind === \"leaf\")\n break;\n const bit = bitPosition(hash, shift);\n if ((node.bitmap & bit) === 0)\n break;\n node = node.children[childIndex(node.bitmap, bit)];\n shift += 5;\n }\n return path;\n}\n/**\n * Pre-order walk over an EXPLICIT stack, for the same reason the order-\n * statistic tree's walk uses one: `yield*` delegation routes every element\n * through one generator frame per trie level on its way out, so the cost of a\n * full walk scales with depth as well as size. The order-statistic tree\n * measured 30.04ms → 1.77ms at 50,000 entries on exactly this change; a\n * 32-way trie is shallower, so the win is smaller, but the shape is the same\n * mistake. Children are pushed in reverse so they pop in bitmap order —\n * iteration order is unspecified but must stay stable run to run.\n */\nfunction* iterateEntries(node) {\n if (node === null)\n return;\n const pending = [node];\n for (;;) {\n const visited = pending.pop();\n if (visited === undefined)\n return;\n if (visited.kind === \"leaf\") {\n for (const [key, value] of visited.entries)\n yield [key, value];\n continue;\n }\n for (let index = visited.children.length - 1; index >= 0; index -= 1) {\n const child = visited.children[index];\n if (child !== undefined)\n pending.push(child);\n }\n }\n}\nclass PersistentHashMap {\n #size;\n #root;\n #hash;\n #instrumentation;\n constructor(size, root, hash, instrumentation) {\n this.#size = size;\n this.#root = root;\n this.#hash = hash;\n this.#instrumentation = instrumentation;\n }\n get size() {\n return this.#size;\n }\n get(key) {\n return lookupEntry(this.#root, this.#hash(key) >>> 0, key)?.[1];\n }\n has(key) {\n return lookupEntry(this.#root, this.#hash(key) >>> 0, key) !== undefined;\n }\n set(key, value) {\n const change = setNode(this.#root, 0, this.#hash(key) >>> 0, key, value, null, this.#instrumentation);\n if (!change.changed)\n return this;\n return new PersistentHashMap(this.#size + change.sizeDelta, change.node, this.#hash, this.#instrumentation);\n }\n delete(key) {\n const change = deleteNode(this.#root, 0, this.#hash(key) >>> 0, key, null, this.#instrumentation);\n if (!change.changed)\n return this;\n return new PersistentHashMap(this.#size + change.sizeDelta, change.node, this.#hash, this.#instrumentation);\n }\n asTransient() {\n return new TransientHashMap(this.#size, this.#root, this.#hash, this.#instrumentation);\n }\n entries() {\n return iterateEntries(this.#root);\n }\n [inspectPersistentPath](key) {\n return nodePath(this.#root, this.#hash(key) >>> 0);\n }\n [attachInstrumentation](instrumentation) {\n return new PersistentHashMap(this.#size, this.#root, this.#hash, instrumentation);\n }\n}\nclass TransientHashMap {\n #size;\n #root;\n #hash;\n #edit = new TransientEditToken();\n #instrumentation;\n #frozen;\n constructor(size, root, hash, instrumentation) {\n this.#size = size;\n this.#root = root;\n this.#hash = hash;\n this.#instrumentation = instrumentation;\n }\n get size() {\n return this.#size;\n }\n get(key) {\n return lookupEntry(this.#root, this.#hash(key) >>> 0, key)?.[1];\n }\n has(key) {\n return lookupEntry(this.#root, this.#hash(key) >>> 0, key) !== undefined;\n }\n set(key, value) {\n this.#edit.assertEditable();\n const change = setNode(this.#root, 0, this.#hash(key) >>> 0, key, value, this.#edit, this.#instrumentation);\n this.#root = change.node;\n this.#size += change.sizeDelta;\n return this;\n }\n delete(key) {\n this.#edit.assertEditable();\n const change = deleteNode(this.#root, 0, this.#hash(key) >>> 0, key, this.#edit, this.#instrumentation);\n this.#root = change.node;\n this.#size += change.sizeDelta;\n return this;\n }\n freeze() {\n if (this.#frozen !== undefined)\n return this.#frozen;\n this.#edit.freeze();\n this.#frozen = new PersistentHashMap(this.#size, this.#root, this.#hash, this.#instrumentation);\n return this.#frozen;\n }\n entries() {\n return iterateEntries(this.#root);\n }\n [inspectTransientPath](key) {\n return nodePath(this.#root, this.#hash(key) >>> 0);\n }\n}\nexport function createPersistentMap() {\n return new PersistentHashMap(0, null, hashKey);\n}\nexport function instrumentPersistentMap(map, instrumentation) {\n if (instrumentation === undefined)\n return map;\n if (!(map instanceof PersistentHashMap)) {\n throw new TypeError(\"Instrumentation requires a map created by this module.\");\n }\n return map[attachInstrumentation](instrumentation);\n}\nexport function createPersistentMapForTesting(hash) {\n return new PersistentHashMap(0, null, hash);\n}\nexport function getPersistentMapPathForTesting(map, key) {\n if (!(map instanceof PersistentHashMap)) {\n throw new TypeError(\"Diagnostics require a map created by this module.\");\n }\n return map[inspectPersistentPath](key);\n}\nexport function getTransientMapPathForTesting(map, key) {\n if (!(map instanceof TransientHashMap)) {\n throw new TypeError(\"Diagnostics require a map created by this module.\");\n }\n return map[inspectTransientPath](key);\n}\n","var _a;\nimport { createPersistentMap } from \"./persistent-map\";\nimport { instrumentPersistentMap } from \"./persistent-map\";\nconst attachInstrumentation = Symbol(\"attachOrderInstrumentation\");\nconst createDeferredMeasureDraft = Symbol(\"createDeferredMeasureDraft\");\nconst buildFromSortedEntries = Symbol(\"buildFromSortedEntries\");\nclass TreeEditToken {\n #editable = true;\n assertEditable() {\n if (!this.#editable) {\n throw new Error(\"Cannot mutate a frozen transient order-statistic tree.\");\n }\n }\n freeze() {\n this.#editable = false;\n }\n}\nexport class PoisonedTransientOrderStatisticTreeError extends Error {\n code = \"poisoned-transient-order-statistic-tree\";\n constructor(cause) {\n super(\"Cannot use a transient order-statistic tree after a callback failure.\", { cause });\n this.name = \"PoisonedTransientOrderStatisticTreeError\";\n }\n}\nconst persistentRoots = new WeakMap();\nfunction sameId(left, right) {\n return left === right || (left !== left && right !== right);\n}\nfunction compareIds(left, right) {\n if (sameId(left, right))\n return 0;\n if (typeof left !== typeof right)\n return typeof left === \"number\" ? -1 : 1;\n if (typeof left === \"number\" && typeof right === \"number\") {\n if (Number.isNaN(left))\n return 1;\n if (Number.isNaN(right))\n return -1;\n return left < right ? -1 : 1;\n }\n return left < right ? -1 : 1;\n}\nfunction compareEntries(left, leftId, right, rightId, context) {\n const comparison = context.compare(left, right);\n if (comparison < 0)\n return -1;\n if (comparison > 0)\n return 1;\n return compareIds(leftId, rightId);\n}\nfunction nodeHeight(node) {\n return node?.height ?? 0;\n}\nfunction createNode(entry, id, context, edit) {\n const ownMeasure = context.measure.fromEntry(entry);\n return {\n edit,\n id,\n entry,\n ownMeasure,\n measure: ownMeasure,\n count: 1,\n height: 1,\n left: null,\n right: null,\n };\n}\nfunction editableNode(node, edit, instrumentation) {\n if (edit !== null && node.edit === edit)\n return node;\n if (instrumentation !== undefined)\n instrumentation.work.orderNodesCopied += 1;\n return { ...node, edit };\n}\nfunction refreshNode(node, context) {\n node.count = (node.left?.count ?? 0) + 1 + (node.right?.count ?? 0);\n node.height = 1 + Math.max(nodeHeight(node.left), nodeHeight(node.right));\n refreshNodeMeasure(node, context);\n}\nfunction refreshNodeMeasure(node, context) {\n const left = node.left?.measure ?? context.measure.empty;\n const right = node.right?.measure ?? context.measure.empty;\n node.measure = context.measure.combine(context.measure.combine(left, node.ownMeasure), right);\n}\nfunction refreshDeferredNodeMeasure(node, context) {\n let measure = node.ownMeasure;\n if (node.left !== null) {\n measure = context.measure.combine(node.left.measure, measure);\n }\n if (node.right !== null) {\n measure = context.measure.combine(measure, node.right.measure);\n }\n node.measure = measure;\n}\nfunction refreshNodeStructure(node) {\n node.count = (node.left?.count ?? 0) + 1 + (node.right?.count ?? 0);\n node.height = 1 + Math.max(nodeHeight(node.left), nodeHeight(node.right));\n}\nfunction refreshForMode(node, context, deferMeasure) {\n if (deferMeasure)\n refreshNodeStructure(node);\n else\n refreshNode(node, context);\n}\nfunction balanceFactor(node) {\n return nodeHeight(node.left) - nodeHeight(node.right);\n}\nfunction rotateRight(root, context, edit, deferMeasure = false) {\n const lower = editableNode(root, edit, context.instrumentation);\n const pivot = editableNode(lower.left, edit, context.instrumentation);\n lower.left = pivot.right;\n refreshForMode(lower, context, deferMeasure);\n pivot.right = lower;\n refreshForMode(pivot, context, deferMeasure);\n return pivot;\n}\nfunction rotateLeft(root, context, edit, deferMeasure = false) {\n const lower = editableNode(root, edit, context.instrumentation);\n const pivot = editableNode(lower.right, edit, context.instrumentation);\n lower.right = pivot.left;\n refreshForMode(lower, context, deferMeasure);\n pivot.left = lower;\n refreshForMode(pivot, context, deferMeasure);\n return pivot;\n}\nfunction rebalance(root, context, edit, deferMeasure = false) {\n refreshForMode(root, context, deferMeasure);\n const balance = balanceFactor(root);\n if (balance > 1) {\n if (balanceFactor(root.left) < 0) {\n root.left = rotateLeft(root.left, context, edit, deferMeasure);\n }\n return rotateRight(root, context, edit, deferMeasure);\n }\n if (balance < -1) {\n if (balanceFactor(root.right) > 0) {\n root.right = rotateRight(root.right, context, edit, deferMeasure);\n }\n return rotateLeft(root, context, edit, deferMeasure);\n }\n return root;\n}\nfunction insertNode(root, inserted, context, edit, deferMeasure = false) {\n if (root === null)\n return inserted;\n const comparison = compareEntries(inserted.entry, inserted.id, root.entry, root.id, context);\n if (comparison === 0)\n return root;\n const updated = editableNode(root, edit, context.instrumentation);\n if (comparison < 0) {\n updated.left = insertNode(updated.left, inserted, context, edit, deferMeasure);\n }\n else {\n updated.right = insertNode(updated.right, inserted, context, edit, deferMeasure);\n }\n return rebalance(updated, context, edit, deferMeasure);\n}\nfunction extractMinimum(root, context, edit) {\n if (root.left === null)\n return { minimum: root, node: root.right };\n const extracted = extractMinimum(root.left, context, edit);\n const updated = editableNode(root, edit, context.instrumentation);\n updated.left = extracted.node;\n return {\n minimum: extracted.minimum,\n node: rebalance(updated, context, edit),\n };\n}\nfunction removeNode(root, removedEntry, removedId, context, edit) {\n if (root === null)\n return { node: null, changed: false };\n const comparison = compareEntries(removedEntry, removedId, root.entry, root.id, context);\n if (comparison === 0) {\n if (root.left === null)\n return { node: root.right, changed: true };\n if (root.right === null)\n return { node: root.left, changed: true };\n const extracted = extractMinimum(root.right, context, edit);\n const replacement = editableNode(extracted.minimum, edit, context.instrumentation);\n replacement.left = root.left;\n replacement.right = extracted.node;\n return {\n node: rebalance(replacement, context, edit),\n changed: true,\n };\n }\n if (comparison < 0) {\n const change = removeNode(root.left, removedEntry, removedId, context, edit);\n if (!change.changed)\n return { node: root, changed: false };\n const updated = editableNode(root, edit, context.instrumentation);\n updated.left = change.node;\n return { node: rebalance(updated, context, edit), changed: true };\n }\n const change = removeNode(root.right, removedEntry, removedId, context, edit);\n if (!change.changed)\n return { node: root, changed: false };\n const updated = editableNode(root, edit, context.instrumentation);\n updated.right = change.node;\n return { node: rebalance(updated, context, edit), changed: true };\n}\nfunction entryAtNode(root, index) {\n if (!Number.isInteger(index) || index < 0 || index >= (root?.count ?? 0)) {\n return undefined;\n }\n let node = root;\n let remaining = index;\n while (node !== null) {\n const leftCount = node.left?.count ?? 0;\n if (remaining < leftCount)\n node = node.left;\n else if (remaining === leftCount)\n return node.entry;\n else {\n remaining -= leftCount + 1;\n node = node.right;\n }\n }\n return undefined;\n}\nfunction rankOfNode(root, entry, id, context) {\n let node = root;\n let rank = 0;\n while (node !== null) {\n if (sameId(id, node.id))\n return rank + (node.left?.count ?? 0);\n const comparison = compareEntries(entry, id, node.entry, node.id, context);\n if (comparison < 0)\n node = node.left;\n else if (comparison > 0) {\n rank += (node.left?.count ?? 0) + 1;\n node = node.right;\n }\n else\n return rank + (node.left?.count ?? 0);\n }\n return undefined;\n}\nfunction normalizedBound(bound, size) {\n if (Number.isNaN(bound))\n return 0;\n return Math.max(0, Math.min(size, Math.trunc(bound)));\n}\nfunction appendRange(node, offset, start, end, result) {\n if (node === null || start >= end)\n return;\n const nodeRank = offset + (node.left?.count ?? 0);\n if (start < nodeRank)\n appendRange(node.left, offset, start, end, result);\n if (start <= nodeRank && nodeRank < end)\n result.push(node.entry);\n if (nodeRank + 1 < end) {\n appendRange(node.right, nodeRank + 1, start, end, result);\n }\n}\nfunction rangeFromNode(root, start, end) {\n const size = root?.count ?? 0;\n const normalizedStart = normalizedBound(start, size);\n const normalizedEnd = normalizedBound(end, size);\n if (normalizedStart >= normalizedEnd)\n return [];\n const result = [];\n appendRange(root, 0, normalizedStart, normalizedEnd, result);\n return result;\n}\n/**\n * In-order walk over an EXPLICIT stack, and it must stay that way.\n *\n * The obvious shape — `yield* iterateEntries(node.left)` — makes every\n * element bubble up through one generator frame per tree level on its way\n * out, so walking n entries of a ~log2(n)-deep tree costs O(n log n)\n * generator resumptions rather than O(n). Measured on a 50,000-entry tree:\n * `yield*` delegation 30.04ms, this shape 1.77ms. The delegating version is\n * shorter and 17× slower; do not \"simplify\" it back.\n *\n * Laziness is part of the contract — callers step this iterator across\n * cooperative-transition slices — so materializing into an array here is not\n * an option either. Callers that materialize anyway should use `range(0,\n * size)`, which is faster still because it never suspends.\n */\nfunction* iterateEntries(node) {\n const pending = [];\n let current = node;\n for (;;) {\n while (current !== null) {\n pending.push(current);\n current = current.left;\n }\n const visited = pending.pop();\n if (visited === undefined)\n return;\n yield visited.entry;\n current = visited.right;\n }\n}\n/**\n * The transient walk, same explicit-stack shape and same reason (see\n * `iterateEntries`), plus the liveness guard a draft owes its callers: the\n * draft is checked on first resumption and again before every element, so a\n * walk in flight when the draft freezes or is abandoned fails on its next\n * step rather than yielding from a structure that has moved on.\n */\nfunction* iterateTransientEntries(node, assertHealthy) {\n assertHealthy();\n const pending = [];\n let current = node;\n for (;;) {\n while (current !== null) {\n pending.push(current);\n current = current.left;\n }\n const visited = pending.pop();\n if (visited === undefined)\n return;\n assertHealthy();\n yield visited.entry;\n current = visited.right;\n }\n}\nclass PersistentOrderStatisticTree {\n #root;\n #byId;\n #context;\n constructor(root, byId, context) {\n this.#root = root;\n this.#byId = byId;\n this.#context = context;\n persistentRoots.set(this, root);\n }\n get size() {\n return this.#root?.count ?? 0;\n }\n get measure() {\n return this.#root?.measure ?? this.#context.measure.empty;\n }\n get(id) {\n return this.#byId.get(id);\n }\n entryAt(index) {\n return entryAtNode(this.#root, index);\n }\n rankOf(id) {\n const entry = this.#byId.get(id);\n if (entry === undefined && !this.#byId.has(id))\n return undefined;\n return rankOfNode(this.#root, entry, id, this.#context);\n }\n range(start, end) {\n return rangeFromNode(this.#root, start, end);\n }\n insertOrReplace(entry) {\n const id = this.#context.getId(entry);\n const previous = this.#byId.get(id);\n const exists = previous !== undefined || this.#byId.has(id);\n if (exists && Object.is(previous, entry))\n return this;\n let root = this.#root;\n if (exists) {\n const removal = removeNode(root, previous, id, this.#context, null);\n if (!removal.changed)\n return this;\n root = removal.node;\n }\n root = insertNode(root, createNode(entry, id, this.#context, null), this.#context, null);\n return new _a(root, this.#byId.set(id, entry), this.#context);\n }\n remove(id) {\n const entry = this.#byId.get(id);\n if (entry === undefined && !this.#byId.has(id))\n return this;\n const removal = removeNode(this.#root, entry, id, this.#context, null);\n if (!removal.changed)\n return this;\n return new _a(removal.node, this.#byId.delete(id), this.#context);\n }\n asTransient() {\n return new TransientOrderStatisticTreeImpl(this.#root, this.#byId.asTransient(), this.#context, false);\n }\n /**\n * The strict-order check is unconditional by default: a misordered build\n * silently corrupts every later rank and lookup, which is strictly worse\n * than the O(n) cost of checking. Duplicates compare 0 and are rejected by\n * the same check.\n *\n * `proof.orderIsProven` is the only opt-out, and it exists for the two\n * in-package callers whose input is strictly sorted BY CONSTRUCTION, not by\n * assumption:\n *\n * - `filter-rebuild` merges the captured visible tree's in-order walk (the\n * tree's own order, minus a skipped subset — still strictly increasing)\n * with a subset it just sorted under the identical composite comparator\n * (`compareWithSortKeys` then id). A merge of two strictly-increasing\n * sequences under one total order is strictly increasing, and the two\n * sequences are disjoint by id (a flipped-in row was not visible).\n * - `sort-rebuild` hands over `Array.sort` output under that same composite\n * comparator, id tiebreak included, so it is totally ordered and the ids\n * are unique because they come from a HAMT keyed by id.\n *\n * Any caller that cannot make that argument from its own code — including\n * every external caller, which is why the option is package-internal — must\n * leave the check on. The escape hatch buys n−1 comparator calls per commit\n * and nothing else; it is not worth taking on a hunch.\n */\n [buildFromSortedEntries](sorted, proof) {\n const context = this.#context;\n const entryIds = sorted.map((entry) => context.getId(entry));\n if (proof?.orderIsProven === true) {\n if (context.instrumentation !== undefined) {\n context.instrumentation.work.bulkOrderVerificationsSkipped += 1;\n }\n }\n else {\n for (let index = 1; index < sorted.length; index += 1) {\n const comparison = compareEntries(sorted[index - 1], entryIds[index - 1], sorted[index], entryIds[index], context);\n if (comparison >= 0) {\n throw new TypeError(\"Bulk build input must be strictly sorted by the tree's total order.\");\n }\n }\n }\n const byId = this.#buildById(sorted, entryIds, proof?.derivedById);\n const build = (low, high) => {\n if (low > high)\n return null;\n const middle = (low + high) >> 1;\n const node = createNode(sorted[middle], entryIds[middle], context, null);\n node.left = build(low, middle - 1);\n node.right = build(middle + 1, high);\n if (node.left !== null || node.right !== null) {\n refreshNode(node, context);\n }\n return node;\n };\n return new _a(build(0, sorted.length - 1), byId, context);\n }\n [createDeferredMeasureDraft]() {\n if (this.size !== 0) {\n throw new Error(\"Deferred measure drafts require an empty tree.\");\n }\n return new TransientOrderStatisticTreeImpl(this.#root, this.#byId.asTransient(), this.#context, true);\n }\n entries() {\n return iterateEntries(this.#root);\n }\n /**\n * Builds the id→entry map by whichever of the two routes does fewer map\n * operations, and the choice is made HERE because this is the only place\n * that holds both counts.\n *\n * - Refill: `sorted.length` inserts into a fresh transient.\n * - Derive: `removedIds.size` deletes plus `addedEntries.length` inserts on\n * a transient over the base map.\n *\n * CONSTRAINT — a derivation offered is not a derivation taken. Deriving is\n * only cheaper when its edit count is below the refill's insert count, and\n * the difference is not academic: at S2's 50,000-row target the filter drops\n * to 12,500 survivors, so an unconditional derivation ran **37,500 removes\n * to replace 12,500 inserts — three times the work**. Measured, on that\n * scenario, by single-variable A/B: 217.1ms settle with the derivation\n * always on against 208.3ms with it always off, and 15.3ms of the\n * interaction window's persistent-map time attributed to this method. The\n * comparison below is algebraically `removals < survivors` (the added\n * entries are inserted on either route and cancel), so a narrow flip\n * derives and a wide one refills.\n *\n * The derivation is otherwise a CLAIM, and only one half of it is verified.\n * The\n * post-edit size check below is O(1) and catches the whole class of\n * \"wrong edit set\" slips (leavers left in, an added entry missing, a\n * duplicate id). What it cannot catch is a STALE survivor: derived mode\n * never touches an id that is neither removed nor added, so it keeps\n * whatever entry object the base map held for it. That is only correct\n * when the caller REUSES survivors' entry objects by identity, which is\n * exactly the precondition filter-rebuild's merge satisfies (a still-passing\n * row is unflipped, so its record and keys are both unchanged) and exactly\n * the one sort-rebuild does NOT: it allocates a fresh entry per row to\n * carry the new plan's keys, so its survivors are new objects and derived\n * mode would leave the map pointing at the previous plan's entries. That is\n * why sort-rebuild takes `orderIsProven` and nothing else.\n */\n #buildById(sorted, entryIds, derived) {\n const context = this.#context;\n if (derived !== undefined &&\n !(derived.base instanceof _a)) {\n // Checked before the routing decision, so an unusable base is a hard\n // error rather than a silent fall-through to the refill.\n throw new TypeError(\"Derived bulk-build maps require a base tree created by this module.\");\n }\n if (derived === undefined ||\n derived.removedIds.size + derived.addedEntries.length >= sorted.length) {\n const draft = createPersistentMap().asTransient();\n for (let index = 0; index < sorted.length; index += 1) {\n draft.set(entryIds[index], sorted[index]);\n }\n return draft.freeze();\n }\n const base = derived.base;\n // The base map is taken as-is rather than re-instrumented: the refill it\n // replaces built into a FRESH, uninstrumented map, so re-instrumenting\n // here would start charging visible-index byId churn to\n // `hamtNodesCopied` — the counter the suite uses as the record-rebuild\n // proxy, which must stay zero across a filter commit. The derivation's\n // own cost is reported by `bulkByIdDerived` instead.\n const draft = base.#byId.asTransient();\n for (const id of derived.removedIds)\n draft.delete(id);\n for (const entry of derived.addedEntries) {\n draft.set(context.getId(entry), entry);\n }\n const byId = draft.freeze();\n if (byId.size !== sorted.length) {\n throw new TypeError(\"Derived bulk-build map size must equal the built entry count.\");\n }\n if (context.instrumentation !== undefined) {\n context.instrumentation.work.bulkByIdDerived += 1;\n }\n return byId;\n }\n [attachInstrumentation](instrumentation, beforeCombine) {\n const measure = beforeCombine === undefined\n ? this.#context.measure\n : {\n ...this.#context.measure,\n combine: (left, right) => {\n beforeCombine();\n return this.#context.measure.combine(left, right);\n },\n };\n return new _a(this.#root, instrumentPersistentMap(this.#byId, instrumentation), { ...this.#context, measure, instrumentation });\n }\n}\n_a = PersistentOrderStatisticTree;\nclass TransientOrderStatisticTreeImpl {\n #root;\n #byId;\n #context;\n #edit = new TreeEditToken();\n #deferredMeasure;\n #frozen;\n #measureFrames;\n #pendingMeasureCount = 0;\n #poisoned = false;\n #poisonCause;\n constructor(root, byId, context, deferredMeasure) {\n this.#root = root;\n this.#byId = byId;\n this.#context = context;\n this.#deferredMeasure = deferredMeasure;\n }\n #assertHealthy() {\n if (this.#poisoned) {\n throw new PoisonedTransientOrderStatisticTreeError(this.#poisonCause);\n }\n }\n #assertMutable() {\n this.#assertHealthy();\n this.#edit.assertEditable();\n }\n #guard(operation) {\n try {\n return operation();\n }\n catch (error) {\n this.#poisoned = true;\n this.#poisonCause = error;\n throw error;\n }\n }\n get size() {\n this.#assertHealthy();\n return this.#root?.count ?? 0;\n }\n get measure() {\n this.#assertHealthy();\n if (this.#deferredMeasure && this.#pendingMeasureCount > 0) {\n throw new Error(\"Deferred tree measures must seal before they are read.\");\n }\n return this.#root?.measure ?? this.#context.measure.empty;\n }\n get(id) {\n this.#assertHealthy();\n return this.#byId.get(id);\n }\n entryAt(index) {\n this.#assertHealthy();\n return entryAtNode(this.#root, index);\n }\n rankOf(id) {\n this.#assertHealthy();\n return this.#guard(() => {\n const entry = this.#byId.get(id);\n if (entry === undefined && !this.#byId.has(id))\n return undefined;\n return rankOfNode(this.#root, entry, id, this.#context);\n });\n }\n range(start, end) {\n this.#assertHealthy();\n return rangeFromNode(this.#root, start, end);\n }\n insertOrReplace(entry) {\n this.#assertMutable();\n if (this.#measureFrames !== undefined) {\n throw new Error(\"Cannot insert after deferred measure sealing started.\");\n }\n return this.#guard(() => {\n const id = this.#context.getId(entry);\n const previous = this.#byId.get(id);\n const exists = previous !== undefined || this.#byId.has(id);\n if (exists && Object.is(previous, entry))\n return this;\n let root = this.#root;\n if (exists) {\n const removal = removeNode(root, previous, id, this.#context, this.#edit);\n if (!removal.changed)\n return this;\n root = removal.node;\n }\n root = insertNode(root, createNode(entry, id, this.#context, this.#edit), this.#context, this.#edit, this.#deferredMeasure);\n this.#root = root;\n this.#byId.set(id, entry);\n if (this.#deferredMeasure)\n this.#pendingMeasureCount = this.size;\n return this;\n });\n }\n remove(id) {\n this.#assertMutable();\n if (this.#deferredMeasure) {\n throw new Error(\"Deferred measure drafts do not support removal.\");\n }\n return this.#guard(() => {\n const entry = this.#byId.get(id);\n if (entry === undefined && !this.#byId.has(id))\n return this;\n const removal = removeNode(this.#root, entry, id, this.#context, this.#edit);\n if (!removal.changed)\n return this;\n this.#root = removal.node;\n this.#byId.delete(id);\n return this;\n });\n }\n freeze() {\n this.#assertHealthy();\n if (this.#deferredMeasure && this.#pendingMeasureCount > 0) {\n throw new Error(\"Deferred tree measures must seal before freezing.\");\n }\n if (this.#frozen !== undefined)\n return this.#frozen;\n this.#edit.freeze();\n this.#frozen = new PersistentOrderStatisticTree(this.#root, this.#byId.freeze(), this.#context);\n return this.#frozen;\n }\n entries() {\n this.#assertHealthy();\n return iterateTransientEntries(this.#root, () => this.#assertHealthy());\n }\n get pendingMeasureCount() {\n this.#assertHealthy();\n return this.#deferredMeasure ? this.#pendingMeasureCount : 0;\n }\n sealMeasureStep() {\n this.#assertMutable();\n if (!this.#deferredMeasure || this.#pendingMeasureCount === 0)\n return true;\n return this.#guard(() => {\n if (this.#measureFrames === undefined) {\n this.#measureFrames =\n this.#root === null ? [] : [{ node: this.#root, exit: false }];\n }\n for (;;) {\n const frame = this.#measureFrames.pop();\n if (frame.exit) {\n refreshDeferredNodeMeasure(frame.node, this.#context);\n break;\n }\n else {\n this.#measureFrames.push({ node: frame.node, exit: true });\n if (frame.node.right !== null) {\n this.#measureFrames.push({ node: frame.node.right, exit: false });\n }\n if (frame.node.left !== null) {\n this.#measureFrames.push({ node: frame.node.left, exit: false });\n }\n }\n }\n this.#pendingMeasureCount -= 1;\n return this.#pendingMeasureCount === 0;\n });\n }\n}\n/** Creates an empty persistent AVL order-statistic tree. */\nexport function createOrderStatisticTree(options) {\n const context = {\n getId: options.getId,\n compare: options.compare,\n measure: {\n empty: options.measure.empty,\n fromEntry: options.measure.fromEntry,\n combine: options.measure.combine,\n },\n };\n return new PersistentOrderStatisticTree(null, createPersistentMap(), context);\n}\n/** Internal bulk-build primitive; deliberately omitted from the package index. */\nexport function createDeferredMeasureTransientOrderStatisticTree(tree) {\n if (!(tree instanceof PersistentOrderStatisticTree)) {\n throw new TypeError(\"Deferred measure drafts require a tree created by this module.\");\n }\n return tree[createDeferredMeasureDraft]();\n}\n/** Internal bulk-build primitive; deliberately omitted from the package index. */\nexport function compareOrderStatisticTreeIds(left, right) {\n return compareIds(left, right);\n}\n/**\n * Internal bulk-build primitive; deliberately omitted from the package index.\n *\n * Builds a balanced tree in O(n) from `sorted`, which must be strictly\n * increasing under `like`'s total order (comparator, ties broken by ID).\n * Throws TypeError when adjacent entries compare `>= 0` — misordered input,\n * equal-compare entries with misordered IDs, and duplicate IDs alike — or\n * when `like` was not created by this module.\n *\n * `proof` lets an in-package caller trade a claim it can prove from its own\n * construction for work the builder would otherwise redo; see\n * {@link BulkBuildProof}. Omitting it keeps every check on.\n */\nexport function createOrderStatisticTreeFromSortedEntries(like, sorted, proof) {\n if (!(like instanceof PersistentOrderStatisticTree)) {\n throw new TypeError(\"Bulk builds require a tree created by this module.\");\n }\n return like[buildFromSortedEntries](sorted, proof);\n}\nexport function instrumentOrderStatisticTree(tree, instrumentation) {\n if (instrumentation === undefined)\n return tree;\n if (!(tree instanceof PersistentOrderStatisticTree)) {\n throw new TypeError(\"Instrumentation requires an order tree created by this module.\");\n }\n return tree[attachInstrumentation](instrumentation);\n}\nexport function instrumentMeasuredOrderStatisticTree(tree, instrumentation, beforeCombine) {\n if (!(tree instanceof PersistentOrderStatisticTree)) {\n throw new TypeError(\"Instrumentation requires an order tree created by this module.\");\n }\n return tree[attachInstrumentation](instrumentation, beforeCombine);\n}\nfunction inspectNode(node) {\n if (node === null) {\n return { snapshot: null, balanced: true, count: 0, height: 0 };\n }\n const left = inspectNode(node.left);\n const right = inspectNode(node.right);\n const count = left.count + 1 + right.count;\n const height = 1 + Math.max(left.height, right.height);\n const balance = left.height - right.height;\n const snapshot = Object.freeze({\n id: node.id,\n count: node.count,\n height: node.height,\n balance,\n left: left.snapshot,\n right: right.snapshot,\n });\n return {\n snapshot,\n balanced: left.balanced &&\n right.balanced &&\n Math.abs(balance) <= 1 &&\n node.count === count &&\n node.height === height,\n count,\n height,\n };\n}\nfunction collectNodes(node, result) {\n if (node === null)\n return;\n result.add(node);\n collectNodes(node.left, result);\n collectNodes(node.right, result);\n}\nfunction countSharedNodes(node, candidates) {\n if (node === null)\n return 0;\n return ((candidates.has(node) ? 1 : 0) +\n countSharedNodes(node.left, candidates) +\n countSharedNodes(node.right, candidates));\n}\nexport function getOrderStatisticTreeDiagnosticsForTesting(tree, comparedWith) {\n if (!persistentRoots.has(tree)) {\n throw new TypeError(\"Diagnostics require a tree created by this module.\");\n }\n const root = persistentRoots.get(tree);\n const inspected = inspectNode(root);\n let sharedNodeCount = 0;\n if (comparedWith !== undefined) {\n if (!persistentRoots.has(comparedWith)) {\n throw new TypeError(\"Diagnostics require a tree created by this module.\");\n }\n const comparedRoot = persistentRoots.get(comparedWith);\n const candidates = new Set();\n collectNodes(comparedRoot, candidates);\n sharedNodeCount = countSharedNodes(root, candidates);\n }\n return Object.freeze({\n count: inspected.count,\n height: inspected.height,\n balanced: inspected.balanced,\n sharedNodeCount,\n root: inspected.snapshot,\n });\n}\n","/**\n * Immutable chunked slot-indexed vector: a chunk table over\n * `SLOT_VECTOR_CHUNK`-element chunks, copy-on-write per commit. A commit\n * touching k slots copies the table plus each touched chunk once — this is\n * what keeps old snapshots valid under slot reuse: every revision holds its\n * own table, so revision N still binds slot s to whatever row owned s at\n * revision N no matter what later commits do (M0 priced maintenance at\n * ~33–98µs per 100-write commit).\n *\n * Holes (`undefined`) are free slots. Iteration hole-skips, which is why no\n * separate \"live\" bitset exists (recorded plan deviation from the spec).\n */\nexport const SLOT_VECTOR_CHUNK = 1024;\nconst EMPTY = Object.freeze({ chunks: Object.freeze([]) });\nexport function emptySlotVector() {\n return EMPTY;\n}\nexport function slotVectorFromEntries(entries, capacity) {\n const tableSize = Math.ceil(capacity / SLOT_VECTOR_CHUNK);\n const limit = tableSize * SLOT_VECTOR_CHUNK;\n const chunks = new Array(tableSize);\n for (const [slot, value] of entries) {\n if (slot >= limit) {\n throw new RangeError(`Slot ${slot} is beyond capacity ${capacity}.`);\n }\n const index = (slot / SLOT_VECTOR_CHUNK) | 0;\n let chunk = chunks[index];\n if (chunk === undefined) {\n chunk = new Array(SLOT_VECTOR_CHUNK);\n chunks[index] = chunk;\n }\n chunk[slot % SLOT_VECTOR_CHUNK] = value;\n }\n return { chunks };\n}\nexport function slotVectorGet(vector, slot) {\n const chunk = vector.chunks[(slot / SLOT_VECTOR_CHUNK) | 0];\n return chunk === undefined ? undefined : chunk[slot % SLOT_VECTOR_CHUNK];\n}\n/**\n * One commit's writes (`undefined` value = clear the slot), COW: table copied\n * once, each touched chunk copied once. `capacity` may exceed the old\n * table's reach (allocator growth).\n *\n * `chunksTouched` counts every chunk this commit allocated or copied,\n * including a brand-new chunk created for a hole beyond the old table — that\n * counts as touched even though nothing was copied.\n */\nexport function slotVectorWithAll(vector, writes, capacity) {\n const tableSize = Math.max(vector.chunks.length, Math.ceil(capacity / SLOT_VECTOR_CHUNK));\n const limit = tableSize * SLOT_VECTOR_CHUNK;\n const chunks = new Array(tableSize);\n for (let i = 0; i < vector.chunks.length; i += 1)\n chunks[i] = vector.chunks[i];\n let chunksTouched = 0;\n for (const [slot, value] of writes) {\n if (slot >= limit) {\n throw new RangeError(`Slot ${slot} is beyond capacity ${capacity}.`);\n }\n const index = (slot / SLOT_VECTOR_CHUNK) | 0;\n // A chunk still equal to the base's (or absent) hasn't been copied for\n // this commit yet; after copy/create it is a fresh object, so identity\n // alone tells touched from untouched with no separate tracking set.\n if (chunks[index] === undefined || chunks[index] === vector.chunks[index]) {\n const existing = chunks[index];\n chunks[index] =\n existing === undefined\n ? new Array(SLOT_VECTOR_CHUNK)\n : existing.slice();\n chunksTouched += 1;\n }\n chunks[index][slot % SLOT_VECTOR_CHUNK] = value;\n }\n return { next: { chunks }, chunksTouched };\n}\n/** Hole-skipping walk in slot order. */\nexport function forEachSlotEntry(vector, callback) {\n for (let index = 0; index < vector.chunks.length; index += 1) {\n const chunk = vector.chunks[index];\n if (chunk === undefined)\n continue;\n const base = index * SLOT_VECTOR_CHUNK;\n for (let offset = 0; offset < chunk.length; offset += 1) {\n const value = chunk[offset];\n if (value !== undefined)\n callback(value, base + offset);\n }\n }\n}\n","import { sortKeysOf } from \"./compiled-query\";\n/**\n * Standalone module because both visible-index and group-index need it and\n * visible-index already imports group-index — either home would cycle.\n *\n * Decorates a record for tree residence: ONE store get, at insert time. The\n * record must already be evaluated (or swap-filled) under `queryPlan` —\n * `sortKeysOf` throws otherwise, which is the fail-loud contract. Entry keys\n * stay valid for the tree's lifetime because a tree is bound to one plan\n * (the A2 rebuild-or-reseed invariant) and row updates replace the entry.\n */\nexport function orderedRowEntry(queryPlan, record) {\n return Object.freeze({\n record,\n keys: sortKeysOf(queryPlan, record),\n });\n}\n","import { createDeferredMeasureTransientOrderStatisticTree, createOrderStatisticTree, instrumentMeasuredOrderStatisticTree, } from \"./order-statistic-tree\";\nconst attachInstrumentation = Symbol(\"attachAggregateInstrumentation\");\nconst createDeferredMeasureDraft = Symbol(\"createDeferredMeasureDraft\");\nconst DEVELOPMENT = process.env.NODE_ENV !== \"production\";\nexport function isScalarBuiltinAggregator(aggregator) {\n return aggregator === \"sum\" || aggregator === \"avg\" || aggregator === \"count\";\n}\nfunction aggregatableNumber(value) {\n return typeof value === \"number\" && !Number.isNaN(value);\n}\n// BigInt is a runtime requirement for exact sum/average accumulation, but\n// literal syntax (`1n`) is newer than the public package's ES2018 grammar\n// contract. Constructor calls preserve the arithmetic while allowing older\n// parsers and bundlers to load the package; consumers still need BigInt support\n// (native or polyfilled) at runtime.\nconst BIGINT_ZERO = BigInt(0);\nconst BIGINT_ONE = BigInt(1);\nconst BIGINT_TWO = BigInt(2);\nconst FRACTION_BITS = BigInt(52);\nconst FRACTION_MASK = (BIGINT_ONE << FRACTION_BITS) - BIGINT_ONE;\nconst IMPLICIT_BIT = BIGINT_ONE << FRACTION_BITS;\nconst SIGN_BIT = BIGINT_ONE << BigInt(63);\nconst MAX_FINITE_UNITS = ((BIGINT_ONE << BigInt(53)) - BIGINT_ONE) << BigInt(2045);\nconst OVERFLOW_THRESHOLD_UNITS = MAX_FINITE_UNITS + (BIGINT_ONE << BigInt(2044));\nconst BINARY64_VIEW = new DataView(new ArrayBuffer(8));\nfunction finiteNumberUnits(value) {\n BINARY64_VIEW.setFloat64(0, value);\n const bits = BINARY64_VIEW.getBigUint64(0);\n const negative = (bits & SIGN_BIT) !== BIGINT_ZERO;\n const exponent = Number((bits >> FRACTION_BITS) & BigInt(0x7ff));\n const fraction = bits & FRACTION_MASK;\n const magnitude = exponent === 0\n ? fraction\n : (IMPLICIT_BIT + fraction) << BigInt(exponent - 1);\n return negative ? -magnitude : magnitude;\n}\nfunction roundDivideEven(numerator, denominator) {\n const quotient = numerator / denominator;\n const remainder = numerator % denominator;\n const comparison = remainder * BIGINT_TWO - denominator;\n return comparison > BIGINT_ZERO ||\n (comparison === BIGINT_ZERO && (quotient & BIGINT_ONE) === BIGINT_ONE)\n ? quotient + BIGINT_ONE\n : quotient;\n}\nfunction bitLength(value) {\n return value.toString(2).length;\n}\nfunction floorLog2Ratio(numerator, denominator) {\n let exponent = bitLength(numerator) - bitLength(denominator);\n const belowCandidate = exponent >= 0\n ? numerator < denominator << BigInt(exponent)\n : numerator << BigInt(-exponent) < denominator;\n if (belowCandidate)\n exponent -= 1;\n return exponent;\n}\nfunction numberFromBits(bits) {\n BINARY64_VIEW.setBigUint64(0, bits);\n return BINARY64_VIEW.getFloat64(0);\n}\n/** Rounds an exact `(units / divisor) * 2^-1074` rational once to binary64. */\nfunction roundedUnits(units, divisor = BIGINT_ONE) {\n if (units === BIGINT_ZERO)\n return 0;\n const negative = units < BIGINT_ZERO;\n const magnitude = negative ? -units : units;\n if (magnitude >= OVERFLOW_THRESHOLD_UNITS * divisor) {\n return negative ? -Infinity : Infinity;\n }\n const exponent = floorLog2Ratio(magnitude, divisor);\n let shift = Math.max(0, exponent - 52);\n let significand = roundDivideEven(magnitude, divisor << BigInt(shift));\n if (significand >= BIGINT_ONE << BigInt(53)) {\n significand >>= BIGINT_ONE;\n shift += 1;\n }\n const sign = negative ? SIGN_BIT : BIGINT_ZERO;\n if (significand < IMPLICIT_BIT) {\n return numberFromBits(sign | significand);\n }\n const exponentBits = BigInt(shift + 1);\n return numberFromBits(sign | (exponentBits << FRACTION_BITS) | (significand - IMPLICIT_BIT));\n}\nfunction emptySumAccumulator() {\n return {\n finiteUnits: BIGINT_ZERO,\n count: 0,\n positiveInfinity: false,\n negativeInfinity: false,\n };\n}\nfunction accumulateSum(accumulator, value) {\n if (!aggregatableNumber(value))\n return accumulator;\n return {\n finiteUnits: Number.isFinite(value)\n ? accumulator.finiteUnits + finiteNumberUnits(value)\n : accumulator.finiteUnits,\n count: accumulator.count + 1,\n positiveInfinity: accumulator.positiveInfinity || value === Infinity,\n negativeInfinity: accumulator.negativeInfinity || value === -Infinity,\n };\n}\nfunction mergeSums(left, right) {\n return {\n finiteUnits: left.finiteUnits + right.finiteUnits,\n count: left.count + right.count,\n positiveInfinity: left.positiveInfinity || right.positiveInfinity,\n negativeInfinity: left.negativeInfinity || right.negativeInfinity,\n };\n}\nfunction finalizedSum(accumulator, average) {\n if (accumulator.count === 0)\n return null;\n if (accumulator.positiveInfinity && accumulator.negativeInfinity)\n return NaN;\n if (accumulator.positiveInfinity)\n return Infinity;\n if (accumulator.negativeInfinity)\n return -Infinity;\n return roundedUnits(accumulator.finiteUnits, average ? BigInt(accumulator.count) : BIGINT_ONE);\n}\nconst sum = {\n init: emptySumAccumulator,\n accumulate: accumulateSum,\n merge: mergeSums,\n finalize: (accumulator) => finalizedSum(accumulator, false),\n};\nconst avg = {\n init: sum.init,\n accumulate: sum.accumulate,\n merge: sum.merge,\n finalize: (accumulator) => finalizedSum(accumulator, true),\n};\nfunction extremum(kind) {\n return {\n init: () => ({ value: null }),\n accumulate(accumulator, value) {\n if (!aggregatableNumber(value))\n return accumulator;\n if (accumulator.value === null)\n return { value };\n return {\n value: kind === \"min\"\n ? value < accumulator.value\n ? value\n : accumulator.value\n : value > accumulator.value\n ? value\n : accumulator.value,\n };\n },\n merge(left, right) {\n if (left.value === null)\n return right;\n if (right.value === null)\n return left;\n return {\n value: kind === \"min\"\n ? right.value < left.value\n ? right.value\n : left.value\n : right.value > left.value\n ? right.value\n : left.value,\n };\n },\n finalize: (accumulator) => accumulator.value,\n };\n}\nconst count = {\n init: () => ({ count: 0 }),\n accumulate: (accumulator) => ({ count: accumulator.count + 1 }),\n merge: (left, right) => ({ count: left.count + right.count }),\n finalize: (accumulator) => accumulator.count === 0 ? null : accumulator.count,\n};\n/**\n * Pure, persistent-safe built-in monoids. Numeric admission, empty output, and\n * ordered extrema match the legacy grid. Sum and average intentionally use an\n * exact binary64 superaccumulator so cached merges are genuinely associative;\n * they round only once when finalized rather than reproducing history-dependent\n * floating-point folds.\n */\nexport const aggregateTreeBuiltinAggregators = Object.freeze({\n sum,\n avg,\n min: extremum(\"min\"),\n max: extremum(\"max\"),\n count,\n});\nfunction sameLeaf(left, right) {\n return (Object.is(left.row, right.row) &&\n Object.is(left.value, right.value) &&\n Object.is(left.dependency, right.dependency));\n}\nfunction normalizedLeaf(leaf) {\n // A frozen leaf with exactly the four data properties IS the canonical\n // shape (compiled queries freeze their leaves at construction); copying it\n // again on every insert was ~157ms of allocation + GC at 50k rows × 10\n // aggregated columns (#500 cycle 2 decision 3).\n if (Object.isFrozen(leaf) && Reflect.ownKeys(leaf).length === 4)\n return leaf;\n return Object.freeze({\n id: leaf.id,\n row: leaf.row,\n value: leaf.value,\n dependency: leaf.dependency,\n });\n}\nfunction containsSharedMemory(value, seen = new Set()) {\n if (value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")) {\n return false;\n }\n if (typeof SharedArrayBuffer !== \"undefined\" &&\n value instanceof SharedArrayBuffer) {\n return true;\n }\n if (seen.has(value))\n return false;\n seen.add(value);\n if (ArrayBuffer.isView(value) && containsSharedMemory(value.buffer, seen)) {\n return true;\n }\n if (value instanceof Map) {\n for (const [key, entry] of value) {\n if (containsSharedMemory(key, seen) ||\n containsSharedMemory(entry, seen)) {\n return true;\n }\n }\n }\n if (value instanceof Set) {\n for (const entry of value) {\n if (containsSharedMemory(entry, seen))\n return true;\n }\n }\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor !== undefined &&\n \"value\" in descriptor &&\n containsSharedMemory(descriptor.value, seen)) {\n return true;\n }\n }\n return false;\n}\nfunction finalizedValue(accumulator, aggregator, cache, custom, snapshotAccumulator) {\n if (!Object.is(cache.accumulator, accumulator)) {\n throw new Error(\"Aggregate finalization cache does not match its root.\");\n }\n if (!cache.ready) {\n let finalizedAccumulator = accumulator;\n if (custom &&\n accumulator !== null &&\n (typeof accumulator === \"object\" || typeof accumulator === \"function\")) {\n if (snapshotAccumulator !== undefined) {\n finalizedAccumulator = snapshotAccumulator(accumulator);\n if (Object.is(finalizedAccumulator, accumulator)) {\n throw new TypeError(\"snapshotAccumulator must return a detached accumulator.\");\n }\n }\n else {\n try {\n finalizedAccumulator = structuredClone(accumulator);\n }\n catch (error) {\n throw new TypeError(\"Custom aggregator accumulators must be structured-cloneable or provide snapshotAccumulator.\", { cause: error });\n }\n }\n if (containsSharedMemory(finalizedAccumulator)) {\n throw new TypeError(\"Finalized accumulator snapshots cannot contain SharedArrayBuffer-backed memory; provide snapshotAccumulator that copies it into detached storage.\");\n }\n }\n cache.output = aggregator.finalize(finalizedAccumulator);\n cache.ready = true;\n }\n return cache.output;\n}\nclass PersistentAggregateTree {\n #tree;\n #context;\n #cache;\n constructor(tree, context, cache) {\n this.#tree = tree;\n this.#context = context;\n this.#cache =\n cache !== undefined && Object.is(cache.accumulator, tree.measure)\n ? cache\n : { accumulator: tree.measure, ready: false };\n }\n get size() {\n return this.#tree.size;\n }\n firstId() {\n return this.#tree.entryAt(0)?.id;\n }\n insertOrReplace(leaf) {\n const previous = this.#tree.get(leaf.id);\n if (previous !== undefined && sameLeaf(previous, leaf))\n return this;\n const nextTree = this.#tree.insertOrReplace(normalizedLeaf(leaf));\n if (nextTree === this.#tree)\n return this;\n if (this.#context.custom) {\n this.#context.lawValidator?.observe({\n aggregator: this.#context.aggregator,\n columnId: this.#context.columnId,\n leafId: leaf.id,\n row: leaf.row,\n value: leaf.value,\n });\n }\n return new PersistentAggregateTree(nextTree, this.#context, this.#cache);\n }\n remove(id) {\n const nextTree = this.#tree.remove(id);\n return nextTree === this.#tree\n ? this\n : new PersistentAggregateTree(nextTree, this.#context, this.#cache);\n }\n finalize() {\n return finalizedValue(this.#tree.measure, this.#context.aggregator, this.#cache, this.#context.custom, this.#context.snapshotAccumulator);\n }\n asTransient() {\n return new TransientAggregateTreeImpl(this.#tree.asTransient(), this.#context, this.#cache);\n }\n [createDeferredMeasureDraft]() {\n return new TransientAggregateTreeImpl(createDeferredMeasureTransientOrderStatisticTree(this.#tree), this.#context, this.#cache);\n }\n [attachInstrumentation](instrumentation) {\n if (this.#context.instrumentation === instrumentation)\n return this;\n const tree = instrumentMeasuredOrderStatisticTree(this.#tree, instrumentation, () => {\n instrumentation.work.aggregateMerges += 1;\n });\n return new PersistentAggregateTree(tree, { ...this.#context, instrumentation }, this.#cache);\n }\n}\nclass TransientAggregateTreeImpl {\n #tree;\n #context;\n #cache;\n #frozen;\n constructor(tree, context, cache) {\n this.#tree = tree;\n this.#context = context;\n this.#cache = cache;\n }\n get size() {\n return this.#tree.size;\n }\n firstId() {\n return this.#tree.entryAt(0)?.id;\n }\n insertOrReplace(leaf) {\n const previous = this.#tree.get(leaf.id);\n if (previous !== undefined && sameLeaf(previous, leaf)) {\n this.#tree.insertOrReplace(previous);\n return this;\n }\n this.#tree.insertOrReplace(normalizedLeaf(leaf));\n if (this.#context.custom) {\n this.#context.lawValidator?.observe({\n aggregator: this.#context.aggregator,\n columnId: this.#context.columnId,\n leafId: leaf.id,\n row: leaf.row,\n value: leaf.value,\n });\n }\n return this;\n }\n remove(id) {\n this.#tree.remove(id);\n return this;\n }\n finalize() {\n const accumulator = this.#tree.measure;\n if (!Object.is(this.#cache.accumulator, accumulator)) {\n this.#cache = { accumulator, ready: false };\n }\n return finalizedValue(accumulator, this.#context.aggregator, this.#cache, this.#context.custom, this.#context.snapshotAccumulator);\n }\n freeze() {\n if (this.#frozen !== undefined)\n return this.#frozen;\n const tree = this.#tree.freeze();\n this.#frozen = new PersistentAggregateTree(tree, this.#context, this.#cache);\n return this.#frozen;\n }\n get pendingMeasureCount() {\n return \"pendingMeasureCount\" in this.#tree\n ? this.#tree.pendingMeasureCount\n : 0;\n }\n sealMeasureStep() {\n if (!(\"sealMeasureStep\" in this.#tree))\n return true;\n return this.#tree.sealMeasureStep();\n }\n}\nconst EMPTY_SCALAR_STATE = Object.freeze({\n size: 0,\n admitted: 0,\n finiteUnits: BIGINT_ZERO,\n positiveInfinities: 0,\n negativeInfinities: 0,\n});\nfunction scalarStateWith(state, value, direction) {\n // Admission is applied SYMMETRICALLY: a value the insert did not\n // accumulate (NaN, null, non-number) must not be subtracted on remove.\n if (!aggregatableNumber(value)) {\n return { ...state, size: state.size + direction };\n }\n return {\n size: state.size + direction,\n admitted: state.admitted + direction,\n finiteUnits: Number.isFinite(value)\n ? direction === 1\n ? state.finiteUnits + finiteNumberUnits(value)\n : state.finiteUnits - finiteNumberUnits(value)\n : state.finiteUnits,\n positiveInfinities: state.positiveInfinities + (value === Infinity ? direction : 0),\n negativeInfinities: state.negativeInfinities + (value === -Infinity ? direction : 0),\n };\n}\nfunction finalizeScalarState(kind, state) {\n if (kind === \"count\")\n return state.size === 0 ? null : state.size;\n if (state.admitted === 0)\n return null;\n if (state.positiveInfinities > 0 && state.negativeInfinities > 0)\n return NaN;\n if (state.positiveInfinities > 0)\n return Infinity;\n if (state.negativeInfinities > 0)\n return -Infinity;\n return roundedUnits(state.finiteUnits, kind === \"avg\" ? BigInt(state.admitted) : BIGINT_ONE);\n}\nfunction requireRemovedLeaf(columnId, state, removedLeaf) {\n if (removedLeaf === undefined) {\n throw new TypeError(`Scalar aggregate cell for column ${columnId} needs the originally-inserted leaf to remove a row.`);\n }\n if (state.size === 0) {\n throw new Error(`Scalar aggregate cell for column ${columnId} removed a row it never inserted.`);\n }\n return removedLeaf;\n}\n/**\n * O(1) accumulator cell for `sum`/`avg`/`count` behind the aggregate-root\n * interface (#500 cycle 2 decision A): insert accumulates inline, remove\n * applies the exact inverse from the originally-inserted leaf, and there is\n * no per-row structure at all — so no seal work and no `firstId` (its only\n * consumer is custom-finalizer error context, and customs keep the tree).\n */\nclass ScalarAggregateCell {\n #kind;\n #columnId;\n #state;\n #output = null;\n #finalized = false;\n constructor(kind, columnId, state) {\n this.#kind = kind;\n this.#columnId = columnId;\n this.#state = state;\n }\n get size() {\n return this.#state.size;\n }\n firstId() {\n return undefined;\n }\n insertOrReplace(leaf) {\n return new ScalarAggregateCell(this.#kind, this.#columnId, scalarStateWith(this.#state, leaf.value, 1));\n }\n remove(id, removedLeaf) {\n void id;\n const leaf = requireRemovedLeaf(this.#columnId, this.#state, removedLeaf);\n return new ScalarAggregateCell(this.#kind, this.#columnId, scalarStateWith(this.#state, leaf.value, -1));\n }\n finalize() {\n if (!this.#finalized) {\n this.#output = finalizeScalarState(this.#kind, this.#state);\n this.#finalized = true;\n }\n return this.#output;\n }\n asTransient() {\n return new TransientScalarAggregateCell(this.#kind, this.#columnId, this.#state);\n }\n}\n/**\n * The mutable draft counterpart. It satisfies the deferred-measure draft\n * surface with a permanently-empty measure queue: scalar cells accumulate at\n * insert, so they charge NO seal units (#500 cycle 2).\n */\nclass TransientScalarAggregateCell {\n #kind;\n #columnId;\n #state;\n #frozen;\n constructor(kind, columnId, state) {\n this.#kind = kind;\n this.#columnId = columnId;\n this.#state = state;\n }\n get size() {\n return this.#state.size;\n }\n firstId() {\n return undefined;\n }\n #assertMutable() {\n if (this.#frozen !== undefined) {\n throw new Error(`Scalar aggregate cell draft for column ${this.#columnId} is frozen.`);\n }\n }\n insertOrReplace(leaf) {\n this.#assertMutable();\n this.#state = scalarStateWith(this.#state, leaf.value, 1);\n return this;\n }\n remove(id, removedLeaf) {\n void id;\n this.#assertMutable();\n const leaf = requireRemovedLeaf(this.#columnId, this.#state, removedLeaf);\n this.#state = scalarStateWith(this.#state, leaf.value, -1);\n return this;\n }\n finalize() {\n return finalizeScalarState(this.#kind, this.#state);\n }\n freeze() {\n this.#frozen ??= new ScalarAggregateCell(this.#kind, this.#columnId, this.#state);\n return this.#frozen;\n }\n get pendingMeasureCount() {\n return 0;\n }\n sealMeasureStep() {\n return true;\n }\n}\nexport function createScalarAggregateCell(options) {\n return new ScalarAggregateCell(options.aggregator, options.columnId, EMPTY_SCALAR_STATE);\n}\nexport function isScalarAggregateCell(value) {\n return (value instanceof ScalarAggregateCell ||\n value instanceof TransientScalarAggregateCell);\n}\n/** Internal bulk-build primitive; deliberately omitted from the package index. */\nexport function createDeferredMeasureTransientAggregateTree(tree) {\n if (!(tree instanceof PersistentAggregateTree)) {\n throw new TypeError(\"Deferred measure drafts require an aggregate tree created by this module.\");\n }\n return tree[createDeferredMeasureDraft]();\n}\nexport function createAggregateTree(options) {\n const custom = typeof options.aggregator !== \"string\";\n const aggregator = (custom\n ? options.aggregator\n : aggregateTreeBuiltinAggregators[options.aggregator]);\n const context = {\n columnId: options.columnId,\n aggregator,\n lawValidator: DEVELOPMENT && custom\n ? options.lawValidator\n : undefined,\n snapshotAccumulator: custom\n ? (options.snapshotAccumulator ?? aggregator.snapshotAccumulator)\n : undefined,\n custom,\n };\n const tree = createOrderStatisticTree({\n getId: (leaf) => leaf.id,\n compare: options.compare ?? (() => 0),\n measure: {\n empty: aggregator.init(),\n fromEntry: (leaf) => aggregator.accumulate(aggregator.init(), leaf.value, leaf.row),\n combine: aggregator.merge,\n },\n });\n return new PersistentAggregateTree(tree, context);\n}\nexport function instrumentAggregateTree(tree, instrumentation) {\n if (instrumentation === undefined)\n return tree;\n // Scalar cells do no tree merges — nothing to instrument.\n if (tree instanceof ScalarAggregateCell)\n return tree;\n if (!(tree instanceof PersistentAggregateTree)) {\n throw new TypeError(\"Instrumentation requires an aggregate tree created by this module.\");\n }\n return tree[attachInstrumentation](instrumentation);\n}\n","import { compareWithSortKeys, filterVerdict, } from \"./compiled-query\";\nimport { PretableInvalidGroupKeyError, PretableRowModelError, } from \"./errors\";\nimport { orderedRowEntry } from \"./ordered-row-entry\";\nimport { createAggregateTree, createDeferredMeasureTransientAggregateTree, createScalarAggregateCell, instrumentAggregateTree, isScalarBuiltinAggregator, } from \"./persistent/aggregate-tree\";\nimport { createOrderStatisticTree, instrumentOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { createPersistentMap, instrumentPersistentMap, } from \"./persistent/persistent-map\";\nconst visibleRangeDiagnostics = new WeakMap();\nexport function getVisibleRangeDiagnosticsForTesting(range) {\n const diagnostics = visibleRangeDiagnostics.get(range);\n if (diagnostics === undefined) {\n throw new TypeError(\"Diagnostics require a grouped visible range.\");\n }\n return diagnostics;\n}\nconst EMPTY_COUNTS = Object.freeze({\n collapsed: 0,\n expanded: 0,\n throughDepth: Object.freeze([]),\n data: 0,\n dataCollapsed: 0,\n dataExpanded: 0,\n dataThroughDepth: Object.freeze([]),\n});\nconst groupIndexInstrumentation = new WeakMap();\nconst groupedIndex = Symbol(\"pretable.grouped-index\");\n/**\n * The grouped half of the filter-verdict seam (see `./filter-membership`,\n * which owns the seam's documentation and re-exports this). It lives here\n * because it reads this module's internal invariant: EVERY inserted row gets\n * a `rowParents` entry, but only a PASSING row is inserted into its leaf\n * group's `leaves` tree — so leaf membership is the stored verdict, and a row\n * this index never saw is simply not a member.\n */\nexport function rowPassesFilterInGroupIndex(grouped, rowId) {\n const parentGroupId = grouped.rowParents.get(rowId);\n if (parentGroupId === undefined)\n return false;\n return grouped.groups.get(parentGroupId)?.leaves.get(rowId) !== undefined;\n}\nexport function getGroupIndex(visible) {\n return visible[groupedIndex];\n}\nexport function attachGroupIndex(rows, groups) {\n return Object.freeze({ rows, [groupedIndex]: groups });\n}\nfunction escape(raw) {\n return raw.replace(/%/g, \"%25\").replace(/\\//g, \"%2F\").replace(/=/g, \"%3D\");\n}\n/** Canonical equality/identity key. Null and undefined intentionally share the legacy blank group. */\nexport function encodeGroupValue(value, context) {\n if (value === null || value === undefined)\n return \"~\";\n if (typeof value === \"string\")\n return `s:${value}`;\n if (typeof value === \"number\") {\n if (Number.isNaN(value))\n return \"n:NaN\";\n if (Object.is(value, -0))\n return \"n:-0\";\n return `n:${String(value)}`;\n }\n if (typeof value === \"boolean\")\n return `b:${String(value)}`;\n if (typeof value === \"bigint\")\n return `i:${String(value)}`;\n throw new PretableInvalidGroupKeyError(context?.operation ?? \"set-query\", context?.rowId, context?.columnId ?? \"<unknown>\", value);\n}\nexport function makeGroupId(path) {\n return `__group__:${path\n .map((entry) => `${escape(entry.columnId)}=${escape(encodeGroupValue(entry.value))}`)\n .join(\"/\")}`;\n}\nfunction combineCounts(left, right) {\n const length = Math.max(left.throughDepth.length, right.throughDepth.length);\n const throughDepth = Array.from({ length }, (_, index) => (left.throughDepth[index] ?? 0) + (right.throughDepth[index] ?? 0));\n const dataLength = Math.max(left.dataThroughDepth.length, right.dataThroughDepth.length);\n return Object.freeze({\n collapsed: left.collapsed + right.collapsed,\n expanded: left.expanded + right.expanded,\n throughDepth: Object.freeze(throughDepth),\n data: left.data + right.data,\n dataCollapsed: left.dataCollapsed + right.dataCollapsed,\n dataExpanded: left.dataExpanded + right.dataExpanded,\n dataThroughDepth: Object.freeze(Array.from({ length: dataLength }, (_, index) => (left.dataThroughDepth[index] ?? 0) +\n (right.dataThroughDepth[index] ?? 0))),\n });\n}\nfunction groupCounts(depth, levelCount, override, descendants) {\n const count = (expanded, descendant) => (override ?? expanded) ? 1 + descendant : 1;\n return Object.freeze({\n collapsed: count(false, descendants.collapsed),\n expanded: count(true, descendants.expanded),\n throughDepth: Object.freeze(Array.from({ length: levelCount }, (_, policyDepth) => count(depth <= policyDepth, descendants.throughDepth[policyDepth] ?? 0))),\n data: descendants.data,\n dataCollapsed: (override ?? false) ? descendants.dataCollapsed : 0,\n dataExpanded: (override ?? true) ? descendants.dataExpanded : 0,\n dataThroughDepth: Object.freeze(Array.from({ length: levelCount }, (_, policyDepth) => (override ?? depth <= policyDepth)\n ? (descendants.dataThroughDepth[policyDepth] ?? 0)\n : 0)),\n });\n}\nfunction dataCountForPolicy(counts, policy) {\n if (policy.kind === \"expanded\")\n return counts.dataExpanded;\n if (policy.kind === \"collapsed\")\n return counts.dataCollapsed;\n if (policy.depth < 0)\n return counts.dataCollapsed;\n return (counts.dataThroughDepth[Math.min(policy.depth, counts.dataThroughDepth.length - 1)] ?? counts.dataExpanded);\n}\nfunction countForPolicy(counts, policy) {\n if (policy.kind === \"expanded\")\n return counts.expanded;\n if (policy.kind === \"collapsed\")\n return counts.collapsed;\n if (policy.depth < 0)\n return counts.collapsed;\n return (counts.throughDepth[Math.min(policy.depth, counts.throughDepth.length - 1)] ?? counts.expanded);\n}\nfunction measuredHeight(node) {\n return node?.height ?? 0;\n}\nfunction measuredNode(entry, left, right, instrumentation) {\n if (instrumentation !== undefined)\n instrumentation.work.groupNodesCopied += 1;\n return Object.freeze({\n entry,\n left,\n right,\n height: 1 + Math.max(measuredHeight(left), measuredHeight(right)),\n size: (left?.size ?? 0) + 1 + (right?.size ?? 0),\n measure: combineCounts(combineCounts(left?.measure ?? EMPTY_COUNTS, entry.counts), right?.measure ?? EMPTY_COUNTS),\n });\n}\nfunction measuredBalance(node, instrumentation) {\n const factor = measuredHeight(node.left) - measuredHeight(node.right);\n if (factor > 1) {\n let left = node.left;\n if (measuredHeight(left.left) < measuredHeight(left.right)) {\n const pivot = left.right;\n left = measuredNode(pivot.entry, measuredNode(left.entry, left.left, pivot.left, instrumentation), pivot.right, instrumentation);\n }\n return measuredNode(left.entry, left.left, measuredNode(node.entry, left.right, node.right, instrumentation), instrumentation);\n }\n if (factor < -1) {\n let right = node.right;\n if (measuredHeight(right.right) < measuredHeight(right.left)) {\n const pivot = right.left;\n right = measuredNode(pivot.entry, pivot.left, measuredNode(right.entry, pivot.right, right.right, instrumentation), instrumentation);\n }\n return measuredNode(right.entry, measuredNode(node.entry, node.left, right.left, instrumentation), right.right, instrumentation);\n }\n return measuredNode(node.entry, node.left, node.right, instrumentation);\n}\nfunction compareGroupIds(left, right) {\n return left === right ? 0 : left < right ? -1 : 1;\n}\nclass PersistentMeasuredGroupTree {\n #root;\n #byId;\n #compare;\n #instrumentation;\n constructor(root, byId, compare, instrumentation) {\n this.#root = root;\n this.#byId = byId;\n this.#compare = compare;\n this.#instrumentation = instrumentation;\n }\n get size() {\n return this.#root?.size ?? 0;\n }\n get measure() {\n return this.#root?.measure ?? EMPTY_COUNTS;\n }\n withInstrumentation(instrumentation) {\n if (instrumentation === this.#instrumentation)\n return this;\n return new PersistentMeasuredGroupTree(this.#root, instrumentPersistentMap(this.#byId, instrumentation), this.#compare, instrumentation);\n }\n get(groupId) {\n return this.#byId.get(groupId);\n }\n #compareEntries(left, right) {\n const result = this.#compare(left, right);\n return result < 0\n ? -1\n : result > 0\n ? 1\n : compareGroupIds(left.groupId, right.groupId);\n }\n #insert(root, entry) {\n if (root === null)\n return measuredNode(entry, null, null, this.#instrumentation);\n const comparison = this.#compareEntries(entry, root.entry);\n return comparison < 0\n ? measuredBalance(measuredNode(root.entry, this.#insert(root.left, entry), root.right, this.#instrumentation), this.#instrumentation)\n : measuredBalance(measuredNode(root.entry, root.left, this.#insert(root.right, entry), this.#instrumentation), this.#instrumentation);\n }\n #extractMinimum(root) {\n if (root.left === null)\n return [root, root.right];\n const [minimum, left] = this.#extractMinimum(root.left);\n return [\n minimum,\n measuredBalance(measuredNode(root.entry, left, root.right, this.#instrumentation), this.#instrumentation),\n ];\n }\n #remove(root, entry) {\n if (root === null)\n return null;\n const comparison = this.#compareEntries(entry, root.entry);\n if (comparison < 0)\n return measuredBalance(measuredNode(root.entry, this.#remove(root.left, entry), root.right, this.#instrumentation), this.#instrumentation);\n if (comparison > 0)\n return measuredBalance(measuredNode(root.entry, root.left, this.#remove(root.right, entry), this.#instrumentation), this.#instrumentation);\n if (root.left === null)\n return root.right;\n if (root.right === null)\n return root.left;\n const [minimum, right] = this.#extractMinimum(root.right);\n return measuredBalance(measuredNode(minimum.entry, root.left, right, this.#instrumentation), this.#instrumentation);\n }\n insertOrReplace(entry) {\n const previous = this.#byId.get(entry.groupId);\n if (previous === entry)\n return this;\n const without = previous === undefined ? this.#root : this.#remove(this.#root, previous);\n return new PersistentMeasuredGroupTree(this.#insert(without, entry), this.#byId.set(entry.groupId, entry), this.#compare, this.#instrumentation);\n }\n remove(groupId) {\n const previous = this.#byId.get(groupId);\n if (previous === undefined)\n return this;\n return new PersistentMeasuredGroupTree(this.#remove(this.#root, previous), this.#byId.delete(groupId), this.#compare, this.#instrumentation);\n }\n *entries() {\n function* walk(node) {\n if (node === null)\n return;\n yield* walk(node.left);\n yield node.entry;\n yield* walk(node.right);\n }\n yield* walk(this.#root);\n }\n select(index, policy) {\n if (!Number.isInteger(index) ||\n index < 0 ||\n index >= countForPolicy(this.measure, policy))\n return undefined;\n let node = this.#root;\n let remaining = index;\n while (node !== null) {\n const left = countForPolicy(node.left?.measure ?? EMPTY_COUNTS, policy);\n const own = countForPolicy(node.entry.counts, policy);\n if (remaining < left)\n node = node.left;\n else if (remaining < left + own)\n return { entry: node.entry, offset: remaining - left };\n else {\n remaining -= left + own;\n node = node.right;\n }\n }\n return undefined;\n }\n measureBefore(groupId, policy) {\n const entry = this.#byId.get(groupId);\n if (entry === undefined)\n return undefined;\n let node = this.#root;\n let result = 0;\n while (node !== null) {\n const comparison = this.#compareEntries(entry, node.entry);\n if (comparison < 0)\n node = node.left;\n else {\n result += countForPolicy(node.left?.measure ?? EMPTY_COUNTS, policy);\n if (comparison === 0)\n return result;\n result += countForPolicy(node.entry.counts, policy);\n node = node.right;\n }\n }\n return undefined;\n }\n selectData(index, policy) {\n if (!Number.isInteger(index) ||\n index < 0 ||\n index >= dataCountForPolicy(this.measure, policy))\n return undefined;\n let node = this.#root;\n let remaining = index;\n while (node !== null) {\n const left = dataCountForPolicy(node.left?.measure ?? EMPTY_COUNTS, policy);\n const own = dataCountForPolicy(node.entry.counts, policy);\n if (remaining < left)\n node = node.left;\n else if (remaining < left + own)\n return { entry: node.entry, offset: remaining - left };\n else {\n remaining -= left + own;\n node = node.right;\n }\n }\n return undefined;\n }\n dataBefore(groupId, policy) {\n const entry = this.#byId.get(groupId);\n if (entry === undefined)\n return undefined;\n let node = this.#root;\n let result = 0;\n while (node !== null) {\n const comparison = this.#compareEntries(entry, node.entry);\n if (comparison < 0)\n node = node.left;\n else {\n result += dataCountForPolicy(node.left?.measure ?? EMPTY_COUNTS, policy);\n if (comparison === 0)\n return result;\n result += dataCountForPolicy(node.entry.counts, policy);\n node = node.right;\n }\n }\n return undefined;\n }\n visitRange(start, end, policy, visitor, diagnostics) {\n const size = countForPolicy(this.measure, policy);\n const from = Math.max(0, Math.min(size, start));\n const to = Math.max(0, Math.min(size, end));\n const walk = (node, offset) => {\n if (node === null || from >= to)\n return;\n const subtreeCount = countForPolicy(node.measure, policy);\n if (to <= offset || from >= offset + subtreeCount)\n return;\n diagnostics.measuredNodeVisits += 1;\n const leftCount = countForPolicy(node.left?.measure ?? EMPTY_COUNTS, policy);\n const ownStart = offset + leftCount;\n const ownCount = countForPolicy(node.entry.counts, policy);\n const ownEnd = ownStart + ownCount;\n if (from < ownStart)\n walk(node.left, offset);\n if (from < ownEnd && to > ownStart) {\n visitor(node.entry, Math.max(0, from - ownStart), Math.min(ownCount, to - ownStart));\n }\n if (to > ownEnd)\n walk(node.right, ownEnd);\n };\n walk(this.#root, 0);\n }\n}\nfunction instrumentMeasuredGroupTree(tree, instrumentation) {\n return tree instanceof PersistentMeasuredGroupTree\n ? tree.withInstrumentation(instrumentation)\n : tree;\n}\nfunction effectiveExpanded(node, policy) {\n if (node.override !== undefined)\n return node.override;\n if (policy.kind === \"expanded\")\n return true;\n if (policy.kind === \"collapsed\")\n return false;\n return node.depth <= policy.depth;\n}\nfunction createLeafTree(queryPlan) {\n return createOrderStatisticTree({\n getId: (entry) => entry.record.rowId,\n // Entries carry their resolved keys, so a comparison is property reads\n // only — no store gets on this slice-hot path (the measured grouped-gate\n // regression was per-comparison WeakMap resolution).\n compare: (left, right) => compareWithSortKeys(queryPlan, left.record, left.keys, right.record, right.keys),\n measure: {\n empty: 0,\n fromEntry: () => 1,\n combine: (left, right) => left + right,\n },\n });\n}\nfunction createChildTree(queryPlan, level, instrumentation) {\n return new PersistentMeasuredGroupTree(null, instrumentPersistentMap(createPersistentMap(), instrumentation), (left, right) => queryPlan.compareGroupKeys(level, left.path[level], right.path[level]), instrumentation);\n}\nfunction compareAggregateLeaves(queryPlan, left, right) {\n const leftDependency = left.dependency;\n const rightDependency = right.dependency;\n // The dependency carries the row's sort keys (resolved at evaluation), so\n // a comparison is property reads only — no store gets on this slice-hot\n // path (the measured grouped-gate regression was per-comparison WeakMap\n // resolution).\n return compareWithSortKeys(queryPlan, {\n rowId: left.id,\n row: left.row,\n sourceOrder: leftDependency.sourceOrder,\n }, leftDependency.sortKeys, {\n rowId: right.id,\n row: right.row,\n sourceOrder: rightDependency.sourceOrder,\n }, rightDependency.sortKeys);\n}\n/**\n * Kind-aware aggregate root construction (#500 cycle 2 decision A):\n * `sum`/`avg`/`count` get an O(1) scalar accumulator cell; `min`/`max` (no\n * inverse) and custom aggregators (fold order is observable — associativity\n * is the only validated law) keep the ordered tree.\n */\nfunction emptyAggregateRoot(queryPlan, leaf) {\n if (isScalarBuiltinAggregator(leaf.aggregate)) {\n return createScalarAggregateCell({\n columnId: leaf.columnId,\n aggregator: leaf.aggregate,\n });\n }\n const factory = createAggregateTree;\n return factory({\n columnId: leaf.columnId,\n aggregator: leaf.aggregate,\n compare: (left, right) => compareAggregateLeaves(queryPlan, left, right),\n });\n}\nfunction updateAggregateRoots(roots, queryPlan, record, operation, \n/**\n * The row's filter verdict, supplied by the caller. Filtered aggregation is\n * membership in the `filtered` tree — there is no per-leaf flag — so this is\n * the single bit that decides insert vs remove there.\n */\nfilterPasses, \n/** The model-lifetime population choice; true selects the all-row root. */\naggregateFilteredRows, modelOperation, instrumentation) {\n // C1 (#500 cycle 2): only the population `aggregateRecord` reads is built.\n // The other root was write-only — constructed on every insert, finalized\n // never. Membership in the post-filter population is `filterPasses`: on\n // insert the row's verdict under this index's plan, on remove the verdict\n // it was INSERTED under (see `mutatePath`), so the inverse unwinds exactly\n // what was accumulated.\n const member = aggregateFilteredRows || filterPasses;\n if (!member)\n return roots;\n const selected = new Map(aggregateFilteredRows ? roots.all : roots.filtered);\n for (const leaf of record.metadata\n .aggregateLeaves) {\n try {\n const root = instrumentAggregateTree(selected.get(leaf.columnId) ?? emptyAggregateRoot(queryPlan, leaf), instrumentation);\n selected.set(leaf.columnId, operation === \"insert\"\n ? root.insertOrReplace(leaf.allLeaf)\n : // The removal record carries the originally-inserted value on\n // `allLeaf` — the exact operand a scalar cell's inverse needs.\n root.remove(record.rowId, leaf.allLeaf));\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw new PretableRowModelError(\"aggregator-failed\", `The aggregate for column ${leaf.columnId} failed.`, {\n operation: modelOperation,\n rowId: record.rowId,\n columnId: leaf.columnId,\n cause,\n });\n }\n }\n return Object.freeze(aggregateFilteredRows\n ? { all: selected, filtered: EMPTY_AGGREGATE_ROOT_MAP }\n : { all: EMPTY_AGGREGATE_ROOT_MAP, filtered: selected });\n}\nconst EMPTY_AGGREGATE_ROOT_MAP = new Map();\nfunction structurallyEqual(left, right, seen = new WeakMap()) {\n if (Object.is(left, right))\n return true;\n if (left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\") {\n return false;\n }\n let rights = seen.get(left);\n if (rights?.has(right))\n return true;\n if (rights === undefined) {\n rights = new WeakSet();\n seen.set(left, rights);\n }\n rights.add(right);\n if (left instanceof Date || right instanceof Date) {\n return (left instanceof Date &&\n right instanceof Date &&\n Object.is(left.getTime(), right.getTime()));\n }\n if (Array.isArray(left) || Array.isArray(right)) {\n return (Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => structurallyEqual(value, right[index], seen)));\n }\n if (left instanceof Map || right instanceof Map) {\n if (!(left instanceof Map) || !(right instanceof Map))\n return false;\n if (left.size !== right.size)\n return false;\n const unmatched = Array.from(right.entries());\n return Array.from(left.entries()).every(([leftKey, leftValue]) => {\n const index = unmatched.findIndex(([rightKey, rightValue]) => structurallyEqual(leftKey, rightKey, seen) &&\n structurallyEqual(leftValue, rightValue, seen));\n if (index < 0)\n return false;\n unmatched.splice(index, 1);\n return true;\n });\n }\n if (left instanceof Set || right instanceof Set) {\n if (!(left instanceof Set) || !(right instanceof Set))\n return false;\n if (left.size !== right.size)\n return false;\n const unmatched = Array.from(right.values());\n return Array.from(left.values()).every((leftValue) => {\n const index = unmatched.findIndex((rightValue) => structurallyEqual(leftValue, rightValue, seen));\n if (index < 0)\n return false;\n unmatched.splice(index, 1);\n return true;\n });\n }\n if (Object.getPrototypeOf(left) !== Object.getPrototypeOf(right) ||\n (Object.getPrototypeOf(left) !== Object.prototype &&\n Object.getPrototypeOf(left) !== null)) {\n return false;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n return (leftKeys.length === rightKeys.length &&\n leftKeys.every((key) => Object.hasOwn(right, key) &&\n structurallyEqual(Reflect.get(left, key), Reflect.get(right, key), seen)));\n}\nclass GroupAggregatorError extends PretableRowModelError {\n name = \"GroupAggregatorError\";\n groupId;\n groupValues;\n constructor(operation, rowId, columnId, groupId, groupValues, cause) {\n super(\"aggregator-failed\", `Finalizing the aggregate for column ${columnId} failed in group ${groupId}.`, { operation, rowId, columnId, cause });\n this.groupId = groupId;\n this.groupValues = Object.freeze([...groupValues]);\n }\n}\nfunction aggregateRecord(roots, allPopulation, previous, operation, rowId, groupId, groupValues) {\n const selected = allPopulation ? roots.all : roots.filtered;\n const values = {};\n let same = previous !== undefined;\n for (const [columnId, tree] of selected) {\n let finalized;\n try {\n finalized = tree.finalize();\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw new GroupAggregatorError(operation, rowId, columnId, groupId, groupValues, cause);\n }\n const value = structurallyEqual(previous?.[columnId], finalized)\n ? previous?.[columnId]\n : finalized;\n values[columnId] = value;\n if (!Object.is(previous?.[columnId], value))\n same = false;\n }\n if (previous !== undefined && Object.keys(previous).length !== selected.size)\n same = false;\n return same ? previous : Object.freeze(values);\n}\nfunction makePublicGroup(source, expanded, previous) {\n if (previous !== undefined &&\n previous.expanded === expanded &&\n previous.childCount === source.childCount &&\n previous.aggregates === source.aggregates &&\n Object.is(previous.value, source.value))\n return previous;\n return Object.freeze({ ...source, expanded });\n}\nfunction finishNode(node, context, triggerRowId) {\n const previous = context.reusable.get(node.groupId);\n if (previous !== undefined && context.instrumentation !== undefined)\n context.instrumentation.work.groupNodesCopied += 1;\n const aggregates = aggregateRecord(node.aggregateRoots, context.aggregateFilteredRows, previous?.aggregates, context.operation, triggerRowId, node.groupId, node.path.map((entry) => entry.value));\n const descendants = node.depth === context.levelCount - 1\n ? Object.freeze({\n collapsed: node.leaves.size,\n expanded: node.leaves.size,\n throughDepth: Object.freeze(Array(context.levelCount).fill(node.leaves.size)),\n data: node.leaves.size,\n dataCollapsed: node.leaves.size,\n dataExpanded: node.leaves.size,\n dataThroughDepth: Object.freeze(Array(context.levelCount).fill(node.leaves.size)),\n })\n : node.children.measure;\n const counts = groupCounts(node.depth, context.levelCount, node.override, descendants);\n const source = {\n kind: \"group\",\n groupId: node.groupId,\n depth: node.depth,\n columnId: node.columnId,\n value: node.value,\n childCount: node.filteredCount,\n aggregates,\n };\n const publicCollapsed = makePublicGroup(source, false, previous?.publicCollapsed);\n const publicExpanded = makePublicGroup(source, true, previous?.publicExpanded);\n return Object.freeze({\n ...node,\n aggregates,\n publicCollapsed,\n publicExpanded,\n counts,\n });\n}\nconst EMPTY_AGGREGATE_ROOTS = Object.freeze({\n all: EMPTY_AGGREGATE_ROOT_MAP,\n filtered: EMPTY_AGGREGATE_ROOT_MAP,\n});\nfunction mutatePath(state, record, operation, context, \n/**\n * On `\"insert\"` the row's verdict under the index's plan; on `\"remove\"` the\n * verdict the row was INSERTED under (its membership in the previous\n * index), so `filteredCount` unwinds exactly what it counted.\n */\nfilterPasses) {\n const metadata = record.metadata;\n const path = metadata.groupPath;\n if (path.length === 0)\n return;\n const pathKeys = path.map((entry) => encodeGroupValue(entry.value, {\n operation: context.operation,\n rowId: record.rowId,\n columnId: entry.columnId,\n }));\n const visit = (depth, parentGroupId, previous) => {\n const entry = path[depth];\n const groupPath = Object.freeze(path.slice(0, depth + 1));\n const groupId = makeGroupId(groupPath);\n const leafLevel = depth === path.length - 1;\n let childrenByKey = instrumentPersistentMap(previous?.childrenByKey ??\n createPersistentMap(), context.instrumentation);\n let children = instrumentMeasuredGroupTree(previous?.children ??\n createChildTree(context.queryPlan, depth + 1, context.instrumentation), context.instrumentation);\n let leaves = instrumentOrderStatisticTree(previous?.leaves ??\n createLeafTree(context.queryPlan), context.instrumentation);\n if (leafLevel) {\n leaves =\n operation === \"insert\" && filterPasses\n ? leaves.insertOrReplace(orderedRowEntry(context.queryPlan, record))\n : leaves.remove(record.rowId);\n }\n else {\n const childKey = pathKeys[depth + 1];\n const oldChild = childrenByKey.get(childKey);\n const nextChild = visit(depth + 1, groupId, oldChild);\n childrenByKey =\n nextChild === undefined\n ? childrenByKey.delete(childKey)\n : childrenByKey.set(childKey, nextChild);\n children = oldChild?.filteredCount\n ? children.remove(oldChild.groupId)\n : children;\n if (nextChild?.filteredCount)\n children = children.insertOrReplace(nextChild);\n }\n const filteredCount = (previous?.filteredCount ?? 0) +\n (filterPasses ? (operation === \"insert\" ? 1 : -1) : 0);\n const allCount = (previous?.allCount ?? 0) + (operation === \"insert\" ? 1 : -1);\n if (allCount === 0) {\n state.groups = state.groups.delete(groupId);\n return undefined;\n }\n const aggregateRoots = updateAggregateRoots(previous?.aggregateRoots ?? EMPTY_AGGREGATE_ROOTS, context.queryPlan, record, operation, filterPasses, context.aggregateFilteredRows, context.operation, context.instrumentation);\n const override = previous?.override;\n const next = finishNode({\n groupId,\n path: groupPath,\n pathKeys: Object.freeze(pathKeys.slice(0, depth + 1)),\n depth,\n columnId: entry.columnId,\n value: previous === undefined ? entry.value : previous.value,\n key: pathKeys[depth],\n parentGroupId,\n override,\n childrenByKey,\n children,\n leaves,\n filteredCount,\n allCount,\n aggregateRoots,\n }, context, record.rowId);\n state.groups = state.groups.set(groupId, next);\n return next;\n };\n const rootKey = pathKeys[0];\n const oldRoot = state.rootsByKey.get(rootKey);\n const nextRoot = visit(0, undefined, oldRoot);\n state.rootsByKey =\n nextRoot === undefined\n ? state.rootsByKey.delete(rootKey)\n : state.rootsByKey.set(rootKey, nextRoot);\n if (oldRoot?.filteredCount)\n state.roots = state.roots.remove(oldRoot.groupId);\n if (nextRoot?.filteredCount)\n state.roots = state.roots.insertOrReplace(nextRoot);\n state.rowParents =\n operation === \"insert\"\n ? state.rowParents.set(record.rowId, makeGroupId(path))\n : state.rowParents.delete(record.rowId);\n}\nfunction rootFromState(state, context) {\n const root = Object.freeze({\n levelCount: context.levelCount,\n queryPlan: context.queryPlan,\n aggregateFilteredRows: context.aggregateFilteredRows,\n ...state,\n counts: state.roots.measure,\n });\n if (context.instrumentation !== undefined)\n groupIndexInstrumentation.set(root, context.instrumentation);\n return root;\n}\n/**\n * Candidate-only grouped index builder. It owns transient leaves, aggregate\n * trees, and membership maps for the unpublished initial rebuild, then seals\n * group nodes bottom-up one cooperative unit at a time. Published revisions\n * continue to use the persistent changed-path updater below.\n */\nexport function createGroupIndexBuildDraft(options) {\n const { queryPlan, aggregateFilteredRows, operation, instrumentation } = options;\n const levelCount = queryPlan.query.rowGroups.length;\n const rootsByKey = new Map();\n const nodes = [];\n const rowParents = instrumentPersistentMap(createPersistentMap(), instrumentation).asTransient();\n const groups = instrumentPersistentMap(createPersistentMap(), instrumentation).asTransient();\n const context = {\n queryPlan,\n levelCount,\n aggregateFilteredRows,\n reusable: options.reusable?.groups ?? createPersistentMap(),\n operation,\n instrumentation,\n };\n let root;\n let released = false;\n let sealingStarted = false;\n let pendingUnits = 0;\n let activeNode;\n let activeChildIterator;\n let activeChildrenByKey;\n let activeMeasuredChildren;\n let rootIterator;\n let persistentRootsByKey;\n let measuredRoots;\n const assertActive = () => {\n if (released)\n throw new Error(\"Released grouped index build draft.\");\n };\n const createMutableNode = (path, pathKeys, parentGroupId) => {\n const entry = path[path.length - 1];\n const node = {\n groupId: makeGroupId(path),\n path,\n pathKeys,\n depth: path.length - 1,\n columnId: entry.columnId,\n value: entry.value,\n key: pathKeys[pathKeys.length - 1],\n parentGroupId,\n override: options.overrides.get(makeGroupId(path)),\n childrenByKey: new Map(),\n leaves: instrumentOrderStatisticTree(createLeafTree(queryPlan), instrumentation).asTransient(),\n aggregateRoots: { all: new Map(), filtered: new Map() },\n filteredCount: 0,\n allCount: 0,\n triggerRowId: undefined,\n finished: undefined,\n };\n nodes.push(node);\n // One unit seals this node and one installs its parent/root edge.\n pendingUnits += 2;\n return node;\n };\n const createRootDraft = (leaf) => {\n const root = emptyAggregateRoot(queryPlan, leaf);\n // Scalar cells never defer measures, so they skip the deferred-measure\n // draft machinery entirely (their transient satisfies its surface with a\n // permanently-empty queue).\n return isScalarBuiltinAggregator(leaf.aggregate)\n ? root.asTransient()\n : createDeferredMeasureTransientAggregateTree(instrumentAggregateTree(root, instrumentation));\n };\n const updateMutableAggregates = (node, record, filterPasses) => {\n // C1 (#500 cycle 2): only the SELECTED population root is built — the\n // other was write-only. A row outside the selected population\n // contributes nothing at all.\n if (!aggregateFilteredRows && !filterPasses)\n return;\n const selected = aggregateFilteredRows\n ? node.aggregateRoots.all\n : node.aggregateRoots.filtered;\n let grewAnyTree = false;\n for (const leaf of record.metadata\n .aggregateLeaves) {\n try {\n let root = selected.get(leaf.columnId);\n if (root === undefined) {\n root = createRootDraft(leaf);\n selected.set(leaf.columnId, root);\n }\n const sizeBefore = root.size;\n root.insertOrReplace(leaf.allLeaf);\n // A scalar cell accumulates inline and holds NO deferred measures\n // (pendingMeasureCount stays 0), so it must charge no seal units —\n // only a grown ordered tree leaves work for the seal phase.\n if (root.size > sizeBefore && root.pendingMeasureCount > 0) {\n grewAnyTree = true;\n }\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw new PretableRowModelError(\"aggregator-failed\", `The aggregate for column ${leaf.columnId} failed.`, {\n operation,\n rowId: record.rowId,\n columnId: leaf.columnId,\n cause,\n });\n }\n }\n // One seal unit per (row, node), NOT per (row × column): sealing\n // advances every still-pending tree of the node by one measure, so a\n // row's deferred measures across ALL its tree-backed aggregated columns\n // drain together under a single charged unit (#500). Scalar-only rows\n // charge nothing (#500 cycle 2).\n if (grewAnyTree)\n pendingUnits += 1;\n };\n const finishRoot = () => rootFromState({\n rootsByKey: persistentRootsByKey.freeze(),\n roots: measuredRoots,\n groups: groups.freeze(),\n rowParents: rowParents.freeze(),\n }, context);\n const finalizeActiveNode = () => {\n const mutable = activeNode;\n const aggregateRoots = Object.freeze({\n all: new Map([...mutable.aggregateRoots.all].map(([columnId, tree]) => [\n columnId,\n tree.freeze(),\n ])),\n filtered: new Map([...mutable.aggregateRoots.filtered].map(([columnId, tree]) => [\n columnId,\n tree.freeze(),\n ])),\n });\n const finished = finishNode({\n groupId: mutable.groupId,\n path: mutable.path,\n pathKeys: mutable.pathKeys,\n depth: mutable.depth,\n columnId: mutable.columnId,\n value: mutable.value,\n key: mutable.key,\n parentGroupId: mutable.parentGroupId,\n override: mutable.override,\n childrenByKey: activeChildrenByKey.freeze(),\n children: activeMeasuredChildren,\n leaves: mutable.leaves.freeze(),\n filteredCount: mutable.filteredCount,\n allCount: mutable.allCount,\n aggregateRoots,\n }, context, mutable.triggerRowId);\n mutable.finished = finished;\n groups.set(finished.groupId, finished);\n activeNode = undefined;\n activeChildIterator = undefined;\n activeChildrenByKey = undefined;\n activeMeasuredChildren = undefined;\n };\n /**\n * One seal unit = one ROW of deferred measures: every still-pending\n * aggregate tree of the active node — all tree-backed aggregated columns\n * of the selected population root — advances by exactly one measure per\n * call. The trees drain in lockstep, so a node consumes max(tree size)\n * units, which is the one-unit-per-(row, node) charge\n * `updateMutableAggregates` recorded. Scalar cells report zero pending\n * measures and are skipped (#500 cycle 2).\n * Resumability is preserved at row granularity: each call is one atomic\n * unit and the pending counts on the trees are the resume cursor (#500).\n */\n const sealActiveAggregate = () => {\n const mutable = activeNode;\n let sealedAnyMeasure = false;\n for (const roots of [\n mutable.aggregateRoots.all,\n mutable.aggregateRoots.filtered,\n ]) {\n for (const [columnId, tree] of roots) {\n if (tree.pendingMeasureCount === 0)\n continue;\n try {\n tree.sealMeasureStep();\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw new GroupAggregatorError(operation, mutable.triggerRowId, columnId, mutable.groupId, mutable.path.map((entry) => entry.value), cause);\n }\n sealedAnyMeasure = true;\n }\n }\n if (!sealedAnyMeasure)\n return false;\n pendingUnits -= 1;\n return true;\n };\n const draft = {\n get pendingFinalizationCount() {\n return pendingUnits;\n },\n insert(record) {\n assertActive();\n if (sealingStarted)\n throw new Error(\"Cannot insert after grouped index sealing started.\");\n const path = record.metadata.groupPath;\n if (path.length === 0)\n return;\n // Computed once per record and spent locally on the three membership\n // decisions below (filteredCount, the filtered aggregate tree, and the\n // leaf tree) — which together ARE this index's record of the verdict.\n const filterPasses = filterVerdict(queryPlan, record);\n const pathKeys = path.map((entry) => encodeGroupValue(entry.value, {\n operation,\n rowId: record.rowId,\n columnId: entry.columnId,\n }));\n let children = rootsByKey;\n let parentGroupId;\n let current;\n for (let depth = 0; depth < path.length; depth += 1) {\n const key = pathKeys[depth];\n current = children.get(key);\n if (current === undefined) {\n current = createMutableNode(Object.freeze(path.slice(0, depth + 1)), Object.freeze(pathKeys.slice(0, depth + 1)), parentGroupId);\n children.set(key, current);\n }\n current.allCount += 1;\n if (filterPasses)\n current.filteredCount += 1;\n updateMutableAggregates(current, record, filterPasses);\n current.triggerRowId = record.rowId;\n parentGroupId = current.groupId;\n children = current.childrenByKey;\n }\n if (filterPasses) {\n current.leaves.insertOrReplace(orderedRowEntry(queryPlan, record));\n }\n rowParents.set(record.rowId, current.groupId);\n },\n sealStep() {\n assertActive();\n sealingStarted = true;\n if (root !== undefined)\n return true;\n if (activeNode !== undefined) {\n if (sealActiveAggregate())\n return false;\n const next = activeChildIterator.next();\n if (!next.done) {\n const [key, child] = next.value;\n const finished = child.finished;\n if (finished === undefined)\n throw new Error(\"Grouped index children must seal before parents.\");\n activeChildrenByKey.set(key, finished);\n if (finished.filteredCount > 0) {\n activeMeasuredChildren =\n activeMeasuredChildren.insertOrReplace(finished);\n }\n pendingUnits -= 1;\n return false;\n }\n finalizeActiveNode();\n pendingUnits -= 1;\n return false;\n }\n const mutable = nodes.pop();\n if (mutable !== undefined) {\n activeNode = mutable;\n activeChildIterator = mutable.childrenByKey.entries();\n activeMeasuredChildren = createChildTree(queryPlan, mutable.depth + 1, instrumentation);\n activeChildrenByKey = instrumentPersistentMap(createPersistentMap(), instrumentation).asTransient();\n return draft.sealStep();\n }\n if (rootIterator === undefined) {\n rootIterator = rootsByKey.entries();\n measuredRoots = createChildTree(queryPlan, 0, instrumentation);\n persistentRootsByKey = instrumentPersistentMap(createPersistentMap(), instrumentation).asTransient();\n }\n const next = rootIterator.next();\n if (!next.done) {\n const [key, mutableRoot] = next.value;\n const finished = mutableRoot.finished;\n persistentRootsByKey.set(key, finished);\n if (finished.filteredCount > 0)\n measuredRoots = measuredRoots.insertOrReplace(finished);\n pendingUnits -= 1;\n return false;\n }\n root = finishRoot();\n return true;\n },\n finish() {\n assertActive();\n if (root === undefined)\n throw new Error(\"Grouped index build draft is not sealed.\");\n return root;\n },\n release() {\n released = true;\n rootsByKey.clear();\n nodes.length = 0;\n activeNode = undefined;\n activeChildIterator = undefined;\n activeChildrenByKey = undefined;\n activeMeasuredChildren = undefined;\n rootIterator = undefined;\n persistentRootsByKey = undefined;\n measuredRoots = undefined;\n root = undefined;\n },\n };\n return draft;\n}\nexport function createGroupIndex(records, queryPlan, aggregateFilteredRows, overrides, operation = \"set-rows\", reusable, instrumentation) {\n const levelCount = queryPlan.query.rowGroups.length;\n const rootsByKey = createPersistentMap();\n const state = {\n rootsByKey,\n roots: createChildTree(queryPlan, 0, instrumentation),\n groups: createPersistentMap(),\n rowParents: createPersistentMap(),\n };\n const context = {\n queryPlan,\n levelCount,\n aggregateFilteredRows,\n reusable: reusable?.groups ?? state.groups,\n operation,\n instrumentation,\n };\n for (const record of records) {\n mutatePath(state, record, \"insert\", context, filterVerdict(queryPlan, record));\n }\n // Apply retained overrides after all future/current groups have been materialized.\n let root = rootFromState(state, context);\n for (const [groupId, expanded] of overrides.entries()) {\n if (root.groups.has(groupId))\n root = setGroupOverride(root, groupId, expanded, operation);\n }\n return root;\n}\nexport function updateGroupIndex(previous, removals, insertions, overrides, operation = \"apply-transaction\", instrumentation = groupIndexInstrumentation.get(previous)) {\n const state = {\n rootsByKey: instrumentPersistentMap(previous.rootsByKey, instrumentation),\n roots: instrumentMeasuredGroupTree(previous.roots, instrumentation),\n groups: instrumentPersistentMap(previous.groups, instrumentation),\n rowParents: instrumentPersistentMap(previous.rowParents, instrumentation),\n };\n const context = {\n queryPlan: previous.queryPlan,\n levelCount: previous.levelCount,\n aggregateFilteredRows: previous.aggregateFilteredRows,\n reusable: previous.groups,\n operation,\n instrumentation,\n };\n // A removal must unwind the verdict the row was counted under, which is\n // exactly its membership in the PREVIOUS index — read before any mutation\n // touches `state`.\n //\n // An insertion's verdict comes from the index's OWN plan, the same authority\n // this function already trusts for leaf order (`orderedRowEntry` resolves\n // keys from that plan's store) and for its comparators. That binds the\n // verdict to the same standing precondition as the rest: records handed to\n // an existing index must be coherent with the plan the index was built\n // under. A same-reference mutation breaks that precondition for every\n // derived value, not just this one, and its caller answers by rebuilding\n // the index outright under the fresh plan.\n for (const record of removals) {\n mutatePath(state, record, \"remove\", context, rowPassesFilterInGroupIndex(previous, record.rowId));\n }\n for (const record of insertions) {\n mutatePath(state, record, \"insert\", context, filterVerdict(previous.queryPlan, record));\n }\n let root = rootFromState(state, context);\n if (overrides !== undefined) {\n for (const [groupId, expanded] of overrides.entries()) {\n const group = root.groups.get(groupId);\n if (group !== undefined && group.override !== expanded) {\n root = setGroupOverride(root, groupId, expanded, operation);\n }\n }\n }\n return root;\n}\nexport function setGroupOverride(root, groupId, override, operation = \"set-group-expanded\") {\n const target = root.groups.get(groupId);\n if (target === undefined || target.override === override)\n return root;\n const context = {\n queryPlan: root.queryPlan,\n levelCount: root.levelCount,\n aggregateFilteredRows: root.aggregateFilteredRows,\n reusable: root.groups,\n operation,\n instrumentation: groupIndexInstrumentation.get(root),\n };\n let groups = instrumentPersistentMap(root.groups, context.instrumentation);\n const representativeRowId = (node) => {\n const child = node.childrenByKey.entries().next().value?.[1];\n if (child !== undefined)\n return representativeRowId(child);\n // C1 (#500 cycle 2): only the selected population root exists, so read\n // whichever one holds trees. Builtin-scalar-only groups yield undefined\n // — the sole consumer is custom-finalizer error context, and customs\n // always ride a tree with a firstId.\n for (const roots of [\n node.aggregateRoots.all,\n node.aggregateRoots.filtered,\n ]) {\n for (const tree of roots.values()) {\n const rowId = tree.firstId();\n if (rowId !== undefined)\n return rowId;\n }\n }\n return undefined;\n };\n const replace = (depth, node) => {\n let childrenByKey = instrumentPersistentMap(node.childrenByKey, context.instrumentation);\n let children = instrumentMeasuredGroupTree(node.children, context.instrumentation);\n if (depth < target.depth) {\n const key = target.pathKeys[depth + 1];\n const oldChild = childrenByKey.get(key);\n const nextChild = replace(depth + 1, oldChild);\n childrenByKey = childrenByKey.set(key, nextChild);\n if (oldChild.filteredCount)\n children = children.remove(oldChild.groupId).insertOrReplace(nextChild);\n }\n const next = finishNode({\n ...node,\n override: depth === target.depth ? override : node.override,\n childrenByKey,\n children,\n }, context, \n // Expansion does not change aggregate roots. If a custom lazy finalizer\n // is nevertheless invoked, use the first ordered descendant as the\n // deterministic representative for complete error context.\n representativeRowId(node));\n groups = groups.set(next.groupId, next);\n return next;\n };\n const rootKey = target.pathKeys[0];\n const oldTop = root.rootsByKey.get(rootKey);\n const nextTop = replace(0, oldTop);\n let roots = instrumentMeasuredGroupTree(root.roots, context.instrumentation);\n if (oldTop.filteredCount)\n roots = roots.remove(oldTop.groupId);\n if (nextTop.filteredCount)\n roots = roots.insertOrReplace(nextTop);\n const nextRoot = Object.freeze({\n ...root,\n rootsByKey: instrumentPersistentMap(root.rootsByKey, context.instrumentation).set(rootKey, nextTop),\n roots,\n groups,\n counts: roots.measure,\n });\n if (context.instrumentation !== undefined)\n groupIndexInstrumentation.set(nextRoot, context.instrumentation);\n return nextRoot;\n}\nfunction publicGroup(node, policy) {\n return effectiveExpanded(node, policy)\n ? node.publicExpanded\n : node.publicCollapsed;\n}\nfunction publicData(record, depth) {\n if (record.publicRow.depth === depth)\n return record.publicRow;\n let byDepth = groupedPublicData.get(record);\n const cached = byDepth?.get(depth);\n if (cached !== undefined)\n return cached;\n const created = Object.freeze({ ...record.publicRow, depth });\n if (byDepth === undefined) {\n byDepth = new Map();\n groupedPublicData.set(record, byDepth);\n }\n byDepth.set(depth, created);\n return created;\n}\nconst groupedPublicData = new WeakMap();\nexport function visibleCount(root, policy) {\n return countForPolicy(root.counts, policy);\n}\nfunction visibleAtNode(node, policy, offset) {\n if (offset === 0)\n return publicGroup(node, policy);\n if (!effectiveExpanded(node, policy))\n return undefined;\n const descendantOffset = offset - 1;\n if (node.children.size > 0) {\n const selected = node.children.select(descendantOffset, policy);\n return selected === undefined\n ? undefined\n : visibleAtNode(selected.entry, policy, selected.offset);\n }\n const entry = node.leaves.entryAt(descendantOffset);\n return entry === undefined\n ? undefined\n : publicData(entry.record, node.depth + 1);\n}\nexport function visibleAt(root, policy, index) {\n const selected = root.roots.select(index, policy);\n return selected === undefined\n ? undefined\n : visibleAtNode(selected.entry, policy, selected.offset);\n}\nexport function visibleRange(root, policy, start, end, resolveRecord = (record) => record) {\n const size = visibleCount(root, policy);\n const from = Math.max(0, Math.min(size, Math.trunc(Number.isNaN(start) ? 0 : start)));\n const to = Math.max(0, Math.min(size, Math.trunc(Number.isNaN(end) ? 0 : end)));\n const diagnostics = {\n measuredNodeVisits: 0,\n };\n const result = [];\n const appendNodeRange = (node, nodeStart, nodeEnd) => {\n if (nodeStart >= nodeEnd)\n return;\n if (nodeStart === 0)\n result.push(publicGroup(node, policy));\n if (!effectiveExpanded(node, policy) || nodeEnd <= 1)\n return;\n const descendantsStart = Math.max(0, nodeStart - 1);\n const descendantsEnd = nodeEnd - 1;\n if (node.children.size > 0) {\n node.children.visitRange(descendantsStart, descendantsEnd, policy, appendNodeRange, diagnostics);\n return;\n }\n for (const entry of node.leaves.range(descendantsStart, descendantsEnd)) {\n result.push(publicData(resolveRecord(entry.record), node.depth + 1));\n }\n };\n if (from < to) {\n root.roots.visitRange(from, to, policy, appendNodeRange, diagnostics);\n }\n const frozen = Object.freeze(result);\n visibleRangeDiagnostics.set(frozen, Object.freeze({ measuredNodeVisits: diagnostics.measuredNodeVisits }));\n return frozen;\n}\nexport function isExpanded(root, groupId, policy) {\n const node = root.groups.get(groupId);\n return node === undefined ? false : effectiveExpanded(node, policy);\n}\nexport function visibleIndexOf(root, policy, ref) {\n const targetId = ref.kind === \"data\" ? root.rowParents.get(ref.rowId) : ref.groupId;\n if (targetId === undefined)\n return -1;\n const target = root.groups.get(targetId);\n if (target === undefined || target.filteredCount === 0)\n return -1;\n const chain = [];\n let cursor = target;\n while (cursor !== undefined) {\n chain.push(cursor);\n cursor =\n cursor.parentGroupId === undefined\n ? undefined\n : root.groups.get(cursor.parentGroupId);\n }\n chain.reverse();\n let index = root.roots.measureBefore(chain[0].groupId, policy);\n if (index === undefined)\n return -1;\n for (let depth = 1; depth < chain.length; depth += 1) {\n const parent = chain[depth - 1];\n if (!effectiveExpanded(parent, policy))\n return -1;\n const before = parent.children.measureBefore(chain[depth].groupId, policy);\n if (before === undefined)\n return -1;\n index += 1 + before;\n }\n if (ref.kind === \"group\")\n return index;\n if (!effectiveExpanded(target, policy))\n return -1;\n const rank = target.leaves.rankOf(ref.rowId);\n return rank === undefined ? -1 : index + 1 + rank;\n}\nfunction dataAtNode(node, policy, index, resolveRecord) {\n if (!effectiveExpanded(node, policy))\n return undefined;\n if (node.children.size > 0) {\n const selected = node.children.selectData(index, policy);\n return selected === undefined\n ? undefined\n : dataAtNode(selected.entry, policy, selected.offset, resolveRecord);\n }\n const entry = node.leaves.entryAt(index);\n return entry === undefined\n ? undefined\n : publicData(resolveRecord(entry.record), node.depth + 1);\n}\nexport function visibleDataCount(root, policy) {\n return dataCountForPolicy(root.counts, policy);\n}\nexport function dataAt(root, policy, index, resolveRecord = (record) => record) {\n const selected = root.roots.selectData(index, policy);\n return selected === undefined\n ? undefined\n : dataAtNode(selected.entry, policy, selected.offset, resolveRecord);\n}\n/** Returns the visible data rank of a data ref, or the count before a group ref. */\nexport function dataRankAtRef(root, policy, ref) {\n const targetId = ref.kind === \"data\" ? root.rowParents.get(ref.rowId) : ref.groupId;\n if (targetId === undefined)\n return undefined;\n const target = root.groups.get(targetId);\n if (target === undefined || target.filteredCount === 0)\n return undefined;\n const chain = [];\n let cursor = target;\n while (cursor !== undefined) {\n chain.push(cursor);\n cursor =\n cursor.parentGroupId === undefined\n ? undefined\n : root.groups.get(cursor.parentGroupId);\n }\n chain.reverse();\n let rank = root.roots.dataBefore(chain[0].groupId, policy);\n if (rank === undefined)\n return undefined;\n for (let depth = 1; depth < chain.length; depth += 1) {\n const parent = chain[depth - 1];\n if (!effectiveExpanded(parent, policy))\n return undefined;\n const before = parent.children.dataBefore(chain[depth].groupId, policy);\n if (before === undefined)\n return undefined;\n rank += before;\n }\n if (ref.kind === \"group\")\n return rank;\n if (!effectiveExpanded(target, policy))\n return undefined;\n const leafRank = target.leaves.rankOf(ref.rowId);\n return leafRank === undefined ? undefined : rank + leafRank;\n}\nexport function parentGroup(root, ref, policy) {\n const parentId = ref.kind === \"data\"\n ? root.rowParents.get(ref.rowId)\n : root.groups.get(ref.groupId)?.parentGroupId;\n const node = parentId === undefined ? undefined : root.groups.get(parentId);\n return node === undefined ? undefined : publicGroup(node, policy);\n}\nexport function nearestVisible(root, ref, policy) {\n if (visibleIndexOf(root, policy, ref) >= 0)\n return Object.freeze({ ...ref });\n let groupId = ref.kind === \"data\" ? root.rowParents.get(ref.rowId) : ref.groupId;\n while (groupId !== undefined) {\n const groupRef = Object.freeze({ kind: \"group\", groupId });\n if (visibleIndexOf(root, policy, groupRef) >= 0)\n return groupRef;\n groupId = root.groups.get(groupId)?.parentGroupId;\n }\n return undefined;\n}\n","import { compareWithSortKeys, filterVerdict, } from \"./compiled-query\";\nimport { orderedRowEntry } from \"./ordered-row-entry\";\nimport { attachGroupIndex, createGroupIndex, dataAt, dataRankAtRef, getGroupIndex, isExpanded, nearestVisible, parentGroup, visibleCount, visibleDataCount, visibleIndexOf, visibleRange, } from \"./group-index\";\nimport { createMembership, setMembershipBit, } from \"./membership-bitset\";\nimport { createOrderStatisticTree } from \"./persistent/order-statistic-tree\";\nexport function createFlatVisibleIndex(records, queryPlan) {\n const draft = createFlatVisibleTree(queryPlan).asTransient();\n for (const record of records) {\n // The verdict is COMPUTED here and stays local: the tree this loop fills\n // IS where the answer is recorded, so storing it on the record would only\n // duplicate what membership already says.\n if (filterVerdict(queryPlan, record)) {\n draft.insertOrReplace(orderedRowEntry(queryPlan, record));\n }\n }\n return Object.freeze({ rows: draft.freeze() });\n}\nexport function createVisibleIndex(records, queryPlan, aggregateFilteredRows, overrides, operation = \"set-rows\", reusable) {\n if (queryPlan.query.rowGroups.length === 0) {\n return createFlatVisibleIndex(records, queryPlan);\n }\n return attachGroupIndex(createFlatVisibleTree(queryPlan), createGroupIndex(records, queryPlan, aggregateFilteredRows, overrides, operation, reusable));\n}\n/**\n * Membership bitset of a FLAT visible tree: one pass, `entry.record.slot`.\n * `capacity` must be the owning root's self-described `slotCapacity` (or the\n * value that will become it), never the live allocator's.\n */\nexport function membershipFromFlatTree(rows, capacity) {\n const bits = createMembership(capacity);\n // `range(0, size)` rather than `entries()`: a full walk, and the tree's\n // materialized non-generator walk is the cheaper way to make one — ~1ms\n // against ~30ms at 50,000 rows (see `iterateEntries`).\n for (const entry of rows.range(0, rows.size)) {\n setMembershipBit(bits, entry.record.slot);\n }\n return bits;\n}\nexport function createFlatVisibleTree(queryPlan) {\n return createOrderStatisticTree({\n getId: (entry) => entry.record.rowId,\n // Entries carry their resolved keys, so a comparison is property reads\n // only — no store gets on this slice-hot path (the measured grouped-gate\n // regression was per-comparison WeakMap resolution).\n compare: (left, right) => compareWithSortKeys(queryPlan, left.record, left.keys, right.record, right.keys),\n measure: {\n empty: 0,\n fromEntry: () => 1,\n combine: (left, right) => left + right,\n },\n });\n}\nfunction dataRef(rowId) {\n return Object.freeze({ kind: \"data\", rowId });\n}\n/** Creates an immutable indexed facade that closes over exactly one root. */\nexport function createFlatSnapshot(root) {\n const grouped = getGroupIndex(root.visible);\n if (grouped !== undefined) {\n const policy = root.expansion.default;\n const resolveCurrentRecord = (record) => root.rows.get(record.rowId) ?? record;\n const publicRowAt = (index) => visibleRange(grouped, policy, index, index + 1, resolveCurrentRecord)[0];\n const refAtDataRank = (index) => dataAt(grouped, policy, index, resolveCurrentRecord);\n const neighbor = (ref, delta) => {\n const rank = dataRankAtRef(grouped, policy, ref);\n if (rank === undefined)\n return undefined;\n return dataAt(grouped, policy, ref.kind === \"data\" ? rank + delta : rank + (delta < 0 ? -1 : 0), resolveCurrentRecord);\n };\n const count = visibleCount(grouped, policy);\n const dataCount = visibleDataCount(grouped, policy);\n return Object.freeze({\n revision: root.revision,\n sourceRowCount: root.rows.size,\n visibleRowCount: count,\n visibleDataRowCount: dataCount,\n rowAt: publicRowAt,\n range: (start, end) => visibleRange(grouped, policy, start, end, resolveCurrentRecord),\n indexOf: (ref) => visibleIndexOf(grouped, policy, ref),\n dataIndexOf: (ref) => dataRankAtRef(grouped, policy, ref) ?? -1,\n dataRowAt: refAtDataRank,\n firstDataRow: () => refAtDataRank(0),\n lastDataRow: () => refAtDataRank(dataCount - 1),\n nextDataRow: (ref) => neighbor(ref, 1),\n previousDataRow: (ref) => neighbor(ref, -1),\n parentGroupOf: (ref) => parentGroup(grouped, ref, policy),\n nearestVisibleRef: (ref) => nearestVisible(grouped, ref, policy),\n isGroupExpanded: (groupId) => isExpanded(grouped, groupId, policy),\n // Dense reads answer `undefined` wholesale on grouped roots: group rows\n // carry no slot, and the seam's contract is all-or-nothing — the caller\n // falls back to string identities.\n ɵvisibleSlotRange: () => undefined,\n ɵslotOfRowId: () => undefined,\n ɵslotCapacity: () => undefined,\n query: root.queryPlan.query,\n expansion: root.expansion.state,\n });\n }\n const visible = root.visible.rows;\n const publicRowAt = (index) => {\n const ordered = visible.entryAt(index);\n return ordered === undefined\n ? undefined\n : root.rows.get(ordered.record.rowId)?.publicRow;\n };\n const lookupRank = (ref) => ref.kind === \"data\" ? visible.rankOf(ref.rowId) : undefined;\n return Object.freeze({\n revision: root.revision,\n sourceRowCount: root.rows.size,\n visibleRowCount: visible.size,\n visibleDataRowCount: visible.size,\n rowAt: publicRowAt,\n range: (start, end) => Object.freeze(visible\n .range(start, end)\n .map((entry) => root.rows.get(entry.record.rowId)?.publicRow)\n .filter((row) => row !== undefined)),\n indexOf: (ref) => lookupRank(ref) ?? -1,\n dataIndexOf: (ref) => lookupRank(ref) ?? -1,\n dataRowAt: publicRowAt,\n firstDataRow: () => publicRowAt(0),\n lastDataRow: () => publicRowAt(visible.size - 1),\n nextDataRow: (ref) => {\n const rank = lookupRank(ref);\n return rank === undefined ? undefined : publicRowAt(rank + 1);\n },\n previousDataRow: (ref) => {\n const rank = lookupRank(ref);\n return rank === undefined ? undefined : publicRowAt(rank - 1);\n },\n parentGroupOf: () => undefined,\n nearestVisibleRef: (ref) => {\n if (ref.kind !== \"data\" || visible.rankOf(ref.rowId) === undefined)\n return undefined;\n return dataRef(ref.rowId);\n },\n isGroupExpanded: () => false,\n // The tree's materialized `range` walk, slots only: on a flat root every\n // entry is a data row, and a record's slot is carried across updates, so\n // `entry.record.slot` IS the current binding — no row-store resolution\n // per row (see `membershipFromFlatTree` for the same read).\n ɵvisibleSlotRange: (start, end) => Object.freeze(visible.range(start, end).map((entry) => entry.record.slot)),\n ɵslotOfRowId: (rowId) => root.rows.get(rowId)?.slot,\n ɵslotCapacity: () => root.slotCapacity,\n query: root.queryPlan.query,\n expansion: root.expansion.state,\n });\n}\n","/**\n * Synchronous subset rebuild for a filter-only plan change on an ungrouped\n * query. Runs to completion on the caller's stack, like `sort-rebuild` — a\n * filter-only change is a membership change over an already-sorted set:\n * values, sort keys, group paths, and relative order are all unchanged. No\n * record is reconstructed — not even a flipped one, because no record holds a\n * verdict any more — so the rows HAMT carries by identity exactly as\n * sort-rebuild's does, and the only new structure is the visible tree: a\n * linear merge of the surviving old order with the sorted flipped-in subset,\n * with no comparator sort of the full set, ever.\n */\nimport { adoptEvaluationCache, compareWithSortKeys, filterVerdict, isFilterOnlyChange, sortKeysOf, } from \"./compiled-query\";\nimport { createMembership, setMembershipBit, testMembershipBit, } from \"./membership-bitset\";\nimport { compareOrderStatisticTreeIds, createOrderStatisticTreeFromSortedEntries, instrumentOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { forEachSlotEntry } from \"./slot-vector\";\nimport { createFlatVisibleTree } from \"./visible-index\";\nexport function rebuildRootForFilterOnlyChange(options) {\n const { captured, nextPlan, revision, now, instrumentation } = options;\n if (!isFilterOnlyChange(captured.queryPlan, nextPlan)) {\n throw new TypeError(\"Synchronous filter rebuild requires a filter-only plan change.\");\n }\n if (nextPlan.query.rowGroups.length > 0) {\n throw new TypeError(\"Synchronous filter rebuild requires an ungrouped query.\");\n }\n const startedAt = now();\n // The next plan ADOPTS the captured plan's evaluation cache by reference:\n // one assignment for the whole store instead of a per-row refill. A\n // filter-only change leaves every cached field valid (the field-by-field\n // argument lives on the seam), and the one filter-dependent field — the\n // verdict memo — is tagged with the plan that wrote it, so the loop below\n // still runs the NEW filters over every row.\n adoptEvaluationCache(nextPlan, captured.queryPlan);\n // One hole-skipping pass over ALL records via the slot vector: run the new\n // plan's verdict, record it as a bit in the next root's membership bitset,\n // and diff it against the captured root's bit. Every record carries by\n // identity — flipped or not — so the pass collects nothing but the two flip\n // sets, and only a flipped-IN row needs its keys resolved (survivors keep\n // their existing entry objects, leavers need nothing). The bitset is sized\n // by `captured.slotCapacity` — roots are self-describing, and reading the\n // live allocator instead would let later growth leak into this snapshot's\n // domain. This path throws on grouped plans above, so\n // `captured.visibleSlots` is always the REAL flat bitset, never the\n // grouped sentinel.\n const nextVisibleSlots = createMembership(captured.slotCapacity);\n const flippedIn = [];\n const flippedOut = new Set();\n // Slot order, not source order — sound because nothing downstream reads\n // this walk's order: flippedIn is comparator-sorted below, flippedOut is a\n // set, and the merge consumes the OLD TREE's walk. recordsBySlot replaces\n // the rows-HAMT get; visibleSlots replaces the old-verdict membership get.\n forEachSlotEntry(captured.recordsBySlot, (previous) => {\n const passes = filterVerdict(nextPlan, previous);\n if (passes)\n setMembershipBit(nextVisibleSlots, previous.slot);\n // The OLD verdict is the captured root's membership bit — the flip diff\n // is a set difference between two structures, not a comparison of two\n // stored flags. And since no record stores a verdict, a FLIPPED row needs\n // no new record either: it carries by identity exactly like an unflipped\n // one, and the flip is expressed entirely by where it sits in the new\n // visible tree.\n if (passes === testMembershipBit(captured.visibleSlots, previous.slot)) {\n return;\n }\n if (passes) {\n // Resolved from the adopted store — the same array the captured plan\n // handed out, since a filter-only change leaves the keys untouched.\n const keys = sortKeysOf(nextPlan, previous);\n flippedIn.push(Object.freeze({ record: previous, keys }));\n }\n else {\n flippedOut.add(previous.rowId);\n }\n });\n const flipped = flippedIn.length + flippedOut.size;\n // Identity, unconditionally: a filter-only change reconstructs NO record,\n // so the rows HAMT is carried whole and the transient is never opened.\n const rows = captured.rows;\n let visible = captured.visible;\n // Zero flips carry the captured bitset by identity — same member set —\n // and the freshly-computed (bit-identical) `nextVisibleSlots` is dropped.\n let visibleSlots = captured.visibleSlots;\n if (flipped === 0) {\n // Zero flips (decided here, pinned by tests): still a NEW root at the\n // requested revision under the next plan, with the rows map AND the\n // visible tree object carried wholesale. Reusing the tree is sound even\n // though its entries' keys resolved under the OLD plan and its comparator\n // closure captured it: a filter-only change keeps sort columns and\n // comparators identical, and the next plan now READS THE SAME STORE, so\n // future inserts decorate entries with the very arrays the carried ones\n // hold — ordering stays coherent.\n }\n else {\n // Both sequences below are strictly sorted by the same composite order\n // the tree maintains (comparator, then id): the old tree's in-order walk\n // by construction, the flipped-in subset by this k log k sort — the only\n // sort in the rebuild, and it never sees an unflipped row.\n const compareEntries = (left, right) => compareWithSortKeys(nextPlan, left.record, left.keys, right.record, right.keys) || compareOrderStatisticTreeIds(left.record.rowId, right.record.rowId);\n flippedIn.sort(compareEntries);\n // Single linear merge: surviving entries keep their ENTRY objects (a\n // still-passing row is by definition unflipped — record and keys are both\n // unchanged), flipped-out rows are skipped, flipped-in entries interleave\n // where the composite order puts them.\n const merged = [];\n let next = 0;\n // `range(0, size)` rather than `entries()`: this walk always runs to\n // completion, and the tree's non-generator walk is the cheaper way to\n // get one — ~1ms against ~30ms at 50,000 rows (see `iterateEntries`).\n for (const entry of captured.visible.rows.range(0, captured.visible.rows.size)) {\n if (flippedOut.has(entry.record.rowId))\n continue;\n while (next < flippedIn.length &&\n compareEntries(flippedIn[next], entry) < 0) {\n merged.push(flippedIn[next]);\n next += 1;\n }\n merged.push(entry);\n }\n while (next < flippedIn.length) {\n merged.push(flippedIn[next]);\n next += 1;\n }\n visible = Object.freeze({\n rows: createOrderStatisticTreeFromSortedEntries(instrumentOrderStatisticTree(createFlatVisibleTree(nextPlan), instrumentation), merged, \n // Both proofs are earned by the merge directly above, and neither\n // would be available to a caller that re-sorted the full set.\n // Order: a merge of two strictly-increasing, id-disjoint sequences\n // under one total order is strictly increasing — so the n−1\n // verification would re-derive what the loop just guaranteed.\n // byId: the visible set changes by exactly `flippedOut` leaving and\n // `flippedIn` arriving; every survivor is pushed into `merged` as the\n // base tree's OWN entry object (unflipped ⇒ record and keys\n // unchanged), which is the identity precondition derived mode\n // requires. Cost drops from n inserts to `flipped` edits.\n {\n orderIsProven: true,\n derivedById: {\n base: captured.visible.rows,\n removedIds: flippedOut,\n addedEntries: flippedIn,\n },\n }),\n });\n // The verdict pass above already set a bit for every member, so the new\n // root takes its bitset directly — no second walk over the tree.\n visibleSlots = nextVisibleSlots;\n }\n const root = Object.freeze({\n revision,\n parentRevision: revision - 1,\n rows,\n sourceOrder: captured.sourceOrder,\n // A filter-only change reconstructs no record and touches no slot, so\n // the slot vector and its domain carry by identity with the rows HAMT.\n recordsBySlot: captured.recordsBySlot,\n slotCapacity: captured.slotCapacity,\n visibleSlots,\n visible,\n queryPlan: nextPlan,\n expansion: captured.expansion,\n cause: Object.freeze({ kind: \"set-query\" }),\n });\n if (instrumentation !== undefined) {\n instrumentation.work.filterRebuilds += 1;\n instrumentation.work.evaluationCacheAdoptions += 1;\n instrumentation.work.filterRowsFlipped += flipped;\n instrumentation.work.filterMergeSortedInsertions += flippedIn.length;\n instrumentation.work.filterRebuildMs += Math.max(0, now() - startedAt);\n }\n return root;\n}\n","/**\n * Filter verdicts are not stored. A committed root already carries the answer\n * structurally: a row passes this root's filters exactly when it is a MEMBER\n * of the root's visible structure. This module is the one place that knows\n * which structure answers for which root shape.\n *\n * - **Flat root** (`query.rowGroups.length === 0`): `root.visible.rows` holds\n * one entry per passing row and nothing else, so membership is a lookup.\n * This is the same predicate `nearestVisibleRef` has always used.\n * - **Grouped root**: `root.visible.rows` is deliberately EMPTY (a grouped\n * visible index attaches the group index to an empty flat tree), so the\n * answer lives in the group index: every inserted row — passing or not —\n * gets a `rowParents` entry, and only passing rows are inserted into their\n * leaf group's `leaves` tree. So `rowParents` locates the leaf group and\n * `leaves` holds the verdict.\n *\n * Absence is the answer, not a fault: a row this root never saw, or one its\n * filters reject, is simply not a member. Nothing here fails loud.\n *\n * These read a COMMITTED root, so they answer \"did this row pass under the\n * plan that built this root\" — the OLD verdict at every site that compares\n * against a new one. A NEW verdict is computed, never resolved: producers\n * call `filterVerdict(plan, record)` and use it locally to decide where the\n * row goes.\n */\nimport { getGroupIndex, rowPassesFilterInGroupIndex } from \"./group-index\";\n/**\n * The grouped half of the seam, re-exported for callers that hold a group\n * index rather than a root (a transaction rebuilds the index, so those\n * callers must read the PREVIOUS one explicitly). Its body lives in\n * `./group-index` because it reads that module's own invariant, and because\n * importing it back from here would cycle.\n */\nexport { rowPassesFilterInGroupIndex };\n/** Did `rowId` pass the filters of the plan that built `root`? */\nexport function rowPassesFilter(root, rowId) {\n const grouped = getGroupIndex(root.visible);\n return grouped === undefined\n ? root.visible.rows.get(rowId) !== undefined\n : rowPassesFilterInGroupIndex(grouped, rowId);\n}\n","/**\n * Synchronous whole-root rebuild for a sort-only plan change on an ungrouped\n * query. Runs to completion on the caller's stack — the deliberate trade\n * measured in #457: scheduler hops cost frames in the browser, and identity\n * carry makes the total work small enough to spend inline. No record is\n * rebuilt and no rows transient is opened: the committed root reuses the\n * captured `rows` map BY IDENTITY, and only the next plan's sort-key store\n * and the visible tree are produced fresh.\n */\nimport { compareWithSortKeys, fillSortKeysFromPrevious, isSortOnlyChange, } from \"./compiled-query\";\nimport { rowPassesFilter } from \"./filter-membership\";\nimport { compareOrderStatisticTreeIds, createOrderStatisticTreeFromSortedEntries, instrumentOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { createFlatVisibleTree } from \"./visible-index\";\nexport function rebuildRootForSortOnlyChange(options) {\n const { captured, nextPlan, revision, now, instrumentation } = options;\n if (!isSortOnlyChange(captured.queryPlan, nextPlan)) {\n throw new TypeError(\"Synchronous rebuild requires a sort-only plan change.\");\n }\n if (nextPlan.query.rowGroups.length > 0) {\n throw new TypeError(\"Synchronous rebuild requires an ungrouped query.\");\n }\n const startedAt = now();\n // Decorated sort: keys resolve ONCE per row here (the fill already returns\n // them) and travel with the record, so the O(n log n) comparison loop does\n // no WeakMap lookups — measured at 50k, per-comparison resolution costs\n // ~4x the decorated form. The pairs ARE the tree's entry type, so the\n // sorted array feeds the bulk constructor directly.\n const visible = [];\n // `range(0, size)` rather than `entries()`: this walk always runs to\n // completion into an array, and the tree's non-generator walk is the\n // cheaper way to get one (see `iterateEntries`).\n for (const source of captured.sourceOrder.range(0, captured.sourceOrder.size)) {\n const previous = captured.rows.get(source.rowId);\n if (previous === undefined)\n continue;\n // Seed the NEXT plan's store for every carried record — the one part of\n // a record's derived state that is plan-scoped. Everything else\n // (metadata, publicRow, integrity) carries with the record itself.\n const keys = fillSortKeysFromPrevious(nextPlan, captured.queryPlan, previous, instrumentation);\n // A sort-only change cannot move a row across the filter, so the CAPTURED\n // root's membership is this row's verdict under the next plan too.\n if (rowPassesFilter(captured, source.rowId)) {\n visible.push(Object.freeze({ record: previous, keys }));\n }\n }\n // The key comparator already totalizes distinct rows via its final\n // sourceOrder comparison, so the id clause is unreachable today. It stays\n // because the composite mirrors the tree's own order (comparator, then id)\n // exactly, so this sort can never diverge from the bulk constructor's\n // strict-order verification even if the comparator ever stopped being\n // total. Every record's keys were seeded into nextPlan's store by the\n // carry loop above, so later insert sites can decorate their entries from\n // the store; the tree's own comparator reads only entry-carried keys.\n visible.sort((left, right) => compareWithSortKeys(nextPlan, left.record, left.keys, right.record, right.keys) || compareOrderStatisticTreeIds(left.record.rowId, right.record.rowId));\n const tree = createOrderStatisticTreeFromSortedEntries(instrumentOrderStatisticTree(createFlatVisibleTree(nextPlan), instrumentation), visible, \n // Order only. The `visible.sort` above is under the tree's own composite\n // order (comparator, then id) over ids drawn from a HAMT, so it is\n // strictly increasing by construction and the n−1 verification can only\n // re-confirm it. Derived byId is deliberately NOT taken: a sort-only\n // change keeps the same entry SET but allocates a fresh entry object per\n // row to carry the next plan's keys, so every \"survivor\" is a new object\n // and a derived map would keep pointing at the previous plan's entries.\n { orderIsProven: true });\n const root = Object.freeze({\n revision,\n parentRevision: revision - 1,\n // Identity — the entire point: records, publicRow, integrity, and the\n // rows HAMT all survive a sort-only change untouched.\n rows: captured.rows,\n sourceOrder: captured.sourceOrder,\n // Same identity carry: a sort-only change touches no record and no slot.\n recordsBySlot: captured.recordsBySlot,\n slotCapacity: captured.slotCapacity,\n // A sort-only change reorders the members but keeps the member SET\n // identical (the loop above pushed exactly the captured membership), so\n // the bitset carries by identity too.\n visibleSlots: captured.visibleSlots,\n visible: Object.freeze({ rows: tree }),\n queryPlan: nextPlan,\n expansion: captured.expansion,\n cause: Object.freeze({ kind: \"set-query\" }),\n });\n if (instrumentation !== undefined) {\n instrumentation.work.synchronousRebuilds += 1;\n instrumentation.work.synchronousRebuildMs += Math.max(0, now() - startedAt);\n }\n return root;\n}\n","import { adoptEvaluationCache, fillSortKeysFromPrevious, sortKeysIfPasses, filterVerdict, isFilterOnlyChange, } from \"./compiled-query\";\nimport { createPersistentMap, instrumentPersistentMap, } from \"./persistent/persistent-map\";\nimport { instrumentOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { forEachSlotEntry, slotVectorFromEntries } from \"./slot-vector\";\nimport { orderedRowEntry } from \"./ordered-row-entry\";\nimport { createFlatVisibleTree } from \"./visible-index\";\nimport { clearMembershipBit, cloneMembership, createMembership, setMembershipBit, } from \"./membership-bitset\";\nimport { registerCooperativeTransitionCandidateDiagnostics, } from \"./cooperative-transition\";\n/**\n * The flat (ungrouped) cooperative transition candidate. Builds against an\n * immutable source root and replays exact live-row deltas; nothing reachable\n * here is published before `finish` returns the swap root.\n *\n * A flat candidate has no group index, no bulk builder, no seal phase, and no\n * expansion-override reconciliation: it completes when the source sweep and\n * the delta queue drain.\n *\n * Two lanes (#490):\n *\n * - **Identity-carry** (flat `set-query` over a flat captured root): records,\n * the rows HAMT and the slot vector all carry BY IDENTITY from the captured\n * root — the sweep only re-runs the filter verdict, decorates survivors\n * with next-plan sort keys, and sets membership bits. Zero evaluations,\n * zero HAMT writes, zero record allocations.\n * - **Evaluate** (`set-derivations`, or a grouped captured root): metadata\n * genuinely changes, so every row is re-evaluated into a fresh record — but\n * the containers are the identity lane's UPGRADED forms from construction:\n * a transient rows map (started EMPTY, not from the captured map — the\n * records are re-evaluated, so nothing captured can carry), the transient\n * visible tree, the mutable slot array and the membership bitset, all\n * frozen/chunked once at `finish`.\n */\nexport function createFlatCooperativeCandidate(options) {\n const operation = options.operation;\n const instrumentation = options.instrumentation;\n /**\n * Lane eligibility (spec amendment): identity-carry requires the CAPTURED\n * plan to be ungrouped too — a grouped→flat `set-query` captures records\n * whose metadata still holds the grouped `groupPath`/`aggregateLeaves`, so\n * those transitions re-evaluate. The NEXT plan is already known flat: the\n * shared constructor dispatches here only when\n * `queryPlan.query.rowGroups.length === 0`.\n */\n const identityCarry = options.operation === \"set-query\" &&\n options.captured.queryPlan.query.rowGroups.length === 0;\n /**\n * Whole-store evaluation-cache handoff, gated on the SAME precondition the\n * synchronous filter rebuild owns (`adoptEvaluationCache`'s documented\n * contract): only a filter-only change leaves every cached field —\n * including the sort-key arrays, which are index-aligned to the plan that\n * wrote them — valid under the next plan. On a sort-changed set-query the\n * per-row `fillSortKeysFromPrevious` below carries what it can instead.\n * Pure perf lever either way: nothing below depends on the adoption.\n */\n const adopted = isFilterOnlyChange(options.captured.queryPlan, options.queryPlan);\n if (adopted) {\n adoptEvaluationCache(options.queryPlan, options.captured.queryPlan);\n if (instrumentation !== undefined) {\n instrumentation.work.evaluationCacheAdoptions += 1;\n }\n }\n let retained = {\n captured: options.captured,\n queryPlan: options.queryPlan,\n sourceOrder: options.captured.sourceOrder,\n expansion: options.captured.expansion,\n transientFlatRows: instrumentOrderStatisticTree(createFlatVisibleTree(options.queryPlan), instrumentation).asTransient(),\n recordsBySlot: [],\n slotCapacity: options.captured.slotCapacity,\n membership: createMembership(options.captured.slotCapacity),\n sweep: identityCarry ? { chunkIndex: 0 } : null,\n transientRows: identityCarry\n ? null\n : instrumentPersistentMap(createPersistentMap(), instrumentation).asTransient(),\n iterator: identityCarry ? null : options.captured.sourceOrder.entries(),\n deltas: [],\n reconciledExpansion: undefined,\n };\n // Candidate methods retain only the nullable state binding below. Clear the\n // input container so it cannot independently keep the captured root alive.\n options = undefined;\n let deltaIndex = 0;\n let deltaRowIndex = 0;\n let deltaRowPhase = \"remove\";\n let completedRows = 0;\n let totalRows = retained.captured.rows.size;\n let released = false;\n const resetOverrideReconciliation = (state) => {\n // A flat candidate never starts an override reconciliation pass, so the\n // grouped module's `totalRows -= reconciliation.remaining` shrink can\n // never apply here; the only effect this reset has on the flat path is\n // clearing the reconciled-expansion marker.\n state.reconciledExpansion = undefined;\n };\n /**\n * Identity-carry unit: the record carries WHOLE — metadata included —\n * because on an ungrouped `set-query` no metadata field can change:\n * `groupPath` is `[]` under both plans (both are flat — the lane predicate\n * above pins the captured side), and `aggregateLeaves` derive from\n * derivations, which `set-query` does not touch. Leaves DO embed sortKeys\n * in their `dependency`, and they have flat-path readers: the group index\n * consumes them wholesale (`group-index.ts`), and `transaction-draft.ts`\n * reads them on flat commits too — but only plan-stable fields (`columnId`\n * and the column definition's own `aggregate` object in its leaf compare,\n * and `rebaseSourceOrder` rewrites `dependency.sourceOrder` while carrying\n * the embedded sort keys along unchanged). So stale embedded sortKeys can\n * PROPAGATE through later flat transactions without ever being read as\n * sort authority; a future grouped-leaves reader must re-derive before\n * consuming a root produced here. Sort keys proper are the one\n * plan-scoped piece, resolved via the per-row carry fill exactly as\n * `sort-rebuild.ts` does.\n */\n const carryRecord = (record) => {\n const state = retained;\n if (state === undefined)\n return;\n if (instrumentation !== undefined) {\n // `rowsEvaluated` deliberately NOT incremented: nothing is evaluated\n // on this lane — that zero is the dense claim `work.test.ts` pins.\n instrumentation.work.transitionRows += 1;\n }\n if (adopted) {\n // Fused: the adopted cache answers verdict AND keys from ONE read —\n // `work.test.ts` pins the one-lookup-per-swept-row budget, and the\n // un-fused arm below stays pinned as the counter's control.\n const keys = sortKeysIfPasses(state.queryPlan, record, instrumentation);\n if (keys !== undefined) {\n state.transientFlatRows.insertOrReplace(Object.freeze({ record, keys }));\n setMembershipBit(state.membership, record.slot);\n }\n return;\n }\n if (filterVerdict(state.queryPlan, record, instrumentation)) {\n const keys = fillSortKeysFromPrevious(state.queryPlan, state.captured.queryPlan, record, instrumentation);\n state.transientFlatRows.insertOrReplace(Object.freeze({ record, keys }));\n setMembershipBit(state.membership, record.slot);\n }\n };\n /**\n * Converts the identity-carry candidate to replayable form on the FIRST\n * delta: keyed mutation via the transient, per-slot mutation via a whole\n * copy of the carried vector. From here `finish` builds fresh structures\n * (the upgraded arm) — the carried ones are no longer the truth.\n */\n const upgradeForReplay = (state) => {\n state.transientRows = state.captured.rows.asTransient();\n forEachSlotEntry(state.captured.recordsBySlot, (record, slot) => {\n state.recordsBySlot[slot] = record;\n });\n };\n const removeRecord = (record) => {\n const state = retained;\n if (state === undefined)\n return;\n // `transientRows` is non-null whenever a remove can run: the evaluate\n // lane arms it at construction, and the identity lane's `append` (which\n // precedes every replay unit) upgrades before the first one.\n state.transientRows.delete(record.rowId);\n clearMembershipBit(state.membership, record.slot);\n state.recordsBySlot[record.slot] = undefined;\n state.transientFlatRows.remove(record.rowId);\n };\n const insertRecord = (source) => {\n const state = retained;\n if (state === undefined)\n return;\n if (identityCarry) {\n // Identity-lane replay insert (build routes through `sweepChunk`, so\n // `transientRows` is already armed here): the delta TARGET root's\n // record carries by identity too — it was evaluated under the model's\n // still-committed plan (the captured plan's lineage), and the\n // candidate plan differs only in filter/sort, which cannot change\n // metadata (see `carryRecord`). Only the verdict is re-run, under the\n // candidate's plan.\n state.transientRows.set(source.rowId, source);\n state.recordsBySlot[source.slot] = source;\n carryRecord(source);\n return;\n }\n // Evaluate lane, build AND replay: metadata genuinely depends on the\n // next plan's derivations (or the captured root was grouped), so the\n // record is rebuilt — but into the transient containers, so the per-row\n // cost is the evaluation itself, not a HAMT path copy.\n if (instrumentation !== undefined) {\n instrumentation.work.transitionRows += 1;\n instrumentation.work.rowsEvaluated += 1;\n }\n const metadata = state.queryPlan.evaluate({\n rowId: source.rowId,\n row: source.row,\n sourceOrder: source.sourceOrder,\n slot: source.slot,\n });\n const record = Object.freeze({ ...source, metadata });\n state.transientRows.set(record.rowId, record);\n state.recordsBySlot[record.slot] = record;\n // Computed here, used here: the flat tree this inserts into is where\n // the verdict is recorded, and the membership bit rides along.\n if (filterVerdict(state.queryPlan, record)) {\n state.transientFlatRows.insertOrReplace(orderedRowEntry(state.queryPlan, record));\n setMembershipBit(state.membership, record.slot);\n }\n };\n const removeReplayRow = (rowId) => {\n const state = retained;\n if (state === undefined)\n return;\n const previous = state.transientRows.get(rowId);\n if (previous !== undefined)\n removeRecord(previous);\n };\n const insertReplayRow = (target, rowId) => {\n if (retained === undefined)\n return;\n const next = target.rows.get(rowId);\n if (next !== undefined)\n insertRecord(next);\n };\n /**\n * Identity lane's build unit: the next ALLOCATED slot-vector chunk, whole\n * (M2 amendment, #490). Under #518's slice runner the budget clock is\n * consulted after the first completed unit and then once per 32-unit\n * stride, so a ~1ms chunk unit means slices carry one or two chunks and\n * the 50k sweep pays ~50 scheduler hops instead of ~196 — the per-row\n * unit's slice overhead was the remaining fit-estimate gap, and\n * `maxUnitsPerSlice` becomes a non-binding backstop for this lane.\n *\n * `completedRows` stays ROW-denominated per the status contract: it\n * advances by the POPULATED slots processed, so holes skip for free and\n * the terminal accounting (`completedRows === totalRows` at settle) stays\n * exact. An absent chunk is all holes — zero rows — so it is skipped\n * without spending the unit; a present chunk bounds the unit's work at\n * one `SLOT_VECTOR_CHUNK` scan regardless of how many slots survive.\n */\n const sweepChunk = (state) => {\n const cursor = state.sweep;\n if (cursor === null)\n return false;\n const chunks = state.captured.recordsBySlot.chunks;\n while (cursor.chunkIndex < chunks.length) {\n const chunk = chunks[cursor.chunkIndex];\n cursor.chunkIndex += 1;\n if (chunk === undefined)\n continue;\n for (let offset = 0; offset < chunk.length; offset += 1) {\n const record = chunk[offset];\n if (record !== undefined) {\n carryRecord(record);\n completedRows += 1;\n }\n }\n return true;\n }\n state.sweep = null;\n return false;\n };\n const candidate = {\n get completedRows() {\n return completedRows;\n },\n get totalRows() {\n return totalRows;\n },\n append(delta) {\n const state = retained;\n if (state === undefined)\n return;\n resetOverrideReconciliation(state);\n if (identityCarry && state.transientRows === null) {\n upgradeForReplay(state);\n }\n state.deltas.push(delta);\n // Capacity is monotone across commits, so the widest replayed target\n // bounds every slot this candidate can ever bind (still a captured\n // root's value — the live allocator is never consulted).\n state.slotCapacity = Math.max(state.slotCapacity, delta.target.slotCapacity);\n // Bitset capacity decision: the bitset is maintained incrementally, so\n // widening reallocates it here — a whole copy into the wider word\n // array. Provably correct because slots are stable (a bit's index\n // never changes) and setting a bit beyond a Uint32Array's length is a\n // silent no-op, so the copy MUST precede any replayed write to a\n // grown slot; `append` runs before every such write.\n // `membership` is non-null on every live candidate (both lanes arm it\n // at construction; only `release` nulls it, and the `retained` guard\n // above covers that).\n if ((state.slotCapacity + 31) >>> 5 > state.membership.length) {\n state.membership = cloneMembership(state.membership, state.slotCapacity);\n }\n totalRows += delta.affectedRowIds.length * 2 + 1;\n },\n step() {\n const state = retained;\n if (state === undefined)\n return true;\n if (identityCarry) {\n if (sweepChunk(state))\n return false;\n }\n else if (state.iterator !== null) {\n const source = state.iterator.next();\n if (!source.done) {\n const previous = state.captured.rows.get(source.value.rowId);\n if (previous !== undefined)\n insertRecord(previous);\n completedRows += 1;\n return false;\n }\n state.iterator = null;\n }\n while (deltaIndex < state.deltas.length) {\n const delta = state.deltas[deltaIndex];\n if (delta === null) {\n deltaIndex += 1;\n deltaRowIndex = 0;\n deltaRowPhase = \"remove\";\n continue;\n }\n const rowId = delta.affectedRowIds[deltaRowIndex];\n if (rowId !== undefined) {\n if (deltaRowPhase === \"remove\") {\n removeReplayRow(rowId);\n deltaRowPhase = \"insert\";\n }\n else {\n insertReplayRow(delta.target, rowId);\n deltaRowPhase = \"remove\";\n deltaRowIndex += 1;\n }\n completedRows += 1;\n return false;\n }\n state.sourceOrder = delta.target.sourceOrder;\n state.expansion = delta.target.expansion;\n resetOverrideReconciliation(state);\n state.deltas[deltaIndex] = null;\n deltaIndex += 1;\n deltaRowIndex = 0;\n deltaRowPhase = \"remove\";\n completedRows += 1;\n return false;\n }\n // Terminal condition: the flat candidate is complete once the source\n // sweep and the delta queue drain. This mirrors the grouped module's\n // `reconcileOneOverride` short-circuit for a groupless state byte for\n // byte — it marks the expansion reconciled and reports completion in\n // the same step, without counting a unit against `completedRows`.\n state.reconciledExpansion = state.expansion;\n return true;\n },\n finish(revision) {\n const state = retained;\n if (state === undefined)\n throw new Error(\"Released transition candidate.\");\n const visible = Object.freeze({\n rows: state.transientFlatRows.freeze(),\n });\n if (identityCarry && state.transientRows === null) {\n // Delta-free identity carry: rows, the slot vector and its domain\n // all carry from the captured root's own objects, and membership is\n // the bitset the sweep already filled — no `membershipFromFlatTree`\n // walk, no slot sweep, on the finish stack.\n return Object.freeze({\n revision,\n parentRevision: revision - 1,\n rows: state.captured.rows,\n sourceOrder: state.sourceOrder,\n recordsBySlot: state.captured.recordsBySlot,\n slotCapacity: state.slotCapacity,\n visibleSlots: state.membership,\n visible,\n queryPlan: state.queryPlan,\n expansion: state.expansion,\n cause: Object.freeze({ kind: operation }),\n });\n }\n const slotEntries = [];\n for (let slot = 0; slot < state.recordsBySlot.length; slot += 1) {\n const record = state.recordsBySlot[slot];\n if (record !== undefined)\n slotEntries.push([slot, record]);\n }\n // Upgraded identity lane and evaluate lane share this arm: freeze the\n // transient rows map, chunk the mutable slot array, and publish the\n // membership bitset exactly as maintained by the sweep and replay —\n // no lane in this module walks the visible tree for membership.\n return Object.freeze({\n revision,\n parentRevision: revision - 1,\n rows: state.transientRows.freeze(),\n sourceOrder: state.sourceOrder,\n recordsBySlot: slotVectorFromEntries(slotEntries, state.slotCapacity),\n slotCapacity: state.slotCapacity,\n visibleSlots: state.membership,\n visible,\n queryPlan: state.queryPlan,\n expansion: state.expansion,\n cause: Object.freeze({ kind: operation }),\n });\n },\n release() {\n const state = retained;\n if (state === undefined)\n return;\n released = true;\n state.iterator = null;\n state.sweep = null;\n state.transientRows = null;\n state.transientFlatRows = null;\n state.membership = null;\n state.deltas.fill(null);\n state.deltas.length = 0;\n state.recordsBySlot.length = 0;\n state.reconciledExpansion = undefined;\n retained = undefined;\n },\n };\n registerCooperativeTransitionCandidateDiagnostics(candidate, () => Object.freeze({\n released,\n hasCapturedRoot: retained !== undefined,\n hasQueryPlan: retained !== undefined,\n hasIterator: retained !== undefined &&\n (identityCarry ? retained.sweep !== null : retained.iterator !== null),\n deltaCount: retained?.deltas.reduce((count, delta) => count + (delta === null ? 0 : 1), 0) ?? 0,\n hasRows: retained !== undefined,\n hasSourceOrder: retained !== undefined,\n hasExpansion: retained !== undefined,\n hasFlatRows: retained !== undefined,\n // The flat lane never holds a group index or a bulk builder; the shape\n // matches the grouped module's registration with the grouped-only\n // fields pinned to their groupless values.\n hasGroups: false,\n deltaSlotCount: retained?.deltas.length ?? 0,\n processedDeltaCount: retained === undefined ? 0 : deltaIndex,\n retainedDeltaRootCount: retained?.deltas.reduce((count, delta) => count + (delta === null ? 0 : 1), 0) ?? 0,\n overrideReconciliationRemaining: 0,\n }));\n return candidate;\n}\n","import { attachGroupIndex, createGroupIndex, createGroupIndexBuildDraft, getGroupIndex, setGroupOverride, updateGroupIndex, } from \"./group-index\";\nimport { createPersistentMap, instrumentPersistentMap, } from \"./persistent/persistent-map\";\nimport { instrumentOrderStatisticTree } from \"./persistent/order-statistic-tree\";\nimport { slotVectorFromEntries } from \"./slot-vector\";\nimport { EMPTY_MEMBERSHIP } from \"./membership-bitset\";\nimport { createFlatVisibleTree } from \"./visible-index\";\nimport { createFlatCooperativeCandidate } from \"./flat-cooperative-candidate\";\nconst candidateDiagnostics = new WeakMap();\n/**\n * Registers a candidate's diagnostics reader in the shared WeakMap so\n * `getCooperativeTransitionCandidateDiagnosticsForTesting` serves every lane\n * (the grouped lanes here and the flat lane in its own module) uniformly.\n */\nexport function registerCooperativeTransitionCandidateDiagnostics(candidate, read) {\n candidateDiagnostics.set(candidate, read);\n}\nexport function getCooperativeTransitionCandidateDiagnosticsForTesting(candidate) {\n const read = candidateDiagnostics.get(candidate);\n if (read === undefined) {\n throw new TypeError(\"Diagnostics require a cooperative transition candidate.\");\n }\n return read();\n}\nconst DEFAULT_BUDGET_MS = 0.25;\n// A clock may be coarse, mocked, or stalled. This cap guarantees a yield while\n// keeping enough per-slice work to amortize scheduler overhead.\nconst DEFAULT_MAX_UNITS_PER_SLICE = 256;\n/**\n * The budget clock is consulted after the FIRST completed unit and then once\n * per this many completed units — not once per unit (#500): reading `now()`\n * every unit was itself a measurable share of slice time once seal units\n * became row-sized (~1-2µs each). Worst-case budget overshoot is\n * stride × per-unit cost ≈ 32 × 2µs ≈ 64µs (a full stride of units runs\n * between two consecutive checks) — noise against a 16.7ms\n * frame. The first-unit check keeps a slice honest when individual units are\n * expensive (custom aggregators and accessors run arbitrary consumer code):\n * one over-budget unit ends the slice immediately instead of running a full\n * stride of them. The stride divides DEFAULT_MAX_UNITS_PER_SLICE\n * (32 × 8 = 256), so the hard cap still lands exactly on a stride boundary.\n */\nexport const TRANSITION_CLOCK_CHECK_STRIDE = 32;\nfunction bestEffortCancel(cancel) {\n try {\n cancel?.();\n }\n catch {\n // Scheduler cancellation is advisory infrastructure cleanup. It must not\n // interrupt the model-owned release and settlement that follows.\n }\n}\nfunction postTaskScheduler(postTask, fallback) {\n return {\n schedule(task) {\n const controller = typeof AbortController === \"function\" ? new AbortController() : null;\n let cancelled = false;\n let ran = false;\n let cancelFallback;\n const run = () => {\n if (cancelled || ran)\n return;\n ran = true;\n task();\n };\n const recover = () => {\n if (cancelled || ran || cancelFallback !== undefined)\n return;\n cancelFallback = fallback.schedule(run);\n };\n try {\n void Promise.resolve(postTask(run, controller ? { signal: controller.signal } : undefined)).catch(recover);\n }\n catch {\n recover();\n }\n return () => {\n if (cancelled)\n return;\n cancelled = true;\n const cancel = cancelFallback;\n cancelFallback = undefined;\n try {\n controller?.abort();\n }\n catch {\n // A hostile AbortController is no more authoritative than the task.\n }\n bestEffortCancel(cancel);\n };\n },\n };\n}\nfunction messageChannelScheduler() {\n if (typeof MessageChannel !== \"function\")\n return null;\n return {\n schedule(task) {\n const channel = new MessageChannel();\n let cancelled = false;\n const close = () => {\n try {\n channel.port1.close();\n }\n catch {\n // Closing a host channel is best-effort cleanup.\n }\n try {\n channel.port2.close();\n }\n catch {\n // Closing a host channel is best-effort cleanup.\n }\n };\n channel.port1.onmessage = () => {\n close();\n if (!cancelled)\n task();\n };\n try {\n channel.port2.postMessage(undefined);\n }\n catch (error) {\n close();\n throw error;\n }\n return () => {\n if (cancelled)\n return;\n cancelled = true;\n close();\n };\n },\n };\n}\nfunction timeoutScheduler() {\n return {\n schedule(task) {\n const handle = setTimeout(task, 0);\n return () => clearTimeout(handle);\n },\n };\n}\nfunction fallbackScheduler() {\n const messageChannel = messageChannelScheduler();\n const timeout = timeoutScheduler();\n return {\n schedule(task) {\n if (messageChannel !== null) {\n try {\n return messageChannel.schedule(task);\n }\n catch {\n // A present but unusable MessageChannel must not strand the task.\n }\n }\n return timeout.schedule(task);\n },\n };\n}\n/** Resolves browser-preferred scheduling with a safe server/runtime fallback. */\nexport function createDefaultCooperativeTransitionScheduler() {\n const fallback = fallbackScheduler();\n try {\n const candidate = Reflect.get(globalThis, \"scheduler\");\n if (candidate && typeof candidate.postTask === \"function\") {\n return postTaskScheduler(candidate.postTask.bind(candidate), fallback);\n }\n }\n catch {\n // Host globals are not trusted; continue to the capability fallbacks.\n }\n return fallback;\n}\nexport function createCooperativeTransitionRuntime(options) {\n const budgetMs = options.budgetMs ?? DEFAULT_BUDGET_MS;\n const maxUnitsPerSlice = options.maxUnitsPerSlice ?? DEFAULT_MAX_UNITS_PER_SLICE;\n if (!Number.isFinite(budgetMs) || budgetMs <= 0) {\n throw new RangeError(\"The cooperative transition budget must be positive.\");\n }\n if (!Number.isSafeInteger(maxUnitsPerSlice) || maxUnitsPerSlice <= 0) {\n throw new RangeError(\"The cooperative transition unit cap must be a positive safe integer.\");\n }\n const scheduler = options.scheduler ?? createDefaultCooperativeTransitionScheduler();\n const now = options.now ??\n (() => typeof performance === \"object\" &&\n performance !== null &&\n typeof performance.now === \"function\"\n ? performance.now()\n : Date.now());\n const instrumentedScheduler = options.instrumentation === undefined\n ? undefined\n : {\n schedule(task) {\n const token = {};\n options.instrumentation.scheduledCallbacks.add(token);\n const scheduledAt = now();\n let cancel;\n try {\n cancel = scheduler.schedule(() => {\n options.instrumentation.scheduledCallbacks.delete(token);\n options.instrumentation.work.schedulerWaitDurations.push(Math.max(0, now() - scheduledAt));\n task();\n });\n }\n catch (error) {\n options.instrumentation.scheduledCallbacks.delete(token);\n throw error;\n }\n return () => {\n options.instrumentation.scheduledCallbacks.delete(token);\n bestEffortCancel(cancel);\n };\n },\n };\n return Object.freeze({\n scheduler: instrumentedScheduler ?? scheduler,\n now,\n budgetMs,\n maxUnitsPerSlice,\n instrumentation: options.instrumentation,\n });\n}\n/**\n * Runs at least one unit; the budget clock is consulted after the first\n * completed unit and then once per TRANSITION_CLOCK_CHECK_STRIDE completed\n * units (the hard unit cap is checked every unit and is a whole number of\n * strides).\n */\nexport function runCooperativeTransitionSlice(runtime, step) {\n const startedAt = runtime.now();\n let completedUnits = 0;\n do {\n if (step()) {\n if (runtime.instrumentation !== undefined) {\n runtime.instrumentation.work.schedulerSliceDurations.push(Math.max(0, runtime.now() - startedAt));\n }\n return true;\n }\n completedUnits += 1;\n } while (completedUnits < runtime.maxUnitsPerSlice &&\n ((completedUnits !== 1 &&\n completedUnits % TRANSITION_CLOCK_CHECK_STRIDE !== 0) ||\n runtime.now() - startedAt < runtime.budgetMs));\n if (runtime.instrumentation !== undefined) {\n runtime.instrumentation.work.schedulerSliceDurations.push(Math.max(0, runtime.now() - startedAt));\n }\n return false;\n}\n/**\n * Builds against an immutable source root and replays exact live-row deltas.\n * Nothing reachable here is published before `finish` returns the swap root.\n *\n * Ungrouped transitions dispatch to the flat module; the candidate built here\n * serves the two GROUPED lanes (bulk builder and incremental group index).\n */\nexport function createCooperativeTransitionCandidate(options) {\n if (options.queryPlan.query.rowGroups.length === 0) {\n return createFlatCooperativeCandidate(options);\n }\n const operation = options.operation;\n const instrumentation = options.instrumentation;\n const builtinAggregatesOnly = options.queryPlan.derivations.every((derivation) => derivation.aggregate === undefined ||\n typeof derivation.aggregate === \"string\");\n const useBulkGroupBuilder = builtinAggregatesOnly;\n const initialRows = instrumentPersistentMap(createPersistentMap(), instrumentation);\n let retained = {\n captured: options.captured,\n queryPlan: options.queryPlan,\n rows: initialRows,\n rowBuilder: useBulkGroupBuilder ? initialRows.asTransient() : undefined,\n sourceOrder: options.captured.sourceOrder,\n expansion: options.captured.expansion,\n flatRows: instrumentOrderStatisticTree(createFlatVisibleTree(options.queryPlan), instrumentation),\n recordsBySlot: [],\n slotCapacity: options.captured.slotCapacity,\n groups: !useBulkGroupBuilder\n ? createGroupIndex([], options.queryPlan, options.aggregateFilteredRows, createPersistentMap(), operation, getGroupIndex(options.captured.visible), instrumentation)\n : undefined,\n groupBuilder: !useBulkGroupBuilder\n ? undefined\n : createGroupIndexBuildDraft({\n queryPlan: options.queryPlan,\n aggregateFilteredRows: options.aggregateFilteredRows,\n operation,\n reusable: getGroupIndex(options.captured.visible),\n overrides: options.captured.expansion.overrides,\n instrumentation,\n }),\n groupSealRemaining: 0,\n iterator: options.captured.sourceOrder.entries(),\n deltas: [],\n appliedOverrides: createPersistentMap(),\n reconciledExpansion: undefined,\n overrideReconciliation: undefined,\n };\n // Candidate methods retain only the nullable state binding below. Clear the\n // input container so it cannot independently keep the captured root alive.\n options = undefined;\n let deltaIndex = 0;\n let deltaRowIndex = 0;\n let deltaRowPhase = \"remove\";\n let completedRows = 0;\n let totalRows = retained.captured.rows.size;\n let released = false;\n const resetOverrideReconciliation = (state) => {\n if (state.overrideReconciliation !== undefined) {\n totalRows -= state.overrideReconciliation.remaining;\n state.overrideReconciliation = undefined;\n }\n state.reconciledExpansion = undefined;\n };\n const reconcileGroupOverride = (state, groupId, desired) => {\n const group = state.groups?.groups.get(groupId);\n if (group === undefined) {\n state.appliedOverrides = state.appliedOverrides.delete(groupId);\n return;\n }\n if (group.override !== desired) {\n state.groups = setGroupOverride(state.groups, groupId, desired, operation);\n }\n state.appliedOverrides =\n desired === undefined\n ? state.appliedOverrides.delete(groupId)\n : state.appliedOverrides.set(groupId, desired);\n };\n const reconcileOneOverride = (state) => {\n if (state.reconciledExpansion === state.expansion)\n return true;\n let reconciliation = state.overrideReconciliation;\n if (reconciliation === undefined) {\n const remaining = state.appliedOverrides.size + state.expansion.overrides.size;\n reconciliation = {\n phase: \"remove\",\n removalIterator: state.appliedOverrides.entries(),\n desiredIterator: state.expansion.overrides.entries(),\n remaining,\n };\n state.overrideReconciliation = reconciliation;\n totalRows += remaining;\n }\n while (reconciliation.phase === \"remove\") {\n const next = reconciliation.removalIterator.next();\n if (next.done) {\n reconciliation.phase = \"apply\";\n break;\n }\n const [groupId] = next.value;\n reconcileGroupOverride(state, groupId, state.expansion.overrides.get(groupId));\n reconciliation.remaining -= 1;\n completedRows += 1;\n return false;\n }\n const next = reconciliation.desiredIterator.next();\n if (!next.done) {\n const [groupId, expanded] = next.value;\n reconcileGroupOverride(state, groupId, expanded);\n reconciliation.remaining -= 1;\n completedRows += 1;\n return false;\n }\n state.overrideReconciliation = undefined;\n state.reconciledExpansion = state.expansion;\n return true;\n };\n const removeRecord = (record) => {\n const state = retained;\n if (state === undefined)\n return;\n state.rows = state.rows.delete(record.rowId);\n state.recordsBySlot[record.slot] = undefined;\n // Replay only runs after the bulk builder (if any) sealed and published\n // its index, so a grouped candidate always has `groups` here.\n state.groups = updateGroupIndex(state.groups, [record], [], undefined, operation, instrumentation);\n };\n const insertRecord = (source) => {\n const state = retained;\n if (state === undefined)\n return;\n if (instrumentation !== undefined) {\n instrumentation.work.transitionRows += 1;\n instrumentation.work.rowsEvaluated += 1;\n }\n const metadata = state.queryPlan.evaluate({\n rowId: source.rowId,\n row: source.row,\n sourceOrder: source.sourceOrder,\n slot: source.slot,\n });\n const record = Object.freeze({ ...source, metadata });\n if (state.rowBuilder !== undefined)\n state.rowBuilder.set(record.rowId, record);\n else\n state.rows = state.rows.set(record.rowId, record);\n state.recordsBySlot[record.slot] = record;\n if (state.groupBuilder !== undefined) {\n state.groupBuilder.insert(record);\n }\n else {\n state.groups = updateGroupIndex(state.groups, [], [record], undefined, operation, instrumentation);\n }\n };\n const removeReplayRow = (rowId) => {\n const state = retained;\n if (state === undefined)\n return;\n const previous = state.rows.get(rowId);\n if (previous !== undefined)\n removeRecord(previous);\n };\n const insertReplayRow = (target, rowId) => {\n if (retained === undefined)\n return;\n const next = target.rows.get(rowId);\n if (next !== undefined)\n insertRecord(next);\n };\n const candidate = {\n get completedRows() {\n return completedRows;\n },\n get totalRows() {\n return totalRows;\n },\n append(delta) {\n const state = retained;\n if (state === undefined)\n return;\n resetOverrideReconciliation(state);\n state.deltas.push(delta);\n // Capacity is monotone across commits, so the widest replayed target\n // bounds every slot this candidate can ever bind (still a captured\n // root's value — the live allocator is never consulted).\n state.slotCapacity = Math.max(state.slotCapacity, delta.target.slotCapacity);\n totalRows += delta.affectedRowIds.length * 2 + 1;\n },\n step() {\n const state = retained;\n if (state === undefined)\n return true;\n if (state.iterator !== null) {\n const source = state.iterator.next();\n if (!source.done) {\n const previous = state.captured.rows.get(source.value.rowId);\n if (previous !== undefined)\n insertRecord(previous);\n completedRows += 1;\n return false;\n }\n state.iterator = null;\n if (state.groupBuilder !== undefined) {\n // Seal units are ROWS, not cells: the builder charges one unit per\n // (row, group node) — a unit seals that row's measures across all\n // its aggregated columns and both population roots — plus two\n // bookkeeping units per group node (finalize + edge). O(R) total,\n // not R × aggregated columns × 2 roots (#500).\n state.groupSealRemaining =\n state.groupBuilder.pendingFinalizationCount;\n totalRows += state.groupSealRemaining;\n }\n }\n if (state.groupBuilder !== undefined) {\n const builder = state.groupBuilder;\n const complete = builder.sealStep();\n if (state.groupSealRemaining > 0) {\n state.groupSealRemaining -= 1;\n completedRows += 1;\n }\n if (complete) {\n state.groups = builder.finish();\n builder.release();\n state.groupBuilder = undefined;\n state.rows = state.rowBuilder.freeze();\n state.rowBuilder = undefined;\n state.appliedOverrides = state.captured.expansion.overrides;\n state.reconciledExpansion = state.captured.expansion;\n }\n return false;\n }\n while (deltaIndex < state.deltas.length) {\n const delta = state.deltas[deltaIndex];\n if (delta === null) {\n deltaIndex += 1;\n deltaRowIndex = 0;\n deltaRowPhase = \"remove\";\n continue;\n }\n const rowId = delta.affectedRowIds[deltaRowIndex];\n if (rowId !== undefined) {\n if (deltaRowPhase === \"remove\") {\n removeReplayRow(rowId);\n deltaRowPhase = \"insert\";\n }\n else {\n insertReplayRow(delta.target, rowId);\n deltaRowPhase = \"remove\";\n deltaRowIndex += 1;\n }\n completedRows += 1;\n return false;\n }\n state.sourceOrder = delta.target.sourceOrder;\n state.expansion = delta.target.expansion;\n resetOverrideReconciliation(state);\n state.deltas[deltaIndex] = null;\n deltaIndex += 1;\n deltaRowIndex = 0;\n deltaRowPhase = \"remove\";\n completedRows += 1;\n return false;\n }\n return reconcileOneOverride(state);\n },\n finish(revision) {\n const state = retained;\n if (state === undefined)\n throw new Error(\"Released transition candidate.\");\n if (state.groupBuilder !== undefined ||\n state.groups === undefined ||\n state.reconciledExpansion !== state.expansion) {\n throw new Error(\"Transition expansion overrides are not reconciled.\");\n }\n const visible = attachGroupIndex(state.flatRows, state.groups);\n const slotEntries = [];\n for (let slot = 0; slot < state.recordsBySlot.length; slot += 1) {\n const record = state.recordsBySlot[slot];\n if (record !== undefined)\n slotEntries.push([slot, record]);\n }\n return Object.freeze({\n revision,\n parentRevision: revision - 1,\n rows: state.rows,\n sourceOrder: state.sourceOrder,\n recordsBySlot: slotVectorFromEntries(slotEntries, state.slotCapacity),\n slotCapacity: state.slotCapacity,\n // Grouped transitions keep answering visibility from the group\n // index — sentinel. (Flat transitions live in their own module and\n // publish real membership.)\n visibleSlots: EMPTY_MEMBERSHIP,\n visible,\n queryPlan: state.queryPlan,\n expansion: state.expansion,\n cause: Object.freeze({ kind: operation }),\n });\n },\n release() {\n const state = retained;\n if (state === undefined)\n return;\n released = true;\n state.iterator = null;\n state.groupBuilder?.release();\n state.groupBuilder = undefined;\n state.rowBuilder = undefined;\n state.groupSealRemaining = 0;\n state.deltas.fill(null);\n state.deltas.length = 0;\n state.recordsBySlot.length = 0;\n state.overrideReconciliation = undefined;\n state.reconciledExpansion = undefined;\n retained = undefined;\n },\n };\n candidateDiagnostics.set(candidate, () => Object.freeze({\n released,\n hasCapturedRoot: retained !== undefined,\n hasQueryPlan: retained !== undefined,\n hasIterator: retained?.iterator !== null && retained !== undefined,\n deltaCount: retained?.deltas.reduce((count, delta) => count + (delta === null ? 0 : 1), 0) ?? 0,\n hasRows: retained !== undefined,\n hasSourceOrder: retained !== undefined,\n hasExpansion: retained !== undefined,\n hasFlatRows: retained !== undefined,\n hasGroups: retained?.groups !== undefined || retained?.groupBuilder !== undefined,\n deltaSlotCount: retained?.deltas.length ?? 0,\n processedDeltaCount: retained === undefined ? 0 : deltaIndex,\n retainedDeltaRootCount: retained?.deltas.reduce((count, delta) => count + (delta === null ? 0 : 1), 0) ?? 0,\n overrideReconciliationRemaining: retained?.overrideReconciliation?.remaining ?? 0,\n }));\n return candidate;\n}\n","import { isPretableFilterGroup } from \"./column-types\";\nimport { runCooperativeTransitionSlice, } from \"./cooperative-transition\";\nimport { PretableRowModelError, } from \"./errors\";\nimport { rowPassesFilter } from \"./filter-membership\";\nimport { createOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { createPersistentMap, } from \"./persistent/persistent-map\";\nconst DEFAULT_RESULT_LIMIT = 100;\nconst MAX_RESULT_LIMIT = 1_000;\nconst DEFAULT_CACHE_CAPACITY = 8;\nexport class PretableDistinctValueCancelledError extends Error {\n reason;\n name = \"PretableDistinctValueCancelledError\";\n constructor(reason) {\n super(`The distinct-value query was ${reason}.`);\n this.reason = reason;\n }\n}\nconst modelManagers = new WeakMap();\n/** Direct internal test seam; intentionally not exported from the barrel. */\nexport function getDistinctValueDiagnosticsForTesting(model) {\n const manager = modelManagers.get(model);\n if (manager === undefined) {\n throw new TypeError(\"Diagnostics require a local Pretable row model.\");\n }\n return manager.diagnostics();\n}\nconst identityIds = new WeakMap();\nlet nextIdentityId = 1;\nfunction identityId(value) {\n if (value === undefined)\n return 0;\n const existing = identityIds.get(value);\n if (existing !== undefined)\n return existing;\n const id = nextIdentityId++;\n identityIds.set(value, id);\n return id;\n}\nfunction captureQueryOptions(options) {\n if (options !== undefined &&\n (options === null || typeof options !== \"object\")) {\n throw new TypeError(\"Distinct-value options must be an object.\");\n }\n const search = options?.search;\n const start = options?.start ?? 0;\n const limit = options?.limit ?? DEFAULT_RESULT_LIMIT;\n const population = options?.population ?? \"all\";\n const includeBlanks = options?.includeBlanks ?? false;\n const blankOrder = options?.blankOrder ?? \"last\";\n if (search !== undefined && typeof search !== \"string\") {\n throw new TypeError(\"Distinct-value search must be a string.\");\n }\n if (!Number.isSafeInteger(start) || start < 0) {\n throw new RangeError(\"Distinct-value start must be a non-negative safe integer.\");\n }\n if (!Number.isSafeInteger(limit) || limit <= 0 || limit > MAX_RESULT_LIMIT) {\n throw new RangeError(`Distinct-value limit must be a positive safe integer no greater than ${MAX_RESULT_LIMIT}.`);\n }\n if (population !== \"all\" && population !== \"filtered\") {\n throw new TypeError('Distinct-value population must be \"all\" or \"filtered\".');\n }\n if (typeof includeBlanks !== \"boolean\") {\n throw new TypeError(\"Distinct-value includeBlanks must be boolean.\");\n }\n if (blankOrder !== \"first\" && blankOrder !== \"last\") {\n throw new TypeError('Distinct-value blankOrder must be \"first\" or \"last\".');\n }\n return Object.freeze({\n search,\n start,\n limit,\n population,\n includeBlanks,\n blankOrder,\n });\n}\nfunction describeValue(value) {\n if (value === null) {\n return { id: \"null\", blank: true, blankRank: 0 };\n }\n if (value === undefined) {\n return { id: \"undefined\", blank: true, blankRank: 1 };\n }\n if (typeof value === \"string\") {\n return {\n id: `string:${value.length}:${value}`,\n blank: value.trim() === \"\",\n blankRank: 3,\n };\n }\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) {\n return { id: \"number:nan\", blank: true, blankRank: 2 };\n }\n return {\n id: `number:${Object.is(value, -0) ? \"0\" : String(value)}`,\n blank: false,\n blankRank: 0,\n };\n }\n if (typeof value === \"bigint\") {\n return { id: `bigint:${String(value)}`, blank: false, blankRank: 0 };\n }\n if (typeof value === \"boolean\") {\n return { id: `boolean:${value ? \"1\" : \"0\"}`, blank: false, blankRank: 0 };\n }\n throw new TypeError(\"Distinct values must be strings, numbers, bigints, booleans, null, or undefined.\");\n}\nfunction snapshotDistinctValue(value) {\n // Number keys use SameValueZero identity. Canonicalizing their representative\n // prevents insertion and removal history from leaking through as negative zero.\n if (typeof value === \"number\" && value === 0)\n return 0;\n return value;\n}\nconst collator = new Intl.Collator(undefined, {\n numeric: true,\n sensitivity: \"base\",\n});\nfunction defaultCompare(left, right) {\n if (typeof left === \"number\" && typeof right === \"number\") {\n return left === right ? 0 : left < right ? -1 : 1;\n }\n if (typeof left === \"bigint\" && typeof right === \"bigint\") {\n return left === right ? 0 : left < right ? -1 : 1;\n }\n if (typeof left === \"boolean\" && typeof right === \"boolean\") {\n return left === right ? 0 : left ? 1 : -1;\n }\n return collator.compare(String(left), String(right));\n}\nfunction createValueTree(column, options) {\n return createOrderStatisticTree({\n getId: (entry) => entry.id,\n compare: (left, right) => {\n if (left.blank || right.blank) {\n if (left.blank && right.blank) {\n if (left.blankRank !== right.blankRank) {\n return left.blankRank - right.blankRank;\n }\n return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;\n }\n const blankResult = options.blankOrder === \"first\" ? -1 : 1;\n return left.blank ? blankResult : -blankResult;\n }\n const compared = column.compare\n ? column.compare(left.value, right.value)\n : defaultCompare(left.value, right.value);\n if (typeof compared !== \"number\" || Number.isNaN(compared)) {\n throw new TypeError(\"Custom distinct-value comparators must return a number other than NaN.\");\n }\n return compared < 0 ? -1 : compared > 0 ? 1 : 0;\n },\n measure: {\n empty: 0,\n fromEntry: () => 1,\n combine: (left, right) => left + right,\n },\n });\n}\nfunction frame(tag, payload = \"\") {\n return `${tag}${payload.length}:${payload}`;\n}\nfunction semanticValueKey(value) {\n if (Array.isArray(value)) {\n return frame(\"a\", value.map(semanticValueKey).join(\"\"));\n }\n if (value && typeof value === \"object\") {\n const keys = Object.keys(value).sort();\n return frame(\"o\", keys\n .map((key) => frame(\"k\", key) +\n frame(\"v\", semanticValueKey(value[key])))\n .join(\"\"));\n }\n if (value === null)\n return frame(\"l\");\n if (value === undefined)\n return frame(\"u\");\n if (typeof value === \"string\")\n return frame(\"s\", value);\n if (typeof value === \"number\") {\n if (Number.isNaN(value))\n return frame(\"nN\");\n if (Object.is(value, -0))\n return frame(\"nZ\");\n return frame(\"n\", String(value));\n }\n if (typeof value === \"bigint\")\n return frame(\"i\", String(value));\n if (typeof value === \"boolean\")\n return frame(value ? \"t\" : \"f\");\n return frame(typeof value, String(value));\n}\nfunction filterSemanticKey(root) {\n const derivations = root.queryPlan\n .derivations;\n const byId = new Map(derivations.map((column) => [column.id, column]));\n const nodeKey = (node) => {\n if (isPretableFilterGroup(node)) {\n const group = node;\n /*\n * Children are keyed then sorted for the same reason the roots are:\n * and/or are commutative, so reordering a group is not a new question.\n *\n * Belt and braces today — deleting the sort breaks no test, because a\n * reordered group is matched structurally by `filterNodesEqual` and so\n * reuses its plan, and this cache never sees a root whose tree differs\n * only in child order. It stops being redundant the moment plan reuse\n * stops absorbing that case.\n */\n return frame(\"g\", frame(\"p\", group.op) +\n frame(\"k\", group.children.map(nodeKey).sort().join(\"\")));\n }\n const runtime = node;\n return frame(\"f\", frame(\"c\", runtime.columnId) +\n frame(\"t\", byId.get(runtime.columnId)?.type ?? \"\") +\n frame(\"i\", String(identityId(byId.get(runtime.columnId)?.accessor))) +\n frame(\"p\", runtime.operator) +\n frame(\"v\", semanticValueKey(runtime.value)));\n };\n return [...root.queryPlan.query.filters].map(nodeKey).sort().join(\"\");\n}\nfunction columnForDerivations(derivations, columnId) {\n const column = derivations.find((candidate) => candidate.id === columnId);\n if (column === undefined) {\n throw new PretableRowModelError(\"derivation-failed\", `Unknown distinct-value column ${columnId}.`, { operation: \"distinct-values\", columnId });\n }\n return column;\n}\nfunction cacheKey(root, column, options) {\n const filterKey = options.population === \"filtered\" ? filterSemanticKey(root) : \"\";\n return frame(\"K\", frame(\"c\", column.id) +\n frame(\"t\", column.type) +\n frame(\"p\", options.population) +\n frame(\"a\", String(identityId(column.accessor))) +\n frame(\"o\", String(identityId(column.compare))) +\n frame(options.includeBlanks ? \"b1\" : \"b0\") +\n frame(\"n\", options.blankOrder) +\n frame(\"f\", filterKey));\n}\nfunction callbackError(code, operation, columnId, rowId, cause) {\n return new PretableRowModelError(code, `Distinct-value ${code === \"accessor-failed\" ? \"accessor\" : \"comparator\"} failed for column ${columnId}.`, { operation, columnId, rowId, cause });\n}\nfunction readValue(record, column, options, operation, \n/** The row's verdict under the root being replayed; see the caller. */\nfilterPasses) {\n if (options.population === \"filtered\" && !filterPasses) {\n return undefined;\n }\n let value;\n try {\n value = column.accessor(record.row);\n }\n catch (cause) {\n throw callbackError(\"accessor-failed\", operation, column.id, record.rowId, cause);\n }\n let description;\n try {\n description = describeValue(value);\n }\n catch (cause) {\n throw callbackError(\"accessor-failed\", operation, column.id, record.rowId, cause);\n }\n if (description.blank && !options.includeBlanks)\n return undefined;\n return { description, value };\n}\nfunction removeValue(state, rowId) {\n const valueId = state.rowValues.get(rowId);\n if (valueId === undefined && !state.rowValues.has(rowId))\n return state;\n const previous = state.values.get(valueId);\n if (previous === undefined) {\n return { values: state.values, rowValues: state.rowValues.delete(rowId) };\n }\n const values = previous.count === 1\n ? state.values.remove(previous.id)\n : state.values.insertOrReplace(Object.freeze({ ...previous, count: previous.count - 1 }));\n return { values, rowValues: state.rowValues.delete(rowId) };\n}\nfunction insertValue(state, rowId, selected) {\n const previous = state.values.get(selected.description.id);\n const entry = Object.freeze({\n id: selected.description.id,\n value: previous?.value ?? snapshotDistinctValue(selected.value),\n count: (previous?.count ?? 0) + 1,\n blank: selected.description.blank,\n blankRank: selected.description.blankRank,\n });\n return {\n values: state.values.insertOrReplace(entry),\n rowValues: state.rowValues.set(rowId, entry.id),\n };\n}\nfunction replayRecord(state, target, rowId, column, options, operation) {\n let next;\n try {\n next = removeValue(state, rowId);\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw callbackError(\"comparator-failed\", operation, column.id, rowId, cause);\n }\n const record = target.rows.get(rowId);\n if (record === undefined)\n return next;\n // The \"filtered\" population is exactly the target root's visible\n // membership, so the root the replay already holds answers it — no stored\n // per-row verdict, and no accessor re-run for the \"all\" population.\n const selected = readValue(record, column, options, operation, options.population === \"filtered\" ? rowPassesFilter(target, rowId) : true);\n if (selected === undefined)\n return next;\n try {\n next = insertValue(next, rowId, selected);\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n throw callbackError(\"comparator-failed\", operation, column.id, rowId, cause);\n }\n return next;\n}\nfunction createDictionaryCandidate(input) {\n const column = input.column;\n const queryOptions = input.options;\n let retained = {\n captured: input.captured,\n iterator: input.captured.sourceOrder.entries(),\n state: {\n values: createValueTree(column, queryOptions),\n rowValues: createPersistentMap(),\n },\n deltas: [],\n };\n // Candidate methods retain only the nullable state and immutable callback\n // configuration. Clear the input container so release truly drops the\n // captured row root rather than keeping it through the parameter closure.\n input = undefined;\n let deltaIndex = 0;\n let deltaRowIndex = 0;\n let processedRows = 0;\n let released = false;\n return {\n get processedRows() {\n return processedRows;\n },\n get deltaCount() {\n return (retained?.deltas.reduce((count, delta) => count + (delta === null ? 0 : 1), 0) ?? 0);\n },\n get released() {\n return released;\n },\n append(delta) {\n retained?.deltas.push(delta);\n },\n step() {\n const state = retained;\n if (state === undefined)\n return true;\n if (state.iterator !== null) {\n const next = state.iterator.next();\n if (!next.done) {\n state.state = replayRecord(state.state, state.captured, next.value.rowId, column, queryOptions, \"distinct-values\");\n processedRows += 1;\n return false;\n }\n state.iterator = null;\n }\n if (deltaIndex < state.deltas.length) {\n const delta = state.deltas[deltaIndex];\n if (delta === null) {\n deltaIndex += 1;\n deltaRowIndex = 0;\n return false;\n }\n const rowId = delta.affectedRowIds[deltaRowIndex];\n if (rowId !== undefined) {\n state.state = replayRecord(state.state, delta.target, rowId, column, queryOptions, \"distinct-values\");\n deltaRowIndex += 1;\n processedRows += 1;\n return false;\n }\n state.deltas[deltaIndex] = null;\n deltaIndex += 1;\n deltaRowIndex = 0;\n return false;\n }\n return true;\n },\n finish() {\n if (retained === undefined)\n throw new Error(\"Released dictionary candidate.\");\n return retained.state;\n },\n release() {\n if (retained === undefined)\n return;\n retained.iterator = null;\n retained.deltas.fill(null);\n retained.deltas.length = 0;\n retained = undefined;\n released = true;\n },\n };\n}\nfunction projectIndexedResult(state, options, revision) {\n const end = Math.min(state.values.size, options.start + options.limit);\n const values = state.values.range(options.start, end).map((entry) => Object.freeze({\n value: snapshotDistinctValue(entry.value),\n count: entry.count,\n }));\n return Object.freeze({\n values: Object.freeze(values),\n totalDistinct: state.values.size,\n population: options.population,\n rowModelRevision: revision,\n });\n}\nexport function createDistinctValueManager(options) {\n const capacity = options.cacheCapacity ?? DEFAULT_CACHE_CAPACITY;\n if (!Number.isSafeInteger(capacity) || capacity <= 0) {\n throw new RangeError(\"The distinct-value cache capacity must be a positive safe integer.\");\n }\n const cache = new Map();\n let clock = 0;\n let disposed = false;\n let rowsEvaluated = 0;\n let releasedCandidateCount = 0;\n let projectionEntriesExamined = 0;\n const projectionRuntime = Object.freeze({\n ...options.runtime,\n maxUnitsPerSlice: Math.min(options.runtime.maxUnitsPerSlice, 256),\n });\n const activeProjections = new Set();\n const bestEffortCancel = (cancel) => {\n try {\n cancel?.();\n }\n catch {\n // Scheduler hooks are advisory and never own dictionary/projection state.\n }\n };\n const releaseProjection = (projection) => {\n const cancelScheduled = projection.cancelScheduled;\n projection.cancelScheduled = undefined;\n bestEffortCancel(cancelScheduled);\n projection.iterator = undefined;\n projection.tree = undefined;\n projection.values.length = 0;\n projection.waiter.cancelActive = undefined;\n activeProjections.delete(projection);\n };\n const finishProjection = (projection) => {\n const waiter = projection.waiter;\n const values = Object.freeze([...projection.values]);\n const result = Object.freeze({\n values,\n totalDistinct: projection.matchingCount,\n population: waiter.options.population,\n rowModelRevision: projection.revision,\n });\n releaseProjection(projection);\n waiter.status = \"ready\";\n waiter.resolve(result);\n };\n const failProjection = (projection, error) => {\n const waiter = projection.waiter;\n releaseProjection(projection);\n waiter.status = \"error\";\n waiter.reject(error);\n };\n const runProjectionSlice = (projection) => {\n if (disposed || !activeProjections.has(projection))\n return;\n try {\n const complete = runCooperativeTransitionSlice(projectionRuntime, () => {\n const next = projection.iterator?.next();\n if (next === undefined || next.done)\n return true;\n projectionEntriesExamined += 1;\n if (String(next.value.value)\n .toLocaleLowerCase()\n .includes(projection.search)) {\n if (projection.matchingCount >= projection.waiter.options.start &&\n projection.values.length < projection.waiter.options.limit) {\n projection.values.push(Object.freeze({\n value: snapshotDistinctValue(next.value.value),\n count: next.value.count,\n }));\n }\n projection.matchingCount += 1;\n }\n return false;\n });\n if (disposed || !activeProjections.has(projection))\n return;\n if (complete) {\n finishProjection(projection);\n return;\n }\n projection.cancelScheduled = options.runtime.scheduler.schedule(() => {\n projection.cancelScheduled = undefined;\n runProjectionSlice(projection);\n });\n }\n catch (error) {\n failProjection(projection, error);\n }\n };\n const startProjection = (state, waiter, revision) => {\n const projection = {\n tree: state.values,\n iterator: state.values.entries(),\n waiter,\n revision,\n search: waiter.options.search.toLocaleLowerCase(),\n values: [],\n matchingCount: 0,\n cancelScheduled: undefined,\n };\n const opaque = projection;\n activeProjections.add(opaque);\n waiter.cancelActive = () => releaseProjection(opaque);\n try {\n projection.cancelScheduled = options.runtime.scheduler.schedule(() => {\n projection.cancelScheduled = undefined;\n runProjectionSlice(opaque);\n });\n }\n catch (error) {\n failProjection(opaque, error);\n }\n };\n const releaseBuilding = (entry) => {\n const cancelScheduled = entry.cancelScheduled;\n entry.cancelScheduled = undefined;\n bestEffortCancel(cancelScheduled);\n if (!entry.candidate.released) {\n rowsEvaluated += entry.candidate.processedRows;\n entry.candidate.release();\n releasedCandidateCount += 1;\n }\n };\n const cancelBuilding = (entry, reason) => {\n releaseBuilding(entry);\n for (const waiter of entry.waiters) {\n waiter.cancelActive = undefined;\n waiter.status = \"cancelled\";\n waiter.reject(new PretableDistinctValueCancelledError(reason));\n }\n entry.waiters.clear();\n cache.delete(entry.key);\n };\n const evictEntry = (entry) => {\n if (entry.kind === \"building\") {\n cancelBuilding(entry, \"evicted\");\n return;\n }\n entry.state = undefined;\n cache.delete(entry.key);\n };\n const makeRoomForEntry = () => {\n while (cache.size >= capacity) {\n const oldest = [...cache.values()].sort((left, right) => left.lastUsed - right.lastUsed)[0];\n if (oldest === undefined)\n return;\n evictEntry(oldest);\n }\n };\n const evictReady = () => {\n const ready = [...cache.values()].filter((entry) => entry.kind === \"ready\" && entry.state !== undefined);\n while (ready.length > capacity) {\n ready.sort((left, right) => left.lastUsed - right.lastUsed);\n const evicted = ready.shift();\n evicted.state = undefined;\n cache.delete(evicted.key);\n }\n };\n const resolveReady = (entry) => {\n const dictionary = entry.candidate.finish();\n rowsEvaluated += entry.candidate.processedRows;\n entry.candidate.release();\n releasedCandidateCount += 1;\n const ready = {\n kind: \"ready\",\n key: entry.key,\n column: entry.column,\n options: entry.options,\n state: dictionary,\n lastUsed: ++clock,\n };\n cache.set(entry.key, ready);\n for (const waiter of entry.waiters) {\n if (waiter.status !== \"pending\")\n continue;\n try {\n const revision = options.getRoot().revision;\n if ((waiter.options.search?.length ?? 0) === 0) {\n const result = projectIndexedResult(dictionary, waiter.options, revision);\n waiter.cancelActive = undefined;\n waiter.status = \"ready\";\n waiter.resolve(result);\n }\n else {\n startProjection(dictionary, waiter, revision);\n }\n }\n catch (error) {\n waiter.cancelActive = undefined;\n waiter.status = \"error\";\n waiter.reject(error);\n }\n }\n entry.waiters.clear();\n evictReady();\n };\n const failBuilding = (entry, error) => {\n releaseBuilding(entry);\n cache.delete(entry.key);\n for (const waiter of entry.waiters) {\n waiter.cancelActive = undefined;\n waiter.status = \"error\";\n waiter.reject(error);\n }\n entry.waiters.clear();\n };\n const runBuildSlice = (entry) => {\n if (disposed || cache.get(entry.key) !== entry)\n return;\n try {\n const complete = runCooperativeTransitionSlice(options.runtime, () => entry.candidate.step());\n if (disposed || cache.get(entry.key) !== entry)\n return;\n if (complete) {\n resolveReady(entry);\n return;\n }\n entry.cancelScheduled = options.runtime.scheduler.schedule(() => {\n entry.cancelScheduled = undefined;\n runBuildSlice(entry);\n });\n }\n catch (error) {\n failBuilding(entry, error);\n }\n };\n const manager = {\n query(columnId, rawOptions) {\n const captured = captureQueryOptions(rawOptions);\n const root = options.getRoot();\n const column = columnForDerivations(options.getDerivations(), columnId);\n const key = cacheKey(root, column, captured);\n const existing = cache.get(key);\n if (existing?.kind === \"ready\" &&\n existing.state !== undefined &&\n (captured.search?.length ?? 0) === 0) {\n existing.lastUsed = ++clock;\n let status = \"ready\";\n const finished = Promise.resolve(projectIndexedResult(existing.state, captured, root.revision));\n return Object.freeze({\n get status() {\n return status;\n },\n finished,\n cancel() {\n status = \"ready\";\n },\n });\n }\n let resolve;\n let reject;\n const finished = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n void finished.catch(() => undefined);\n const waiter = {\n status: \"pending\",\n options: captured,\n resolve,\n reject,\n cancelActive: undefined,\n };\n const query = Object.freeze({\n get status() {\n return waiter.status;\n },\n finished,\n cancel() {\n if (waiter.status !== \"pending\")\n return;\n waiter.status = \"cancelled\";\n const cancelActive = waiter.cancelActive;\n waiter.cancelActive = undefined;\n cancelActive?.();\n waiter.reject(new PretableDistinctValueCancelledError(\"cancelled\"));\n },\n });\n if (existing?.kind === \"ready\" && existing.state !== undefined) {\n existing.lastUsed = ++clock;\n startProjection(existing.state, waiter, root.revision);\n return query;\n }\n let entry;\n if (existing?.kind === \"building\") {\n entry = existing;\n entry.lastUsed = ++clock;\n }\n else {\n makeRoomForEntry();\n entry = {\n kind: \"building\",\n key,\n column,\n options: captured,\n candidate: createDictionaryCandidate({\n captured: root,\n column,\n options: captured,\n }),\n waiters: new Set(),\n lastUsed: ++clock,\n cancelScheduled: undefined,\n };\n cache.set(key, entry);\n }\n entry.waiters.add(waiter);\n waiter.cancelActive = () => {\n if (entry.waiters.delete(waiter)) {\n if (entry.waiters.size === 0 && cache.get(entry.key) === entry) {\n releaseBuilding(entry);\n cache.delete(entry.key);\n }\n }\n };\n if (existing?.kind !== \"building\")\n runBuildSlice(entry);\n return query;\n },\n prepareCommit(target, affectedRowIds, operation) {\n const updates = [];\n for (const entry of cache.values()) {\n if (entry.kind !== \"ready\" || entry.state === undefined)\n continue;\n let state = entry.state;\n for (const rowId of affectedRowIds) {\n state = replayRecord(state, target, rowId, entry.column, entry.options, operation);\n }\n updates.push({\n entry: entry,\n state,\n });\n }\n return Object.freeze({ updates: Object.freeze(updates) });\n },\n publishCommit(prepared, target, affectedRowIds) {\n for (const update of prepared.updates)\n update.entry.state = update.state;\n const delta = Object.freeze({\n target,\n affectedRowIds: Object.freeze([...affectedRowIds]),\n });\n for (const entry of cache.values()) {\n if (entry.kind === \"building\")\n entry.candidate.append(delta);\n }\n },\n publishTransitionRoot(target) {\n for (const entry of [...cache.values()]) {\n const currentColumn = columnForDerivations(options.getDerivations(), entry.column.id);\n if (cacheKey(target, currentColumn, entry.options) === entry.key) {\n continue;\n }\n if (entry.kind === \"building\")\n cancelBuilding(entry, \"superseded\");\n else {\n entry.state = undefined;\n cache.delete(entry.key);\n }\n }\n },\n dispose(error) {\n if (disposed)\n return;\n disposed = true;\n for (const entry of cache.values()) {\n if (entry.kind === \"building\") {\n releaseBuilding(entry);\n for (const waiter of entry.waiters) {\n waiter.cancelActive = undefined;\n waiter.status = \"cancelled\";\n waiter.reject(error);\n }\n entry.waiters.clear();\n }\n else\n entry.state = undefined;\n }\n cache.clear();\n for (const projection of [...activeProjections]) {\n const waiter = projection.waiter;\n releaseProjection(projection);\n waiter.status = \"cancelled\";\n waiter.reject(error);\n }\n },\n attachModel(model) {\n modelManagers.set(model, {\n diagnostics: () => {\n let retainedDictionaryCount = 0;\n let buildingDictionaryCount = 0;\n let retainedRowValueCount = 0;\n let retainedDistinctValueCount = 0;\n let candidateDeltaCount = 0;\n let capturedRootCount = 0;\n for (const entry of cache.values()) {\n if (entry.kind === \"ready\" && entry.state !== undefined) {\n retainedDictionaryCount += 1;\n retainedRowValueCount += entry.state.rowValues.size;\n retainedDistinctValueCount += entry.state.values.size;\n }\n else if (entry.kind === \"building\") {\n buildingDictionaryCount += 1;\n candidateDeltaCount += entry.candidate.deltaCount;\n capturedRootCount += entry.candidate.released ? 0 : 1;\n }\n }\n return Object.freeze({\n cacheEntryCount: cache.size,\n retainedDictionaryCount,\n buildingDictionaryCount,\n retainedRowValueCount,\n retainedDistinctValueCount,\n candidateDeltaCount,\n rowsEvaluated: rowsEvaluated +\n [...cache.values()].reduce((count, entry) => count +\n (entry.kind === \"building\"\n ? entry.candidate.processedRows\n : 0), 0),\n releasedCandidateCount,\n capturedRootCount,\n activeProjectionCount: activeProjections.size,\n projectionEntriesExamined,\n projectionIteratorCount: [...activeProjections].filter((projection) => projection.iterator !== undefined).length,\n projectionScheduledCount: [...activeProjections].filter((projection) => projection.cancelScheduled !== undefined).length,\n disposed,\n });\n },\n });\n },\n };\n return manager;\n}\n","export const DEFAULT_CHANGE_JOURNAL_CAPACITY = 128;\nconst operationDiagnostics = new WeakMap();\nconst journalDiagnostics = new WeakMap();\nexport function attachChangeOperationDiagnosticsForTesting(operations, diagnostics) {\n operationDiagnostics.set(operations, Object.freeze({ ...diagnostics }));\n return operations;\n}\nexport function getChangeOperationDiagnosticsForTesting(operations) {\n const diagnostics = operationDiagnostics.get(operations);\n if (diagnostics === undefined) {\n throw new TypeError(\"Diagnostics require generated transaction operations.\");\n }\n return diagnostics;\n}\nexport function getChangeJournalDiagnosticsForTesting(journal) {\n const diagnostics = journalDiagnostics.get(journal);\n if (diagnostics === undefined) {\n throw new TypeError(\"Diagnostics require a Pretable change journal.\");\n }\n return diagnostics;\n}\nfunction previousRevisionOf(entry) {\n return entry.kind === \"changes\"\n ? entry.changeSet.previousRevision\n : entry.previousRevision;\n}\nfunction freezeRef(ref) {\n return ref.kind === \"data\"\n ? Object.freeze({ kind: \"data\", rowId: ref.rowId })\n : Object.freeze({ kind: \"group\", groupId: ref.groupId });\n}\nfunction freezeOperation(operation) {\n switch (operation.kind) {\n case \"insert\":\n return Object.freeze({\n kind: \"insert\",\n ref: freezeRef(operation.ref),\n index: operation.index,\n });\n case \"remove\":\n return Object.freeze({\n kind: \"remove\",\n ref: freezeRef(operation.ref),\n previousIndex: operation.previousIndex,\n });\n case \"move\":\n return Object.freeze({\n kind: \"move\",\n ref: freezeRef(operation.ref),\n previousIndex: operation.previousIndex,\n index: operation.index,\n });\n case \"update\":\n return Object.freeze({\n kind: \"update\",\n ref: freezeRef(operation.ref),\n index: operation.index,\n fields: Object.freeze(Array.from(operation.fields)),\n });\n }\n}\nfunction changes(fromRevision, toRevision, changeSets) {\n return Object.freeze({\n kind: \"changes\",\n fromRevision,\n toRevision,\n changes: Object.freeze(Array.from(changeSets)),\n });\n}\nfunction reset(toRevision, reason) {\n return Object.freeze({ kind: \"reset\", toRevision, reason });\n}\n/**\n * A root-independent bounded journal. Entries contain only public row refs and\n * frozen scalar metadata, so retaining or evicting them cannot retain or\n * invalidate persistent revision roots.\n */\nexport function createChangeJournal(capacity = DEFAULT_CHANGE_JOURNAL_CAPACITY) {\n if (!Number.isSafeInteger(capacity) || capacity < 0) {\n throw new RangeError(\"Change journal capacity must be a non-negative integer.\");\n }\n let entries = Object.freeze([]);\n let latestRevision = 0;\n function publishDiagnostics() {\n journalDiagnostics.set(journal, Object.freeze({\n capacity,\n entryCount: entries.length,\n latestRevision,\n }));\n }\n const assertContiguous = (previousRevision, revision) => {\n if (!Number.isSafeInteger(previousRevision) ||\n !Number.isSafeInteger(revision) ||\n previousRevision < 0 ||\n revision !== previousRevision + 1 ||\n previousRevision !== latestRevision) {\n throw new RangeError(\"Change journal entries must be safe, non-negative, and contiguous.\");\n }\n };\n const retain = (entry) => {\n if (capacity === 0) {\n entries = Object.freeze([]);\n return;\n }\n const next = [...entries, entry];\n entries = Object.freeze(next.slice(Math.max(0, next.length - capacity)));\n };\n const journal = {\n capacity,\n appendChanges(previousRevision, revision, operations) {\n assertContiguous(previousRevision, revision);\n const diagnostics = operationDiagnostics.get(operations);\n const frozenOperations = Object.freeze(Array.from(operations, (operation) => freezeOperation(operation)));\n if (diagnostics !== undefined) {\n operationDiagnostics.set(frozenOperations, diagnostics);\n }\n const changeSet = Object.freeze({\n previousRevision,\n revision,\n operations: frozenOperations,\n });\n retain(Object.freeze({ kind: \"changes\", changeSet }));\n latestRevision = revision;\n publishDiagnostics();\n },\n appendBarrier(previousRevision, revision, reason = \"bulk-replace\") {\n assertContiguous(previousRevision, revision);\n retain(Object.freeze({\n kind: \"barrier\",\n previousRevision,\n revision,\n reason,\n }));\n latestRevision = revision;\n publishDiagnostics();\n },\n clear() {\n entries = Object.freeze([]);\n publishDiagnostics();\n },\n changesSince(fromRevision, currentRevision) {\n if (currentRevision !== latestRevision) {\n throw new RangeError(\"The supplied current revision does not match the journal.\");\n }\n if (!Number.isSafeInteger(fromRevision) ||\n fromRevision < 0 ||\n fromRevision > currentRevision) {\n return reset(currentRevision, \"unknown-revision\");\n }\n if (fromRevision === currentRevision) {\n return changes(fromRevision, currentRevision, []);\n }\n const first = entries[0];\n if (first === undefined || fromRevision < previousRevisionOf(first)) {\n return reset(currentRevision, \"journal-evicted\");\n }\n const start = entries.findIndex((entry) => previousRevisionOf(entry) === fromRevision);\n if (start < 0)\n return reset(currentRevision, \"unknown-revision\");\n const retained = entries.slice(start);\n // \"reorder\" (order moved, nothing else) and \"refilter\" (membership\n // changed, surviving order and identities intact) are PROMISES, so a\n // promised reason only survives aggregation when every entry in the\n // range is a barrier with that SAME reason. Any other entry — changes,\n // a plain barrier, or the OTHER promise (order + membership both\n // changed delivers neither) — voids it and the whole range degrades\n // to a plain bulk reset.\n const firstReason = retained[0]?.kind === \"barrier\" ? retained[0].reason : undefined;\n if (firstReason === \"reorder\" || firstReason === \"refilter\") {\n let allPromised = true;\n let promisedExpected = fromRevision;\n for (const entry of retained) {\n if (entry.kind !== \"barrier\" ||\n entry.reason !== firstReason ||\n entry.previousRevision !== promisedExpected) {\n allPromised = false;\n break;\n }\n promisedExpected = entry.revision;\n }\n if (allPromised && promisedExpected === currentRevision) {\n return reset(currentRevision, firstReason);\n }\n }\n let expected = fromRevision;\n const changeSets = [];\n for (const entry of retained) {\n if (previousRevisionOf(entry) !== expected) {\n return reset(currentRevision, \"unknown-revision\");\n }\n if (entry.kind === \"barrier\") {\n return reset(currentRevision, entry.reason === \"reorder\" || entry.reason === \"refilter\"\n ? \"bulk-replace\"\n : entry.reason);\n }\n changeSets.push(entry.changeSet);\n expected = entry.changeSet.revision;\n }\n if (expected !== currentRevision) {\n return reset(currentRevision, \"journal-evicted\");\n }\n return changes(fromRevision, currentRevision, changeSets);\n },\n };\n const frozen = Object.freeze(journal);\n publishDiagnostics();\n return frozen;\n}\n","import { PretableRowModelError } from \"./errors\";\nconst DEVELOPMENT = process.env.NODE_ENV !== \"production\";\nfunction failIntegrity(operation, cause) {\n throw new PretableRowModelError(\"derivation-failed\", \"A row could not be inspected safely before publication.\", { operation, cause });\n}\nfunction fingerprint(row, earlierFailure) {\n try {\n const entries = Reflect.ownKeys(row).map((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(row, key);\n if (descriptor === undefined) {\n throw new TypeError(\"An own row key disappeared during inspection.\");\n }\n if (\"value\" in descriptor) {\n return Object.freeze({\n kind: \"data\",\n key,\n value: descriptor.value,\n enumerable: descriptor.enumerable ?? false,\n configurable: descriptor.configurable ?? false,\n writable: descriptor.writable ?? false,\n });\n }\n return Object.freeze({\n kind: \"accessor\",\n key,\n get: descriptor.get,\n set: descriptor.set,\n enumerable: descriptor.enumerable ?? false,\n configurable: descriptor.configurable ?? false,\n });\n });\n return Object.freeze({ entries: Object.freeze(entries) });\n }\n catch (fingerprintFailure) {\n return failIntegrity(\"set-rows\", earlierFailure === undefined\n ? fingerprintFailure\n : Object.freeze({ earlierFailure, fingerprintFailure }));\n }\n}\nfunction fingerprintsEqual(left, right) {\n if (left === undefined || left.entries.length !== right.entries.length)\n return false;\n return left.entries.every((entry, index) => {\n const other = right.entries[index];\n if (other === undefined ||\n entry.kind !== other.kind ||\n entry.key !== other.key ||\n entry.enumerable !== other.enumerable ||\n entry.configurable !== other.configurable) {\n return false;\n }\n if (entry.kind === \"data\" && other.kind === \"data\") {\n return (entry.writable === other.writable && Object.is(entry.value, other.value));\n }\n return (entry.kind === \"accessor\" &&\n other.kind === \"accessor\" &&\n entry.get === other.get &&\n entry.set === other.set);\n });\n}\n/**\n * Applies the development-only immutable-row guard. Production takes a\n * constant-time path with no reflection, freezing, fingerprinting, or output.\n */\nexport function inspectRowIntegrity(row, rowId, previous, sameReference) {\n if (!DEVELOPMENT) {\n return {\n integrity: { kind: \"unchecked\" },\n sameReferenceMutation: false,\n };\n }\n let extensible;\n try {\n extensible = Object.isExtensible(row);\n }\n catch (cause) {\n const current = fingerprint(row, cause);\n return fingerprintInspection(current, rowId, previous, sameReference);\n }\n if (extensible) {\n try {\n Object.freeze(row);\n if (Object.isFrozen(row)) {\n return {\n integrity: { kind: \"frozen\" },\n sameReferenceMutation: false,\n };\n }\n const current = fingerprint(row);\n return fingerprintInspection(current, rowId, previous, sameReference);\n }\n catch (cause) {\n const current = fingerprint(row, cause);\n return fingerprintInspection(current, rowId, previous, sameReference);\n }\n }\n try {\n if (Object.isFrozen(row)) {\n return {\n integrity: { kind: \"frozen\" },\n sameReferenceMutation: false,\n };\n }\n }\n catch (cause) {\n const current = fingerprint(row, cause);\n return fingerprintInspection(current, rowId, previous, sameReference);\n }\n const current = fingerprint(row);\n return fingerprintInspection(current, rowId, previous, sameReference);\n}\nfunction fingerprintInspection(current, rowId, previous, sameReference) {\n const sameReferenceMutation = sameReference &&\n previous?.kind === \"fingerprinted\" &&\n !fingerprintsEqual(previous.fingerprint, current);\n return {\n integrity: { kind: \"fingerprinted\", fingerprint: current },\n sameReferenceMutation,\n diagnostic: sameReferenceMutation\n ? Object.freeze({\n code: \"same-reference-row-mutation\",\n rowId,\n message: \"A row object changed without changing identity; it was reevaluated. Previously captured snapshots may observe that caller-owned mutation through the shared row reference.\",\n })\n : undefined,\n };\n}\n","import { PretableRowModelError } from \"./errors\";\nimport { createOrderStatisticTree, instrumentOrderStatisticTree, } from \"./persistent/order-statistic-tree\";\nimport { createPersistentMap, instrumentPersistentMap, } from \"./persistent/persistent-map\";\nimport { inspectRowIntegrity, } from \"./row-integrity\";\nimport { slotVectorFromEntries } from \"./slot-vector\";\nexport function createSourceOrderTree(instrumentation) {\n return instrumentOrderStatisticTree(createOrderStatisticTree({\n getId: (entry) => entry.rowId,\n compare: (left, right) => left.sourceOrder - right.sourceOrder,\n measure: {\n empty: 0,\n fromEntry: () => 1,\n combine: (left, right) => left + right,\n },\n }), instrumentation);\n}\nfunction captureRows(rows) {\n try {\n return Array.from(rows);\n }\n catch (cause) {\n throw new PretableRowModelError(\"derivation-failed\", \"The rows input could not be read safely.\", { operation: \"set-rows\", cause });\n }\n}\nfunction captureRowId(row, getRowId) {\n try {\n const rowId = getRowId(row);\n if (typeof rowId !== \"string\" && typeof rowId !== \"number\") {\n throw new TypeError(\"Row IDs must be strings or numbers.\");\n }\n return rowId;\n }\n catch (cause) {\n throw new PretableRowModelError(\"derivation-failed\", \"The row ID accessor failed.\", { operation: \"set-rows\", cause });\n }\n}\n/** Builds the canonical persistent store after validating every ID first. */\nexport function buildRowStore(input) {\n const captured = captureRows(input.rows);\n const ids = [];\n const seen = new Set();\n for (const row of captured) {\n const rowId = captureRowId(row, input.getRowId);\n if (seen.has(rowId)) {\n throw new PretableRowModelError(\"duplicate-row-id\", `Duplicate row ID ${String(rowId)}.`, { operation: \"set-rows\", rowId });\n }\n seen.add(rowId);\n ids.push(rowId);\n }\n const inspections = captured.map((row, index) => {\n const rowId = ids[index];\n const previous = input.previous?.get(rowId);\n return inspectRowIntegrity(row, rowId, previous?.integrity, previous !== undefined && Object.is(previous.row, row));\n });\n const sameReferenceMutation = inspections.some((inspection) => inspection.sameReferenceMutation);\n const mapDraft = instrumentPersistentMap(createPersistentMap(), input.instrumentation).asTransient();\n const sourceDraft = createSourceOrderTree(input.instrumentation).asTransient();\n const records = [];\n for (let sourceOrder = 0; sourceOrder < captured.length; sourceOrder += 1) {\n const row = captured[sourceOrder];\n const rowId = ids[sourceOrder];\n const previous = input.previous?.get(rowId);\n if (input.instrumentation !== undefined)\n input.instrumentation.work.rowsEvaluated += 1;\n // `evaluate` needs a slot up front (it's part of `CompiledRowInput` now,\n // unread this task), but the REAL slot for a brand-new row is still\n // resolved after evaluation succeeds, exactly as before this field\n // existed: `input.slots.allocate()` is a real allocator mutation that\n // bumps the high-water mark permanently (capacity never shrinks — see\n // `slot-allocator.ts`), and drawing it before a throwing accessor runs\n // would leak capacity a release can't undo. A carried row's slot has no\n // such hazard (no allocator call), so it is used directly. `-1` is a\n // placeholder for the fresh-slot case only: harmless because nothing\n // reads `CompiledRowInput.slot` yet.\n const metadata = input.queryPlan.evaluate({\n rowId,\n row: row,\n sourceOrder,\n slot: previous !== undefined ? previous.slot : -1,\n });\n const slot = previous !== undefined ? previous.slot : input.slots.allocate();\n const publicRow = previous !== undefined &&\n Object.is(previous.row, row) &&\n previous.sourceOrder === sourceOrder &&\n !inspections[sourceOrder].sameReferenceMutation\n ? previous.publicRow\n : Object.freeze({\n kind: \"data\",\n rowId,\n row,\n sourceIndex: sourceOrder,\n depth: 0,\n });\n const record = Object.freeze({\n rowId,\n row,\n sourceOrder,\n slot,\n metadata,\n publicRow,\n integrity: inspections[sourceOrder].integrity,\n });\n mapDraft.set(rowId, record);\n sourceDraft.insertOrReplace(Object.freeze({ rowId, sourceOrder }));\n records.push(record);\n }\n if (input.previous !== undefined) {\n for (const [rowId, record] of input.previous.entries()) {\n if (!seen.has(rowId))\n input.slots.release(record.slot);\n }\n }\n return {\n rows: mapDraft.freeze(),\n sourceOrder: sourceDraft.freeze(),\n records: Object.freeze(records),\n recordsBySlot: slotVectorFromEntries(records.map((record) => [record.slot, record]), input.slots.capacity),\n sameReferenceMutation,\n sameReferenceMutationCount: inspections.filter((inspection) => inspection.sameReferenceMutation).length,\n diagnostics: Object.freeze(inspections.flatMap((inspection) => inspection.diagnostic === undefined ? [] : [inspection.diagnostic])),\n };\n}\n","/**\n * Per-MODEL slot allocator: every row gets a small dense integer for its\n * lifetime, assigned at ingest and released only on permanent removal.\n * Mutable by design — this is instance state, not revision state; the\n * revision-scoped structures (`slot-vector`, `membership-bitset`) are what\n * keep old snapshots valid when a released slot is reused.\n *\n * Capacity is the high-water mark and never shrinks, so slot-indexed\n * structures never renumber. Release is fail-loud (double release would hand\n * one slot to two live rows, which corrupts every slot-indexed structure\n * from that commit on).\n */\nexport function createSlotAllocator() {\n const free = [];\n let next = 0;\n let live = new Uint8Array(1024);\n const ensure = (slot) => {\n if (slot < live.length)\n return;\n const grown = new Uint8Array(Math.max(live.length * 2, slot + 1));\n grown.set(live);\n live = grown;\n };\n return {\n get capacity() {\n return next;\n },\n allocate() {\n const slot = free.length > 0 ? free.pop() : next++;\n ensure(slot);\n live[slot] = 1;\n return slot;\n },\n release(slot) {\n if (!Number.isInteger(slot) || slot < 0 || slot >= next) {\n throw new RangeError(`Slot ${slot} was never allocated.`);\n }\n if (live[slot] !== 1) {\n throw new RangeError(`Slot ${slot} is not live (double release).`);\n }\n live[slot] = 0;\n free.push(slot);\n },\n };\n}\n","import { filterVerdict, sortKeysOf, } from \"./compiled-query\";\nimport { isCalendarDateAggregate } from \"./calendar-date-aggregates\";\nimport { attachChangeOperationDiagnosticsForTesting, getChangeOperationDiagnosticsForTesting, } from \"./change-journal\";\nimport { rowPassesFilter } from \"./filter-membership\";\nimport { PretableRowIdentityChangeError, PretableRowModelError, PretableUnsupportedRowUpdateError, } from \"./errors\";\nimport { instrumentOrderStatisticTree } from \"./persistent/order-statistic-tree\";\nimport { instrumentPersistentMap } from \"./persistent/persistent-map\";\nimport { attachGroupIndex, getGroupIndex, makeGroupId, updateGroupIndex, visibleIndexOf, visibleRange, } from \"./group-index\";\nimport { inspectRowIntegrity, } from \"./row-integrity\";\nimport { orderedRowEntry } from \"./ordered-row-entry\";\nimport { clearMembershipBit, cloneMembership, setMembershipBit, EMPTY_MEMBERSHIP, } from \"./membership-bitset\";\nimport { slotVectorWithAll } from \"./slot-vector\";\nimport { createFlatVisibleTree, membershipFromFlatTree } from \"./visible-index\";\nexport const getTransactionChangeDiagnosticsForTesting = getChangeOperationDiagnosticsForTesting;\nclass TransactionExecutionError extends PretableRowModelError {\n rowIds;\n groupValues;\n groupId;\n constructor(error) {\n super(error.code, error.message, {\n operation: \"apply-transaction\",\n rowId: error.rowId,\n columnId: error.columnId,\n cause: error.cause,\n });\n const detailed = error;\n this.rowIds = detailed.rowIds;\n this.groupValues = detailed.groupValues;\n this.groupId = detailed.groupId;\n }\n}\nclass TransactionValidationError extends PretableRowModelError {\n path;\n name = \"TransactionValidationError\";\n constructor(path, message, cause) {\n super(\"derivation-failed\", message, {\n operation: \"apply-transaction\",\n cause,\n });\n this.path = path;\n }\n}\nfunction remap(error) {\n if (error instanceof PretableRowModelError &&\n error.code !== \"reentrant-mutation\" &&\n error.operation !== \"apply-transaction\") {\n throw new TransactionExecutionError(error);\n }\n throw error;\n}\nfunction fail(code, message, rowId, cause) {\n throw new PretableRowModelError(code, message, {\n operation: \"apply-transaction\",\n rowId,\n cause,\n });\n}\nfunction invalid(path, message, cause) {\n throw new TransactionValidationError(path, message, cause);\n}\nfunction readProperty(source, key, path) {\n try {\n return Reflect.get(source, key);\n }\n catch (cause) {\n return invalid(path, `The value at ${path} could not be read safely.`, cause);\n }\n}\nfunction captureDenseList(value, path) {\n if (value === undefined)\n return Object.freeze([]);\n try {\n if (!Array.isArray(value))\n return invalid(path, `${path} must be an array.`);\n const length = value.length;\n const captured = [];\n for (let index = 0; index < length; index += 1) {\n const entryPath = `${path}[${index}]`;\n if (!Object.hasOwn(value, index)) {\n return invalid(entryPath, `${path} must be a dense array.`);\n }\n captured.push(readProperty(value, index, entryPath));\n }\n return Object.freeze(captured);\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n return invalid(path, `${path} could not be captured safely.`, cause);\n }\n}\nfunction validRowId(value) {\n return typeof value === \"string\" || typeof value === \"number\";\n}\n/** Patches use enumerable own data properties, including symbol keys. */\nfunction capturePatch(value, path) {\n if (value === null || typeof value !== \"object\") {\n return invalid(path, `${path} must be an object.`);\n }\n try {\n const captured = [];\n for (const key of Reflect.ownKeys(value)) {\n const keyPath = typeof key === \"symbol\" ? `${path}[${String(key)}]` : `${path}.${key}`;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor === undefined)\n return invalid(keyPath, `The property at ${keyPath} disappeared.`);\n if (!descriptor.enumerable)\n continue;\n if (!(\"value\" in descriptor)) {\n return invalid(keyPath, `The patch property at ${keyPath} must be a data property.`);\n }\n captured.push(Object.freeze({ key, value: descriptor.value }));\n }\n return Object.freeze(captured);\n }\n catch (cause) {\n if (cause instanceof PretableRowModelError)\n throw cause;\n return invalid(path, `${path} could not be captured safely.`, cause);\n }\n}\nfunction mergeChanges(previous, patches, rowId) {\n try {\n const prototype = Object.getPrototypeOf(previous);\n if (Array.isArray(previous) ||\n (prototype !== Object.prototype && prototype !== null)) {\n throw new PretableUnsupportedRowUpdateError(rowId);\n }\n const row = Object.create(prototype);\n for (const key of Reflect.ownKeys(previous)) {\n const descriptor = Object.getOwnPropertyDescriptor(previous, key);\n if (descriptor === undefined)\n throw new TypeError(\"A row property disappeared.\");\n Object.defineProperty(row, key, {\n ...descriptor,\n configurable: true,\n ...(\"value\" in descriptor ? { writable: true } : {}),\n });\n }\n const originals = new Map();\n for (const patch of patches) {\n for (const property of patch) {\n if (!originals.has(property.key)) {\n originals.set(property.key, Object.getOwnPropertyDescriptor(previous, property.key));\n }\n Object.defineProperty(row, property.key, {\n value: property.value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n }\n const changed = Array.from(originals, ([key, descriptor]) => {\n const final = Object.getOwnPropertyDescriptor(row, key);\n return (descriptor === undefined ||\n !(\"value\" in descriptor) ||\n descriptor.enumerable !== true ||\n !Object.is(descriptor.value, final.value));\n }).some(Boolean);\n return { row: changed ? Object.freeze(row) : previous, changed };\n }\n catch (cause) {\n if (cause instanceof PretableUnsupportedRowUpdateError)\n throw cause;\n throw new PretableUnsupportedRowUpdateError(rowId, cause);\n }\n}\nfunction createRecord(row, rowId, sourceOrder, slot, queryPlan, instrumentation) {\n if (instrumentation !== undefined)\n instrumentation.work.rowsEvaluated += 1;\n const metadata = queryPlan.evaluate({\n rowId,\n row: row,\n sourceOrder,\n slot,\n });\n const inspection = inspectRowIntegrity(row, rowId, undefined, false);\n return {\n record: Object.freeze({\n rowId,\n row,\n sourceOrder,\n slot,\n metadata,\n publicRow: Object.freeze({\n kind: \"data\",\n rowId,\n row,\n sourceIndex: sourceOrder,\n depth: 0,\n }),\n integrity: inspection.integrity,\n }),\n diagnostic: inspection.diagnostic,\n };\n}\nfunction sameKeyValues(left, right) {\n return (left.length === right.length &&\n left.every((entry, index) => entry.columnId === right[index]?.columnId &&\n Object.is(entry.value, right[index]?.value)));\n}\nfunction sameFlatOrder(previousPlan, nextPlan, previous, next, \n/** The committed root's membership verdict for this row (the OLD one). */\npreviousPasses, \n/** The drafting plan's verdict for `next`, computed by the caller. */\nnextPasses) {\n // Each record's keys resolve from the plan that evaluated it: `previous`\n // from the committed root's plan, `next` from the drafting plan. Outside\n // the same-reference-mutation recompile these are one and the same object.\n // The two VERDICTS likewise come from two different places, and must: the\n // old one is structural (root membership), the new one is computed. A\n // row-keyed verdict store could not tell them apart when the plan object is\n // shared, which is exactly the same-reference-mutation case.\n return (previous.sourceOrder === next.sourceOrder &&\n previousPasses === nextPasses &&\n sameKeyValues(sortKeysOf(previousPlan, previous), sortKeysOf(nextPlan, next)));\n}\nfunction sameGroupIndexContribution(previousPlan, nextPlan, previous, next, previousPasses, nextPasses) {\n if (!sameFlatOrder(previousPlan, nextPlan, previous, next, previousPasses, nextPasses) ||\n !sameKeyValues(previous.metadata.groupPath, next.metadata.groupPath)) {\n return false;\n }\n const previousLeaves = previous.metadata.aggregateLeaves;\n const nextLeaves = next.metadata.aggregateLeaves;\n return (previousLeaves.length === nextLeaves.length &&\n previousLeaves.every((previousLeaf, index) => {\n const nextLeaf = nextLeaves[index];\n if (nextLeaf === undefined ||\n previousLeaf.columnId !== nextLeaf.columnId ||\n previousLeaf.aggregate !== nextLeaf.aggregate\n // A per-leaf filtered flag is deliberately NOT compared: whether a\n // leaf belongs to the filtered aggregate tree is the row's filter\n // verdict, and `sameFlatOrder` above already compared the old verdict\n // against the new one for this very row. Comparing it again here only\n // restated that check.\n ) {\n return false;\n }\n if (typeof previousLeaf.aggregate !== \"string\" &&\n !isCalendarDateAggregate(previousLeaf.aggregate)) {\n return (Object.is(previousLeaf.allLeaf.row, nextLeaf.allLeaf.row) &&\n Object.is(previousLeaf.allLeaf.value, nextLeaf.allLeaf.value) &&\n Object.is(previousLeaf.allLeaf.dependency, nextLeaf.allLeaf.dependency));\n }\n // The dependency's sortKeys are deliberately NOT compared here:\n // sort-key changes no longer dirty aggregate leaves BY DESIGN\n // (aggregation is order-independent; `sameFlatOrder` above already\n // compared keys through the store).\n return ((previousLeaf.aggregate === \"count\" ||\n Object.is(previousLeaf.allLeaf.value, nextLeaf.allLeaf.value)) &&\n previousLeaf.allLeaf.dependency.sourceOrder ===\n nextLeaf.allLeaf.dependency.sourceOrder);\n }));\n}\nfunction dataRef(rowId) {\n return Object.freeze({ kind: \"data\", rowId });\n}\nfunction groupPathIds(metadata) {\n return Object.freeze(metadata.groupPath.map((_, index) => makeGroupId(metadata.groupPath.slice(0, index + 1))));\n}\nfunction sameVisibleRef(left, right) {\n if (left.kind !== right.kind)\n return false;\n if (left.kind === \"group\") {\n return right.kind === \"group\" && left.groupId === right.groupId;\n }\n return (right.kind === \"data\" &&\n (left.rowId === right.rowId ||\n (left.rowId !== left.rowId && right.rowId !== right.rowId)));\n}\nfunction rankAfterStructuralOperations(ref, previousIndex, operations) {\n let current = previousIndex;\n let present = previousIndex >= 0;\n for (const operation of operations) {\n if (operation.kind === \"remove\") {\n if (sameVisibleRef(ref, operation.ref)) {\n present = false;\n current = -1;\n }\n else if (present && operation.previousIndex < current)\n current -= 1;\n continue;\n }\n if (operation.kind === \"insert\") {\n if (sameVisibleRef(ref, operation.ref)) {\n present = true;\n current = operation.index;\n }\n else if (present && operation.index <= current)\n current += 1;\n continue;\n }\n if (sameVisibleRef(ref, operation.ref)) {\n present = true;\n current = operation.index;\n continue;\n }\n if (present) {\n if (operation.previousIndex < current)\n current -= 1;\n if (operation.index <= current)\n current += 1;\n }\n }\n return present ? current : -1;\n}\nfunction groupedTransactionOperations(input) {\n const oldGroups = getGroupIndex(input.previous.visible);\n const nextGroups = getGroupIndex(input.nextVisible);\n if (oldGroups === undefined || nextGroups === undefined)\n return Object.freeze([]);\n const policy = input.previous.expansion.default;\n const affectedGroupIds = new Set();\n for (const record of [...input.removals, ...input.insertions]) {\n for (const groupId of groupPathIds(record.metadata)) {\n affectedGroupIds.add(groupId);\n }\n }\n const candidates = [];\n const rowCandidates = [];\n const updates = [];\n let visibleRowReads = 0;\n for (const groupId of affectedGroupIds) {\n const ref = Object.freeze({ kind: \"group\", groupId });\n const previousIndex = visibleIndexOf(oldGroups, policy, ref);\n const index = visibleIndexOf(nextGroups, policy, ref);\n const candidate = { ref, previousIndex, index };\n candidates.push(candidate);\n if (previousIndex >= 0 && index >= 0) {\n const previousRow = visibleRange(oldGroups, policy, previousIndex, previousIndex + 1)[0];\n const nextRow = visibleRange(nextGroups, policy, index, index + 1)[0];\n visibleRowReads += 2;\n if (previousRow?.kind === \"group\" && nextRow?.kind === \"group\") {\n const fields = [\n !Object.is(previousRow.aggregates, nextRow.aggregates)\n ? \"aggregates\"\n : undefined,\n previousRow.childCount !== nextRow.childCount\n ? \"childCount\"\n : undefined,\n previousRow.expanded !== nextRow.expanded\n ? \"expanded\"\n : undefined,\n previousRow.depth !== nextRow.depth ? \"depth\" : undefined,\n ].filter((field) => field !== undefined);\n if (fields.length > 0) {\n updates.push(Object.freeze({\n kind: \"update\",\n ref,\n index,\n fields: Object.freeze(fields),\n }));\n }\n }\n }\n }\n const insertedById = new Map(input.insertions.map((record) => [record.rowId, record]));\n const removedById = new Map(input.removals.map((record) => [record.rowId, record]));\n for (const rowId of new Set([\n ...removedById.keys(),\n ...insertedById.keys(),\n ])) {\n const previousRecord = removedById.get(rowId);\n const nextRecord = insertedById.get(rowId);\n const ref = dataRef(rowId);\n const previousIndex = visibleIndexOf(oldGroups, policy, ref);\n const index = visibleIndexOf(nextGroups, policy, ref);\n const candidate = { ref, previousIndex, index };\n candidates.push(candidate);\n rowCandidates.push(candidate);\n if (previousIndex >= 0 &&\n index >= 0 &&\n previousRecord !== undefined &&\n nextRecord !== undefined &&\n !Object.is(previousRecord.row, nextRecord.row)) {\n updates.push(Object.freeze({\n kind: \"update\",\n ref,\n index,\n fields: Object.freeze([\"row\"]),\n }));\n }\n }\n const structural = [];\n const absent = candidates\n .filter(({ previousIndex, index }) => previousIndex >= 0 && index < 0)\n .sort((left, right) => right.previousIndex - left.previousIndex);\n for (const { ref, previousIndex } of absent) {\n structural.push(Object.freeze({ kind: \"remove\", ref, previousIndex }));\n }\n const inserted = candidates\n .filter(({ previousIndex, index }) => previousIndex < 0 && index >= 0)\n .sort((left, right) => left.index - right.index);\n const targets = rowCandidates\n .filter(({ previousIndex, index }) => previousIndex >= 0 && index >= 0)\n .map((candidate) => ({\n ...candidate,\n workingIndex: candidate.index -\n inserted.filter(({ index }) => index <= candidate.index).length,\n }))\n .sort((left, right) => left.workingIndex - right.workingIndex);\n const moveToIndex = ({ ref, previousIndex }, index) => {\n const currentIndex = rankAfterStructuralOperations(ref, previousIndex, structural);\n if (currentIndex !== index) {\n structural.push(Object.freeze({\n kind: \"move\",\n ref,\n previousIndex: currentIndex,\n index,\n }));\n }\n return currentIndex;\n };\n // First place surviving changed rows in the view with future insertions\n // removed from its coordinate space. This preserves untouched rows and\n // groups without enumerating them.\n for (const { ref, previousIndex, workingIndex } of targets) {\n const currentIndex = rankAfterStructuralOperations(ref, previousIndex, structural);\n if (currentIndex > workingIndex) {\n moveToIndex({ ref, previousIndex, index: workingIndex }, workingIndex);\n }\n }\n for (const target of [...targets].reverse()) {\n const currentIndex = rankAfterStructuralOperations(target.ref, target.previousIndex, structural);\n if (currentIndex < target.workingIndex) {\n moveToIndex(target, target.workingIndex);\n }\n }\n for (const target of [...targets].reverse()) {\n moveToIndex(target, target.workingIndex);\n }\n for (const { ref, index } of inserted) {\n structural.push(Object.freeze({ kind: \"insert\", ref, index }));\n }\n const finalRowTargets = rowCandidates\n .filter(({ index }) => index >= 0)\n .sort((left, right) => right.index - left.index);\n for (const target of finalRowTargets) {\n moveToIndex(target, target.index);\n }\n return attachChangeOperationDiagnosticsForTesting(Object.freeze([\n ...structural,\n ...updates.sort((left, right) => {\n const leftIndex = left.kind === \"update\" ? left.index : 0;\n const rightIndex = right.kind === \"update\" ? right.index : 0;\n return leftIndex - rightIndex;\n }),\n ]), {\n touchedRefs: candidates.length,\n visibleRowReads,\n });\n}\nfunction rebaseSourceOrder(metadata, sourceOrder) {\n const aggregateLeaves = metadata.aggregateLeaves.map((leaf) => {\n // A rebase changes only the source order; the entry-carried sort keys\n // ride along unchanged.\n const dependency = Object.freeze({\n ...leaf.allLeaf.dependency,\n sourceOrder,\n });\n return Object.freeze({\n ...leaf,\n allLeaf: Object.freeze({ ...leaf.allLeaf, dependency }),\n });\n });\n return Object.freeze({\n ...metadata,\n sourceOrder,\n aggregateLeaves: Object.freeze(aggregateLeaves),\n });\n}\n/** Validates and prepares a complete transaction before acquiring transient roots. */\nexport function applyFlatTransactionDraft(input) {\n /*\n * Abandon rule: the draft allocates slots while preparing records, but this\n * function can still throw after that (metadata evaluation runs user code);\n * leaked allocations would pin free-list slots forever. Every allocation is\n * recorded here; the tail `catch` releases them on that live invariant. The\n * `effective: false` release just above it is defensive — every prepared\n * candidate implies `effective`, so that branch cannot currently be taken\n * with a non-empty `allocatedSlots`, but a future change to this function's\n * effectiveness check must not silently reopen the leak. The success path\n * releases the REMOVED rows' slots instead — a removed slot must never be\n * released on a failure path, because the committed root still owns it.\n */\n const allocatedSlots = [];\n try {\n const transaction = input.transaction;\n if (transaction === null || typeof transaction !== \"object\") {\n return invalid(\"transaction\", \"The transaction must be an object.\");\n }\n const rawAdds = readProperty(transaction, \"add\", \"transaction.add\");\n const rawUpdates = readProperty(transaction, \"update\", \"transaction.update\");\n const rawRemoves = readProperty(transaction, \"remove\", \"transaction.remove\");\n const adds = captureDenseList(rawAdds, \"transaction.add\");\n const updateEntries = captureDenseList(rawUpdates, \"transaction.update\");\n const removes = captureDenseList(rawRemoves, \"transaction.remove\");\n const capturedUpdates = [];\n for (let index = 0; index < updateEntries.length; index += 1) {\n const entry = updateEntries[index];\n const path = `transaction.update[${index}]`;\n if (entry === null || typeof entry !== \"object\") {\n return invalid(path, `${path} must be an object.`);\n }\n const rawId = readProperty(entry, \"id\", `${path}.id`);\n if (!validRowId(rawId)) {\n return invalid(`${path}.id`, `${path}.id must be a string or number.`);\n }\n const changes = readProperty(entry, \"changes\", `${path}.changes`);\n capturedUpdates.push({\n rowId: rawId,\n patch: capturePatch(changes, `${path}.changes`),\n });\n }\n const capturedRemoves = [];\n for (let index = 0; index < removes.length; index += 1) {\n const rowId = removes[index];\n const path = `transaction.remove[${index}]`;\n if (!validRowId(rowId)) {\n return invalid(path, `${path} must be a string or number.`);\n }\n capturedRemoves.push(rowId);\n }\n const addById = new Map();\n for (let index = 0; index < adds.length; index += 1) {\n const row = adds[index];\n let rowId;\n try {\n rowId = input.getRowId(row);\n }\n catch (cause) {\n return invalid(`transaction.add[${index}]`, \"The row ID accessor failed.\", cause);\n }\n if (!validRowId(rowId)) {\n return invalid(`transaction.add[${index}]`, \"The row ID accessor must return a string or number.\");\n }\n if (addById.has(rowId))\n fail(\"duplicate-row-id\", `Duplicate added row ID ${String(rowId)}.`, rowId);\n addById.set(rowId, row);\n }\n const updateById = new Map();\n for (const update of capturedUpdates) {\n const list = updateById.get(update.rowId);\n if (list === undefined)\n updateById.set(update.rowId, [update.patch]);\n else\n list.push(update.patch);\n }\n const removeIds = new Set();\n for (const rowId of capturedRemoves)\n removeIds.add(rowId);\n for (const rowId of addById.keys()) {\n if (updateById.has(rowId) || removeIds.has(rowId))\n fail(\"transaction-conflict\", `Row ID ${String(rowId)} appears in multiple transaction categories.`, rowId);\n }\n for (const rowId of updateById.keys()) {\n if (removeIds.has(rowId))\n fail(\"transaction-conflict\", `Row ID ${String(rowId)} appears in multiple transaction categories.`, rowId);\n }\n for (const rowId of addById.keys()) {\n if (input.root.rows.has(rowId))\n fail(\"existing-row-id\", `Row ID ${String(rowId)} already exists.`, rowId);\n }\n const issues = [];\n const pending = [];\n const prepared = [];\n const diagnostics = [];\n let unchanged = 0;\n let ignored = 0;\n let nextSourceOrder = input.nextSourceOrder;\n for (const [rowId, changes] of updateById) {\n const previous = input.root.rows.get(rowId);\n if (previous === undefined) {\n issues.push(Object.freeze({ code: \"unknown-update-id\", rowId }));\n ignored += 1;\n continue;\n }\n if (previous.integrity.kind === \"fingerprinted\") {\n throw new PretableUnsupportedRowUpdateError(rowId);\n }\n const merged = mergeChanges(previous.row, changes, rowId);\n if (!merged.changed) {\n unchanged += 1;\n continue;\n }\n pending.push({\n rowId,\n row: merged.row,\n sourceOrder: previous.sourceOrder,\n kind: \"update\",\n previousSlot: previous.slot,\n });\n }\n for (const [rowId, row] of addById) {\n pending.push({\n rowId,\n row,\n sourceOrder: nextSourceOrder,\n kind: \"add\",\n });\n nextSourceOrder += 1;\n }\n const effectiveRemoves = [];\n for (const rowId of removeIds) {\n if (!input.root.rows.has(rowId)) {\n issues.push(Object.freeze({ code: \"unknown-remove-id\", rowId }));\n ignored += 1;\n }\n else\n effectiveRemoves.push(rowId);\n }\n for (const candidate of pending) {\n if (candidate.kind !== \"update\")\n continue;\n let nextRowId;\n try {\n nextRowId = input.getRowId(candidate.row);\n }\n catch (cause) {\n throw new PretableRowIdentityChangeError(candidate.rowId, undefined, cause);\n }\n if (!validRowId(nextRowId) ||\n !(nextRowId === candidate.rowId ||\n (nextRowId !== nextRowId && candidate.rowId !== candidate.rowId))) {\n throw new PretableRowIdentityChangeError(candidate.rowId, nextRowId);\n }\n }\n // All lists, IDs, partial values, and resulting identities are validated\n // before active derivation callbacks are allowed to run.\n // Each prepared record's NEW verdict is computed once, here, and keyed by\n // the record OBJECT (the same row id can appear twice in one transaction,\n // and each occurrence carries its own record). It is never stored on the\n // record: the structures this draft builds are where it lands.\n const nextVerdicts = new Map();\n const passesNext = (record) => nextVerdicts.get(record);\n /** The committed root's membership — the OLD verdict for one row. */\n const passedPreviously = (rowId) => rowPassesFilter(input.root, rowId);\n for (const candidate of pending) {\n let slot;\n if (candidate.previousSlot !== undefined) {\n slot = candidate.previousSlot;\n }\n else {\n slot = input.slots.allocate();\n allocatedSlots.push(slot);\n }\n const made = createRecord(candidate.row, candidate.rowId, candidate.sourceOrder, slot, input.queryPlan, input.instrumentation);\n prepared.push(made.record);\n nextVerdicts.set(made.record, filterVerdict(input.queryPlan, made.record));\n if (made.diagnostic)\n diagnostics.push(made.diagnostic);\n }\n const effective = prepared.length > 0 || effectiveRemoves.length > 0;\n if (!effective) {\n for (const slot of allocatedSlots)\n input.slots.release(slot);\n return {\n rows: input.root.rows,\n sourceOrder: input.root.sourceOrder,\n visible: input.root.visible,\n recordsBySlot: input.root.recordsBySlot,\n visibleSlots: input.root.visibleSlots,\n nextSourceOrder: input.nextSourceOrder,\n added: 0,\n updated: 0,\n removed: 0,\n unchanged,\n ignored,\n issues: Object.freeze(issues),\n diagnostics: Object.freeze([]),\n operations: Object.freeze([]),\n affectedRowIds: Object.freeze([]),\n effective: false,\n };\n }\n const rowDraft = instrumentPersistentMap(input.root.rows, input.instrumentation).asTransient();\n const sourceDraft = instrumentOrderStatisticTree(input.root.sourceOrder, input.instrumentation).asTransient();\n const previousGroups = getGroupIndex(input.root.visible);\n const visibleNeedsChange = previousGroups === undefined &&\n (effectiveRemoves.some((rowId) => passedPreviously(rowId)) ||\n prepared.some((record) => {\n const previous = input.root.rows.get(record.rowId);\n return ((passedPreviously(record.rowId) || passesNext(record)) &&\n (previous === undefined ||\n !sameFlatOrder(input.root.queryPlan, input.queryPlan, previous, record, passedPreviously(record.rowId), passesNext(record))));\n }));\n const visibleDraft = visibleNeedsChange\n ? instrumentOrderStatisticTree(input.root.visible.rows, input.instrumentation).asTransient()\n : undefined;\n const operations = [];\n const ref = (rowId) => Object.freeze({ kind: \"data\", rowId });\n for (const rowId of effectiveRemoves) {\n if (previousGroups === undefined) {\n const previousIndex = visibleDraft?.rankOf(rowId);\n if (previousIndex !== undefined) {\n operations.push(Object.freeze({\n kind: \"remove\",\n ref: ref(rowId),\n previousIndex,\n }));\n }\n }\n rowDraft.delete(rowId);\n sourceDraft.remove(rowId);\n visibleDraft?.remove(rowId);\n }\n for (const record of prepared) {\n const previous = input.root.rows.get(record.rowId);\n // Both verdicts, resolved from their own authorities: the old one from\n // the committed root's membership (immutable while this loop mutates\n // the drafts), the new one computed when the record was prepared.\n const previouslyPassed = passedPreviously(record.rowId);\n const passes = passesNext(record);\n rowDraft.set(record.rowId, record);\n if (previous === undefined)\n sourceDraft.insertOrReplace(Object.freeze({\n rowId: record.rowId,\n sourceOrder: record.sourceOrder,\n }));\n if (previousGroups === undefined) {\n if (previous !== undefined &&\n sameFlatOrder(input.root.queryPlan, input.queryPlan, previous, record, previouslyPassed, passes)) {\n if (passes) {\n const index = visibleDraft?.rankOf(record.rowId) ??\n input.root.visible.rows.rankOf(record.rowId);\n if (index !== undefined) {\n operations.push(Object.freeze({\n kind: \"update\",\n ref: ref(record.rowId),\n index,\n fields: Object.freeze([\"row\"]),\n }));\n }\n }\n continue;\n }\n const previousIndex = previouslyPassed\n ? visibleDraft?.rankOf(record.rowId)\n : undefined;\n if (previouslyPassed)\n visibleDraft?.remove(record.rowId);\n if (passes) {\n visibleDraft?.insertOrReplace(orderedRowEntry(input.queryPlan, record));\n }\n const index = passes ? visibleDraft?.rankOf(record.rowId) : undefined;\n if (previousIndex !== undefined && index !== undefined) {\n operations.push(Object.freeze({\n kind: \"move\",\n ref: ref(record.rowId),\n previousIndex,\n index,\n }), Object.freeze({\n kind: \"update\",\n ref: ref(record.rowId),\n index,\n fields: Object.freeze([\"row\"]),\n }));\n }\n else if (previousIndex !== undefined) {\n operations.push(Object.freeze({\n kind: \"remove\",\n ref: ref(record.rowId),\n previousIndex,\n }));\n }\n else if (index !== undefined) {\n operations.push(Object.freeze({\n kind: \"insert\",\n ref: ref(record.rowId),\n index,\n }));\n }\n continue;\n }\n if (previous !== undefined &&\n sameFlatOrder(input.root.queryPlan, input.queryPlan, previous, record, previouslyPassed, passes))\n continue;\n }\n const frozenRows = rowDraft.freeze();\n const frozenFlatRows = visibleDraft?.freeze();\n const removedRecords = effectiveRemoves.map((rowId) => input.root.rows.get(rowId));\n const groupedRemovals = [\n ...removedRecords,\n ...prepared.flatMap((record) => {\n const previous = input.root.rows.get(record.rowId);\n return previous === undefined ||\n sameGroupIndexContribution(input.root.queryPlan, input.queryPlan, previous, record, passedPreviously(record.rowId), passesNext(record))\n ? []\n : [previous];\n }),\n ];\n const groupedInsertions = prepared.filter((record) => {\n const previous = input.root.rows.get(record.rowId);\n return (previous === undefined ||\n !sameGroupIndexContribution(input.root.queryPlan, input.queryPlan, previous, record, passedPreviously(record.rowId), passesNext(record)));\n });\n const grouped = previousGroups === undefined\n ? undefined\n : groupedRemovals.length === 0 && groupedInsertions.length === 0\n ? previousGroups\n : updateGroupIndex(previousGroups, groupedRemovals, groupedInsertions, input.root.expansion.overrides, \"apply-transaction\", input.instrumentation);\n const visible = grouped !== undefined\n ? attachGroupIndex(frozenFlatRows ?? input.root.visible.rows, grouped)\n : visibleDraft === undefined\n ? input.root.visible\n : Object.freeze({ rows: frozenFlatRows });\n const groupedOperations = grouped === undefined\n ? undefined\n : groupedTransactionOperations({\n previous: input.root,\n nextVisible: visible,\n removals: [\n ...removedRecords,\n ...prepared.flatMap((record) => {\n const old = input.root.rows.get(record.rowId);\n return old === undefined ? [] : [old];\n }),\n ],\n insertions: prepared,\n });\n // Flat roots maintain the membership bitset incrementally: clone the\n // committed root's set, clear every removal, then set/clear each prepared\n // record by its NEW verdict — the clone-and-flip the visible tree just\n // underwent, in bit form. When the flat visible tree was carried\n // unchanged, the member SET is provably unchanged too (no removal passed\n // previously, and every prepared record either failed the verdict on\n // both sides or `sameFlatOrder` held — verdict equality included), so\n // the bitset carries by identity. Grouped\n // roots keep the sentinel: their membership lives in the group index.\n let visibleSlots;\n if (previousGroups !== undefined) {\n visibleSlots = EMPTY_MEMBERSHIP;\n }\n else if (visibleDraft === undefined) {\n visibleSlots = input.root.visibleSlots;\n }\n else {\n const nextVisibleSlots = cloneMembership(input.root.visibleSlots, input.slots.capacity);\n for (const record of removedRecords)\n clearMembershipBit(nextVisibleSlots, record.slot);\n for (const record of prepared) {\n if (passesNext(record))\n setMembershipBit(nextVisibleSlots, record.slot);\n else\n clearMembershipBit(nextVisibleSlots, record.slot);\n }\n visibleSlots = nextVisibleSlots;\n }\n // Success path only (a throwing accessor never reaches here): removals\n // clear their slots, prepared records write theirs. No prepared record\n // can share a slot with a removal in one transaction — adds allocate\n // before the removals release below — so the order is free, but clears\n // are listed first anyway to match `replaceFlatRowsDraft`, where a later\n // write to the same slot must win.\n const slotWrites = [\n ...removedRecords.map((record) => [record.slot, undefined]),\n ...prepared.map((record) => [record.slot, record]),\n ];\n const { next: recordsBySlot, chunksTouched } = slotVectorWithAll(input.root.recordsBySlot, slotWrites, input.slots.capacity);\n if (input.instrumentation !== undefined)\n input.instrumentation.work.slotChunksTouched += chunksTouched;\n // The draft is committed as effective: removed rows are permanently gone,\n // so their slots go back to the free list (see the abandon-rule comment\n // above for why this must not happen any earlier).\n for (const record of removedRecords)\n input.slots.release(record.slot);\n return {\n rows: frozenRows,\n sourceOrder: sourceDraft.freeze(),\n visible,\n recordsBySlot,\n visibleSlots,\n nextSourceOrder,\n added: addById.size,\n updated: prepared.length - addById.size,\n removed: effectiveRemoves.length,\n unchanged,\n ignored,\n issues: Object.freeze(issues),\n diagnostics: Object.freeze(diagnostics),\n operations: groupedOperations ?? Object.freeze(operations),\n affectedRowIds: Object.freeze([\n ...effectiveRemoves,\n ...prepared.map((record) => record.rowId),\n ]),\n effective: true,\n };\n }\n catch (error) {\n // Abandoned draft: give back what it allocated, keep every removed slot.\n for (const slot of allocatedSlots)\n input.slots.release(slot);\n return remap(error);\n }\n}\n/** Applies an authoritative rows-array replacement through one set of drafts. */\nexport function replaceFlatRowsDraft(input) {\n let captured;\n try {\n captured = Array.from(input.rows);\n }\n catch (cause) {\n throw new PretableRowModelError(\"derivation-failed\", \"The rows input could not be read safely.\", { operation: \"set-rows\", cause });\n }\n const ids = [];\n const seen = new Set();\n for (const row of captured) {\n let rowId;\n try {\n rowId = input.getRowId(row);\n if (typeof rowId !== \"string\" && typeof rowId !== \"number\") {\n throw new TypeError(\"Row IDs must be strings or numbers.\");\n }\n }\n catch (cause) {\n throw new PretableRowModelError(\"derivation-failed\", \"The row ID accessor failed.\", { operation: \"set-rows\", cause });\n }\n if (seen.has(rowId)) {\n throw new PretableRowModelError(\"duplicate-row-id\", `Duplicate row ID ${String(rowId)}.`, { operation: \"set-rows\", rowId });\n }\n seen.add(rowId);\n ids.push(rowId);\n }\n const candidates = [];\n const changedRecords = [];\n // The NEW verdict per changed record, computed once beside the record and\n // spent on the drafts below. The OLD verdict never appears here: it is read\n // from `input.root`'s membership, which matters most in the\n // same-reference-mutation retry, where the row OBJECT is unchanged and the\n // two plans are distinct compilations of the same query — nothing keyed by\n // the row could separate the two answers, but the two ROOTS are separate\n // objects.\n const nextVerdicts = new Map();\n const passesNext = (record) => nextVerdicts.get(record);\n const passedPreviously = (rowId) => rowPassesFilter(input.root, rowId);\n const diagnostics = [];\n let sameReferenceMutation = false;\n let added = 0;\n let updated = 0;\n let unchanged = 0;\n for (let sourceOrder = 0; sourceOrder < captured.length; sourceOrder += 1) {\n const row = captured[sourceOrder];\n const rowId = ids[sourceOrder];\n const previous = input.root.rows.get(rowId);\n const sameReference = previous !== undefined && Object.is(previous.row, row);\n const inspection = inspectRowIntegrity(row, rowId, previous?.integrity, sameReference);\n if (inspection.diagnostic)\n diagnostics.push(inspection.diagnostic);\n if (inspection.sameReferenceMutation)\n sameReferenceMutation = true;\n if (previous !== undefined &&\n sameReference &&\n previous.sourceOrder === sourceOrder &&\n !inspection.sameReferenceMutation) {\n unchanged += 1;\n continue;\n }\n candidates.push({\n row,\n rowId,\n sourceOrder,\n integrity: inspection.integrity,\n cachedMetadata: sameReference && !inspection.sameReferenceMutation\n ? previous?.metadata\n : undefined,\n previousSlot: previous?.slot,\n });\n if (previous === undefined)\n added += 1;\n else\n updated += 1;\n }\n const removedRecords = [];\n for (const [rowId, record] of input.root.rows.entries()) {\n if (!seen.has(rowId))\n removedRecords.push(record);\n }\n const removed = removedRecords.length;\n const effective = added > 0 || updated > 0 || removed > 0;\n if (sameReferenceMutation && input.acceptSameReferenceMutation !== true) {\n return {\n rows: input.root.rows,\n sourceOrder: input.root.sourceOrder,\n visible: input.root.visible,\n recordsBySlot: input.root.recordsBySlot,\n visibleSlots: input.root.visibleSlots,\n nextSourceOrder: input.nextSourceOrder,\n added,\n updated,\n removed,\n unchanged,\n ignored: 0,\n issues: Object.freeze([]),\n diagnostics: Object.freeze(diagnostics),\n operations: Object.freeze([]),\n affectedRowIds: Object.freeze([]),\n effective: false,\n sameReferenceMutation: true,\n };\n }\n /*\n * Abandon rule (see `applyFlatTransactionDraft` for the rationale): fresh\n * allocations are recorded and released if this draft is abandoned mid-way\n * (metadata evaluation runs user code and can throw). Removed rows' slots\n * are NEVER released on a failure path — the committed root still owns\n * them. On success they are released at the very end, except the ones\n * handed straight to new rows: a set-rows call both retires and ingests\n * rows in one commit, and handing a retiring row's slot to a new row is\n * release-then-reuse without an allocator round trip — which also keeps a\n * mid-draft throw from ever leaving a still-live row's slot on the free\n * list.\n */\n const allocatedSlots = [];\n const reusableRemovedSlots = removedRecords.map((record) => record.slot);\n const takeSlot = () => {\n const reused = reusableRemovedSlots.pop();\n if (reused !== undefined)\n return reused;\n const slot = input.slots.allocate();\n allocatedSlots.push(slot);\n return slot;\n };\n try {\n for (const candidate of candidates) {\n const { row, rowId, sourceOrder } = candidate;\n // `evaluate` needs a slot up front (it's part of `CompiledRowInput`\n // now, unread this task), but the REAL slot for a brand-new row is\n // still resolved after evaluation succeeds, exactly as before this\n // field existed: `takeSlot()` calls `input.slots.allocate()`, a real\n // allocator mutation that bumps the high-water mark permanently (see\n // `slot-allocator.ts` — capacity never shrinks), and doing that before\n // a throwing accessor runs would leak capacity that a release can't\n // undo. A carried row's slot has no such hazard (no allocator call),\n // so it is used directly. `-1` is a placeholder for the fresh-slot\n // case only: harmless because nothing reads `CompiledRowInput.slot`\n // yet.\n const placeholderSlot = candidate.previousSlot !== undefined ? candidate.previousSlot : -1;\n let metadata;\n try {\n if (candidate.cachedMetadata === undefined) {\n if (input.instrumentation !== undefined)\n input.instrumentation.work.rowsEvaluated += 1;\n metadata = input.queryPlan.evaluate({\n rowId,\n row: row,\n sourceOrder,\n slot: placeholderSlot,\n });\n }\n else {\n metadata = rebaseSourceOrder(candidate.cachedMetadata, sourceOrder);\n }\n }\n catch (error) {\n if (error instanceof PretableRowModelError &&\n error.operation !== \"set-rows\") {\n throw new PretableRowModelError(error.code, error.message, {\n operation: \"set-rows\",\n rowId: error.rowId,\n columnId: error.columnId,\n cause: error.cause,\n });\n }\n throw error;\n }\n const slot = candidate.previousSlot !== undefined\n ? candidate.previousSlot\n : takeSlot();\n const publicRow = Object.freeze({\n kind: \"data\",\n rowId,\n row,\n sourceIndex: sourceOrder,\n depth: 0,\n });\n const record = Object.freeze({\n rowId,\n row,\n sourceOrder,\n slot,\n metadata,\n publicRow,\n integrity: candidate.integrity,\n });\n changedRecords.push(record);\n // A record whose metadata was CARRIED carries its verdict too, and the\n // carried verdict is the previous root's membership: `cachedMetadata` is\n // only offered for an unmutated same-reference row, whose filter-column\n // values are by definition the ones the committed root already judged.\n // Re-running the predicate here would be a second accessor pass over\n // rows this path exists to avoid re-evaluating (a pinned budget).\n nextVerdicts.set(record, candidate.cachedMetadata === undefined\n ? filterVerdict(input.queryPlan, record)\n : passedPreviously(rowId));\n }\n if (!effective) {\n return {\n rows: input.root.rows,\n sourceOrder: input.root.sourceOrder,\n visible: input.root.visible,\n recordsBySlot: input.root.recordsBySlot,\n visibleSlots: input.root.visibleSlots,\n nextSourceOrder: input.nextSourceOrder,\n added,\n updated,\n removed,\n unchanged,\n ignored: 0,\n issues: Object.freeze([]),\n diagnostics: Object.freeze(diagnostics),\n operations: Object.freeze([]),\n affectedRowIds: Object.freeze([]),\n effective: false,\n sameReferenceMutation,\n };\n }\n const rowDraft = instrumentPersistentMap(input.root.rows, input.instrumentation).asTransient();\n const sourceDraft = instrumentOrderStatisticTree(input.root.sourceOrder, input.instrumentation).asTransient();\n const orderChangedRecords = changedRecords.filter((record) => {\n const previous = input.root.rows.get(record.rowId);\n return (previous === undefined ||\n !sameFlatOrder(input.root.queryPlan, input.queryPlan, previous, record, passedPreviously(record.rowId), passesNext(record)));\n });\n const affectedVisibleIds = new Set(orderChangedRecords\n .filter((record) => passedPreviously(record.rowId) || passesNext(record))\n .map((record) => record.rowId));\n for (const record of removedRecords) {\n // A removed row's verdict is the one it was drawn under: membership.\n if (passedPreviously(record.rowId))\n affectedVisibleIds.add(record.rowId);\n }\n let hasUnaffectedVisible = false;\n for (const entry of input.root.visible.rows.entries()) {\n if (!affectedVisibleIds.has(entry.record.rowId)) {\n hasUnaffectedVisible = true;\n break;\n }\n }\n const visibleDraft = affectedVisibleIds.size === 0\n ? undefined\n : instrumentOrderStatisticTree(hasUnaffectedVisible\n ? input.root.visible.rows\n : createFlatVisibleTree(input.queryPlan), input.instrumentation).asTransient();\n for (const record of removedRecords) {\n rowDraft.delete(record.rowId);\n sourceDraft.remove(record.rowId);\n if (hasUnaffectedVisible)\n visibleDraft?.remove(record.rowId);\n }\n if (hasUnaffectedVisible) {\n for (const record of orderChangedRecords) {\n if (passedPreviously(record.rowId))\n visibleDraft?.remove(record.rowId);\n }\n }\n for (const record of changedRecords) {\n rowDraft.set(record.rowId, record);\n const previous = input.root.rows.get(record.rowId);\n if (previous === undefined ||\n previous.sourceOrder !== record.sourceOrder) {\n sourceDraft.insertOrReplace(Object.freeze({\n rowId: record.rowId,\n sourceOrder: record.sourceOrder,\n }));\n }\n }\n for (const record of orderChangedRecords) {\n if (passesNext(record)) {\n visibleDraft?.insertOrReplace(orderedRowEntry(input.queryPlan, record));\n }\n }\n const frozenRows = rowDraft.freeze();\n const frozenSource = sourceDraft.freeze();\n const previousGroups = getGroupIndex(input.root.visible);\n const visible = previousGroups === undefined\n ? visibleDraft === undefined\n ? input.root.visible\n : Object.freeze({ rows: visibleDraft.freeze() })\n : attachGroupIndex(input.root.visible.rows, updateGroupIndex(previousGroups, [\n ...removedRecords,\n ...changedRecords.flatMap((record) => {\n const old = input.root.rows.get(record.rowId);\n return old === undefined ? [] : [old];\n }),\n ], changedRecords, input.root.expansion.overrides, \"set-rows\", input.instrumentation));\n // Set-rows is O(n) already, so the flat bitset is simply rebuilt from the\n // final flat tree (carried or frozen — either way that tree IS the\n // membership this bitset indexes). Grouped roots keep the sentinel.\n const visibleSlots = previousGroups !== undefined\n ? EMPTY_MEMBERSHIP\n : membershipFromFlatTree(visible.rows, input.slots.capacity);\n // Success path only. ORDER IS LOAD-BEARING: the transfer pool above can\n // retire a record and ingest a new one ON THE SAME SLOT in this one\n // commit, so every removal-clear must precede every record-write — a\n // later write to the same slot wins inside `slotVectorWithAll`. Records\n // that carried unchanged keep their bindings via the COW carry.\n const slotWrites = [\n ...removedRecords.map((record) => [record.slot, undefined]),\n ...changedRecords.map((record) => [record.slot, record]),\n ];\n const { next: recordsBySlot, chunksTouched } = slotVectorWithAll(input.root.recordsBySlot, slotWrites, input.slots.capacity);\n if (input.instrumentation !== undefined)\n input.instrumentation.work.slotChunksTouched += chunksTouched;\n // Committed as effective: retired slots not handed to new rows go back to\n // the free list (see the abandon-rule comment above).\n for (const slot of reusableRemovedSlots)\n input.slots.release(slot);\n return {\n rows: frozenRows,\n sourceOrder: frozenSource,\n visible,\n recordsBySlot,\n visibleSlots,\n nextSourceOrder: Math.max(input.nextSourceOrder, captured.length),\n added,\n updated,\n removed,\n unchanged,\n ignored: 0,\n issues: Object.freeze([]),\n diagnostics: Object.freeze(diagnostics),\n operations: Object.freeze([]),\n affectedRowIds: Object.freeze([\n ...removedRecords.map((record) => record.rowId),\n ...changedRecords.map((record) => record.rowId),\n ]),\n effective: true,\n sameReferenceMutation,\n };\n }\n catch (error) {\n // Abandoned draft: give back what it allocated, keep every removed slot.\n for (const slot of allocatedSlots)\n input.slots.release(slot);\n throw error;\n }\n}\n","import { compileQuery, fillSortKeysFromPrevious, isFilterOnlyChange, isSortOnlyChange, } from \"./compiled-query\";\nimport { rebuildRootForFilterOnlyChange } from \"./filter-rebuild\";\nimport { rebuildRootForSortOnlyChange } from \"./sort-rebuild\";\nimport { createCooperativeTransitionCandidate, createCooperativeTransitionRuntime, runCooperativeTransitionSlice, } from \"./cooperative-transition\";\nimport { createDistinctValueManager } from \"./distinct-values\";\nimport { createChangeJournal, getChangeJournalDiagnosticsForTesting, } from \"./change-journal\";\nimport { PretableDisposedModelError, findPretableReentrantMutationError, PretableReentrantMutationError, PretableRowModelError, PretableTransitionCancelledError, } from \"./errors\";\nimport { attachGroupIndex, getGroupIndex, setGroupOverride, } from \"./group-index\";\nimport { createPersistentMap } from \"./persistent/persistent-map\";\nimport { buildRowStore } from \"./row-store\";\nimport { createSlotAllocator } from \"./slot-allocator\";\nimport { EMPTY_MEMBERSHIP } from \"./membership-bitset\";\nimport { createFlatSnapshot, createVisibleIndex, membershipFromFlatTree, } from \"./visible-index\";\nimport { applyFlatTransactionDraft, replaceFlatRowsDraft, } from \"./transaction-draft\";\nfunction createSnapshot(root, instrumentation) {\n const snapshot = createFlatSnapshot(root);\n if (instrumentation === undefined)\n return snapshot;\n const count = (value) => {\n if (value !== undefined)\n instrumentation.work.snapshotOutputRowsRead += 1;\n return value;\n };\n const instrumentedSnapshot = Object.freeze({\n ...snapshot,\n rowAt: (index) => count(snapshot.rowAt(index)),\n range: (start, end) => {\n const rows = snapshot.range(start, end);\n instrumentation.work.snapshotOutputRowsRead += rows.length;\n return rows;\n },\n // The dense range read is a visible-row output walk like `range`; the\n // k-sized reads (`ɵslotOfRowId`, `ɵslotCapacity`) pass through the\n // spread above uncounted.\n ɵvisibleSlotRange: (start, end) => {\n const slots = snapshot.ɵvisibleSlotRange?.(start, end);\n if (slots !== undefined) {\n instrumentation.work.snapshotOutputRowsRead += slots.length;\n }\n return slots;\n },\n dataRowAt: (index) => count(snapshot.dataRowAt(index)),\n firstDataRow: () => count(snapshot.firstDataRow()),\n lastDataRow: () => count(snapshot.lastDataRow()),\n nextDataRow: (ref) => count(snapshot.nextDataRow(ref)),\n previousDataRow: (ref) => count(snapshot.previousDataRow(ref)),\n });\n instrumentation.snapshotRoots.set(instrumentedSnapshot, root);\n instrumentation.currentRevisionRoot = root;\n return instrumentedSnapshot;\n}\n/**\n * Default resident-row ceiling for the synchronous sort-only fast path.\n * Measured, not guessed: the 2026-08-27 browser sweep\n * (`docs/superpowers/specs/2026-08-27-size-gate-sync-paths-results.md`) put\n * the sort path's crossover of the dense-handle arc's 50ms single-block bar\n * near 10k rows (64ms observed at 15k); the default halves the crossover for\n * 2x headroom on machines slower than the sweep's.\n */\nexport const SORT_FAST_PATH_ROW_LIMIT_DEFAULT = 5_000;\n/**\n * Default resident-row ceiling for the synchronous filter-only fast path.\n * From the same sweep: the filter path's 50ms-bar crossover sits near 30k\n * rows (50ms first observed there; 87-93ms at 50k), halved for the same 2x\n * slower-machine headroom.\n */\nexport const FILTER_FAST_PATH_ROW_LIMIT_DEFAULT = 15_000;\nconst modelChangeJournals = new WeakMap();\nconst optionInstrumentation = new WeakMap();\nconst modelRevisionCauses = new WeakMap();\nconst modelActiveTransitionCandidates = new WeakMap();\nconst modelFilterAuthoritySetters = new WeakMap();\nconst modelSortAuthoritySetters = new WeakMap();\nconst modelSlotInternals = new WeakMap();\n/**\n * Re-declares who selected the loaded records, recompiling the plan when the\n * answer changes. Deliberately a registry lookup rather than a method on\n * `PretableRowModel`: only the rows-mode React surface needs it — a consumer\n * who builds their own model already decides what goes into the query — and\n * the public model interface should not grow a knob that boundary excludes.\n *\n * Silently ignores any model this module did not create. Callers must still\n * withhold it from models they do not own — a consumer-supplied model built by\n * `createLocalRowModel` is registered here too, and moving its authority would\n * be exactly the explicit-model change this design excludes.\n *\n * @internal\n */\nexport function ɵsetLocalRowModelFilterAuthority(model, \n// Spelled out rather than named as `CompiledFilterAuthority`: this is the one\n// declaration that crosses into `@pretable/core`'s entry point, and naming an\n// unexported alias there is a forgotten export the public-API guard rejects.\nauthority) {\n modelFilterAuthoritySetters.get(model)?.(authority);\n}\n/**\n * Re-declares who ordered the loaded records. The sort twin of\n * `ɵsetLocalRowModelFilterAuthority`, with the same registry design and\n * the same ownership rule: withhold it from models the surface does not own.\n *\n * @internal\n */\nexport function ɵsetLocalRowModelSortAuthority(model, authority) {\n modelSortAuthoritySetters.get(model)?.(authority);\n}\n/** Direct diagnostics seam; intentionally absent from the package barrel. */\nexport function registerLocalRowModelInstrumentationForTesting(options, instrumentation) {\n optionInstrumentation.set(options, instrumentation);\n}\nexport function getLocalRowModelRevisionCauseForTesting(model) {\n const read = modelRevisionCauses.get(model);\n if (read === undefined) {\n throw new TypeError(\"Diagnostics require a local Pretable row model.\");\n }\n return read();\n}\nexport function getLocalRowModelActiveTransitionCandidateForTesting(model) {\n const read = modelActiveTransitionCandidates.get(model);\n if (read === undefined) {\n throw new TypeError(\"Diagnostics require a local Pretable row model.\");\n }\n return read();\n}\n/**\n * Committed-root and slot-allocator seam for the slot-lifecycle tests;\n * intentionally absent from the package barrel.\n *\n * @internal test-only\n */\nexport function getLocalRowModelSlotInternalsForTesting(model) {\n const read = modelSlotInternals.get(model);\n if (read === undefined) {\n throw new TypeError(\"Diagnostics require a local Pretable row model.\");\n }\n return read();\n}\nexport function getLocalRowModelChangeJournalDiagnosticsForTesting(model) {\n const journal = modelChangeJournals.get(model);\n if (journal === undefined) {\n throw new TypeError(\"Diagnostics require a local Pretable row model.\");\n }\n return getChangeJournalDiagnosticsForTesting(journal);\n}\nclass PretableSetRowsExecutionError extends PretableRowModelError {\n name = \"PretableSetRowsExecutionError\";\n rowIds;\n groupValues;\n groupId;\n value;\n constructor(error) {\n super(error.code, error.message, {\n operation: \"set-rows\",\n rowId: error.rowId,\n columnId: error.columnId,\n cause: error.cause,\n });\n const detailed = error;\n this.rowIds = detailed.rowIds && Object.freeze([...detailed.rowIds]);\n this.groupValues =\n detailed.groupValues && Object.freeze([...detailed.groupValues]);\n this.groupId = detailed.groupId;\n this.value = detailed.value;\n }\n}\nclass PretableOperationExecutionError extends PretableRowModelError {\n name = \"PretableOperationExecutionError\";\n rowIds;\n groupValues;\n groupId;\n value;\n constructor(error, operation) {\n super(error.code, error.message, {\n operation,\n rowId: error.rowId,\n columnId: error.columnId,\n cause: error.cause,\n });\n const detailed = error;\n this.rowIds = detailed.rowIds && Object.freeze([...detailed.rowIds]);\n this.groupValues =\n detailed.groupValues && Object.freeze([...detailed.groupValues]);\n this.groupId = detailed.groupId;\n this.value = detailed.value;\n }\n}\nfunction remapOperationError(error, operation) {\n if (error instanceof PretableRowModelError &&\n error.code !== \"reentrant-mutation\" &&\n error.operation !== operation) {\n return new PretableOperationExecutionError(error, operation);\n }\n return error;\n}\nfunction remapSetRowsError(error) {\n if (error instanceof PretableRowModelError &&\n error.code !== \"reentrant-mutation\" &&\n error.operation !== \"set-rows\") {\n return new PretableSetRowsExecutionError(error);\n }\n return error;\n}\nfunction emitDiagnostics(diagnostics, sink) {\n if (sink === undefined)\n return;\n for (const diagnostic of diagnostics) {\n try {\n sink(diagnostic);\n }\n catch {\n // Diagnostics run after publication and never change command success.\n }\n }\n}\nconst READY = Object.freeze({ kind: \"ready\" });\nconst DISPOSED = Object.freeze({ kind: \"disposed\" });\nfunction emptyQuery() {\n return Object.freeze({\n filters: Object.freeze([]),\n sort: Object.freeze([]),\n rowGroups: Object.freeze([]),\n });\n}\nfunction createExpansionRoot(policy) {\n // Expanded, not collapsed. Grouping here is an interactive act as much as a\n // configuration one — the user drags a column into the group panel while\n // reading their rows — and collapsing on drop makes the data they were just\n // looking at disappear. AG Grid (`groupDefaultExpanded: 0`) and TanStack\n // (empty expanded map) both default collapsed, where grouping is set up by a\n // developer before the user arrives; `{ kind: \"through-depth\" }` is the\n // escape hatch for datasets too large to open at once.\n const defaultPolicy = Object.freeze(policy === undefined ? { kind: \"expanded\" } : { ...policy });\n return Object.freeze({\n default: defaultPolicy,\n overrides: createPersistentMap(),\n state: Object.freeze({ default: defaultPolicy, overrideCount: 0 }),\n });\n}\nfunction mutationResult(previousRevision, revision, counts = {}, issues = []) {\n return Object.freeze({\n previousRevision,\n revision,\n added: counts.added ?? 0,\n updated: counts.updated ?? 0,\n removed: counts.removed ?? 0,\n unchanged: counts.unchanged ?? 0,\n ignored: counts.ignored ?? 0,\n issues: Object.freeze(Array.from(issues)),\n });\n}\nfunction visibleRef(row) {\n return row.kind === \"data\"\n ? Object.freeze({ kind: \"data\", rowId: row.rowId })\n : Object.freeze({ kind: \"group\", groupId: row.groupId });\n}\nfunction expansionChangeOperations(previous, next, groupId) {\n const ref = Object.freeze({ kind: \"group\", groupId });\n const previousIndex = previous.indexOf(ref);\n const index = next.indexOf(ref);\n if (previousIndex < 0 || index < 0)\n return Object.freeze([]);\n const previousGroup = previous.rowAt(previousIndex);\n const nextGroup = next.rowAt(index);\n if (previousGroup?.kind !== \"group\" || nextGroup?.kind !== \"group\") {\n return Object.freeze([]);\n }\n const operations = [];\n if (previousGroup.expanded !== nextGroup.expanded) {\n operations.push(Object.freeze({\n kind: \"update\",\n ref,\n index,\n fields: Object.freeze([\"expanded\"]),\n }));\n }\n if (previousGroup.expanded && !nextGroup.expanded) {\n const descendants = [];\n for (let descendantIndex = previousIndex + 1; descendantIndex < previous.visibleRowCount; descendantIndex += 1) {\n const row = previous.rowAt(descendantIndex);\n if (row === undefined || row.depth <= previousGroup.depth)\n break;\n descendants.push({\n ref: visibleRef(row),\n previousIndex: descendantIndex,\n });\n }\n for (const descendant of descendants.reverse()) {\n operations.push(Object.freeze({ kind: \"remove\", ...descendant }));\n }\n }\n else if (!previousGroup.expanded && nextGroup.expanded) {\n for (let descendantIndex = index + 1; descendantIndex < next.visibleRowCount; descendantIndex += 1) {\n const row = next.rowAt(descendantIndex);\n if (row === undefined || row.depth <= nextGroup.depth)\n break;\n operations.push(Object.freeze({\n kind: \"insert\",\n ref: visibleRef(row),\n index: descendantIndex,\n }));\n }\n }\n return Object.freeze(operations);\n}\n/** @public */\nexport function createLocalRowModel(options) {\n const instrumentation = optionInstrumentation.get(options);\n optionInstrumentation.delete(options);\n const columns = Object.freeze(Array.from(options.columns));\n const getRowId = options.getRowId ??\n ((row) => row.id);\n const requestedDerivations = (options.derivations ??\n columns);\n const requestedQuery = options.query ?? emptyQuery();\n let filterAuthority = options.ɵfilterAuthority ?? \"engine\";\n let sortAuthority = options.ɵsortAuthority ?? \"engine\";\n let queryPlan = compileQuery({\n derivations: requestedDerivations,\n query: requestedQuery,\n filterAuthority,\n sortAuthority,\n });\n let derivations = queryPlan.derivations;\n let query = queryPlan.query;\n const aggregateFilteredRows = options.aggregateFilteredRows ?? false;\n const diagnosticSink = options.onDiagnostic;\n /**\n * Per-model row-slot allocator — mutable instance state, like\n * `nextSourceOrder`. Every record-creating path below threads it so a row's\n * slot is assigned exactly once, at ingest, and released exactly once, on\n * permanent removal.\n */\n const slots = createSlotAllocator();\n const initialStore = buildRowStore({\n rows: options.rows,\n getRowId,\n queryPlan,\n slots,\n instrumentation,\n });\n const initialExpansion = createExpansionRoot(options.initialExpansion);\n const initialVisible = createVisibleIndex(initialStore.records, queryPlan, aggregateFilteredRows, initialExpansion.overrides);\n let root = Object.freeze({\n revision: 0,\n parentRevision: null,\n rows: initialStore.rows,\n sourceOrder: initialStore.sourceOrder,\n recordsBySlot: initialStore.recordsBySlot,\n slotCapacity: slots.capacity,\n // Flat roots index their membership per slot; grouped roots carry the\n // sentinel and keep answering from the group index.\n visibleSlots: queryPlan.query.rowGroups.length > 0\n ? EMPTY_MEMBERSHIP\n : membershipFromFlatTree(initialVisible.rows, slots.capacity),\n visible: initialVisible,\n queryPlan,\n expansion: initialExpansion,\n cause: Object.freeze({ kind: \"initial\" }),\n });\n let snapshot = createSnapshot(root, instrumentation);\n let state = Object.freeze({\n snapshot,\n status: READY,\n });\n let disposed = false;\n let activeMutation;\n let nextSourceOrder = initialStore.records.length;\n let nextTransitionId = 1;\n let activeTransition;\n const listeners = new Set();\n const changeJournal = createChangeJournal(options.changeJournalCapacity);\n const sortFastPathRowLimit = options.ɵsortFastPathRowLimit ?? SORT_FAST_PATH_ROW_LIMIT_DEFAULT;\n const filterFastPathRowLimit = options.ɵfilterFastPathRowLimit ?? FILTER_FAST_PATH_ROW_LIMIT_DEFAULT;\n const transitionRuntime = createCooperativeTransitionRuntime({\n scheduler: options.transitionScheduler,\n now: options.transitionClock,\n budgetMs: options.transitionBudgetMs,\n maxUnitsPerSlice: options.transitionMaxUnitsPerSlice,\n instrumentation,\n });\n const distinctValues = createDistinctValueManager({\n getRoot: () => root,\n getDerivations: () => derivations,\n runtime: transitionRuntime,\n cacheCapacity: options.distinctValueCacheCapacity,\n });\n const assertCommandAllowed = (operation) => {\n if (activeMutation !== undefined) {\n throw new PretableReentrantMutationError(operation, activeMutation);\n }\n if (disposed)\n throw new PretableDisposedModelError(operation);\n };\n const guarded = (operation, action) => {\n assertCommandAllowed(operation);\n activeMutation = operation;\n try {\n return action();\n }\n catch (error) {\n const reentrant = findPretableReentrantMutationError(error);\n if (reentrant !== undefined)\n throw reentrant;\n throw error;\n }\n finally {\n activeMutation = undefined;\n }\n };\n const rebuildingStatus = (transition) => Object.freeze({\n kind: \"rebuilding\",\n transitionId: transition.id,\n completedRows: transition.candidate.completedRows,\n totalRows: transition.candidate.totalRows,\n });\n const commit = (next, status = activeTransition === undefined\n ? READY\n : rebuildingStatus(activeTransition)) => {\n root = next;\n snapshot = createSnapshot(root, instrumentation);\n state = Object.freeze({ snapshot, status });\n };\n const notify = () => {\n for (const listener of Array.from(listeners)) {\n try {\n listener();\n }\n catch {\n // One consumer must not prevent the remaining subscribers from waking.\n }\n }\n };\n const publishCommittedRoot = (committedRoot, previousRevision, revision, \n // Only the sort-only fast path may pass \"reorder\" (the one commit that\n // provably changes order and nothing else) and only the filter-only\n // fast path may pass \"refilter\" (membership changed, surviving order\n // and identities intact). Every other publisher keeps the plain\n // barrier default.\n barrierReason = \"bulk-replace\") => {\n queryPlan = committedRoot.queryPlan;\n query = committedRoot.queryPlan.query;\n derivations = committedRoot.queryPlan.derivations;\n commit(committedRoot, READY);\n // Every publisher goes through this one recipe. On a sort-only change\n // the distinct publish is structurally a no-op (distinct-value cache\n // keys hash filter/column/population semantics, never sort); on a\n // filter-only change it is LOAD-BEARING — filters are part of those\n // cache keys, so the new root must reach the manager here.\n distinctValues.publishTransitionRoot(committedRoot);\n changeJournal.appendBarrier(previousRevision, revision, barrierReason);\n };\n const transitionError = (error, operation) => {\n const remapped = remapOperationError(error, operation);\n return remapped instanceof PretableRowModelError\n ? remapped\n : new PretableRowModelError(\"derivation-failed\", `The ${operation} transition failed.`, { operation, cause: remapped });\n };\n const cancelActiveTransition = (reason) => {\n const transition = activeTransition;\n if (transition === undefined)\n return undefined;\n activeTransition = undefined;\n const cancelScheduled = transition.cancelScheduled;\n transition.cancelScheduled = undefined;\n try {\n cancelScheduled?.();\n }\n catch {\n // Scheduler cancellation is best-effort; model ownership still releases.\n }\n transition.candidate.release();\n transition.reject(new PretableTransitionCancelledError(transition.id, reason));\n return transition;\n };\n const failTransition = (transition, error) => {\n if (activeTransition !== transition)\n return;\n activeTransition = undefined;\n const cancelScheduled = transition.cancelScheduled;\n transition.cancelScheduled = undefined;\n try {\n cancelScheduled?.();\n }\n catch {\n // Preserve the transition failure rather than a scheduler cleanup error.\n }\n transition.candidate.release();\n const typed = findPretableReentrantMutationError(error) ??\n transitionError(error, transition.operation);\n state = Object.freeze({\n snapshot,\n status: Object.freeze({\n kind: \"error\",\n transitionId: transition.id,\n error: typed,\n }),\n });\n transition.reject(typed);\n };\n const scheduleTransition = (transition) => {\n transition.cancelScheduled = transitionRuntime.scheduler.schedule(() => {\n if (disposed || activeTransition !== transition)\n return;\n let changed = false;\n try {\n changed = guarded(transition.operation, () => {\n transition.cancelScheduled = undefined;\n return runTransitionSlice(transition);\n });\n }\n catch (error) {\n failTransition(transition, error);\n changed = true;\n }\n if (changed)\n notify();\n });\n };\n const runTransitionSlice = (transition) => {\n if (activeTransition !== transition || disposed)\n return false;\n try {\n const complete = runCooperativeTransitionSlice(transitionRuntime, () => transition.candidate.step());\n if (activeTransition !== transition || disposed)\n return false;\n if (!complete) {\n state = Object.freeze({\n snapshot,\n status: rebuildingStatus(transition),\n });\n scheduleTransition(transition);\n return true;\n }\n const previousRevision = root.revision;\n const revision = previousRevision + 1;\n const committedRoot = transition.candidate.finish(revision);\n activeTransition = undefined;\n const cancelScheduled = transition.cancelScheduled;\n transition.cancelScheduled = undefined;\n try {\n cancelScheduled?.();\n }\n catch {\n // Successful publication cannot be rolled back by advisory cleanup.\n }\n publishCommittedRoot(committedRoot, previousRevision, revision);\n transition.candidate.release();\n transition.resolve(revision);\n return true;\n }\n catch (error) {\n failTransition(transition, error);\n return true;\n }\n };\n const startTransition = (id, operation, nextPlan) => {\n cancelActiveTransition(\"superseded\");\n let resolve;\n let reject;\n const finished = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n // Mark internal lifecycle rejection as observed without changing the\n // original promise returned to callers or its await/rejection semantics.\n void finished.catch(() => undefined);\n const transition = {\n id,\n operation,\n candidate: createCooperativeTransitionCandidate({\n captured: root,\n queryPlan: nextPlan,\n aggregateFilteredRows,\n operation,\n instrumentation,\n }),\n finished,\n resolve,\n reject,\n cancelScheduled: undefined,\n };\n activeTransition = transition;\n state = Object.freeze({ snapshot, status: rebuildingStatus(transition) });\n runTransitionSlice(transition);\n return transition;\n };\n const appendTransitionDelta = (target, affectedRowIds) => {\n activeTransition?.candidate.append(Object.freeze({\n target,\n affectedRowIds: Object.freeze([...affectedRowIds]),\n }));\n };\n const cancelTransitionHandle = (id, operation) => {\n const cancelled = guarded(operation, () => {\n if (activeTransition?.id !== id)\n return false;\n cancelActiveTransition(\"cancelled\");\n state = Object.freeze({ snapshot, status: READY });\n return true;\n });\n if (cancelled)\n notify();\n };\n const applyExpansionDefault = (operation, policy, expansionOptions) => {\n try {\n const prepared = guarded(operation, () => {\n const previousRoot = root;\n const nextPolicy = Object.freeze({\n ...policy,\n });\n const preserve = expansionOptions?.preserveOverrides === true;\n const samePolicy = JSON.stringify(previousRoot.expansion.default) ===\n JSON.stringify(nextPolicy);\n if (samePolicy &&\n (preserve || previousRoot.expansion.overrides.size === 0)) {\n return {\n result: mutationResult(previousRoot.revision, previousRoot.revision),\n notify: false,\n };\n }\n let groups = getGroupIndex(previousRoot.visible);\n if (!preserve && groups !== undefined) {\n for (const [groupId] of previousRoot.expansion.overrides.entries()) {\n groups = setGroupOverride(groups, groupId, undefined, operation);\n }\n }\n const overrides = preserve\n ? previousRoot.expansion.overrides\n : createPersistentMap();\n const expansion = Object.freeze({\n default: nextPolicy,\n overrides,\n state: Object.freeze({\n default: nextPolicy,\n overrideCount: overrides.size,\n }),\n });\n const revision = previousRoot.revision + 1;\n const committedRoot = Object.freeze({\n ...previousRoot,\n revision,\n parentRevision: previousRoot.revision,\n visible: groups === undefined\n ? previousRoot.visible\n : attachGroupIndex(previousRoot.visible.rows, groups),\n expansion,\n });\n appendTransitionDelta(committedRoot, []);\n commit(committedRoot);\n changeJournal.appendBarrier(previousRoot.revision, revision);\n return {\n result: mutationResult(previousRoot.revision, revision),\n notify: true,\n };\n });\n if (prepared.notify)\n notify();\n return prepared.result;\n }\n catch (error) {\n throw remapOperationError(error, operation);\n }\n };\n const model = {\n getState: () => state,\n getColumns: () => columns,\n subscribe(listener) {\n if (disposed)\n return () => undefined;\n listeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed)\n return;\n subscribed = false;\n listeners.delete(listener);\n };\n },\n setRows(nextRows) {\n try {\n const prepared = guarded(\"set-rows\", () => {\n const previousRoot = root;\n let nextPlan = queryPlan;\n let drafted = replaceFlatRowsDraft({\n root: previousRoot,\n rows: nextRows,\n getRowId,\n queryPlan: nextPlan,\n nextSourceOrder,\n slots,\n instrumentation,\n });\n const pendingDiagnostics = drafted.diagnostics;\n if (drafted.sameReferenceMutation) {\n nextPlan = compileQuery({\n derivations,\n query,\n filterAuthority,\n sortAuthority,\n });\n /*\n * The recompile is a plan swap, so the fresh plan's sort-key\n * store must be filled for every surviving row — rows the draft\n * re-evaluates get overwritten with recomputed values right\n * after, and untouched rows carry their previous keys. Without\n * this, records carried into the committed root would be\n * unresolvable under the root's own plan.\n */\n for (const [, record] of previousRoot.rows.entries()) {\n fillSortKeysFromPrevious(nextPlan, queryPlan, record, instrumentation);\n }\n drafted = replaceFlatRowsDraft({\n root: previousRoot,\n rows: nextRows,\n getRowId,\n queryPlan: nextPlan,\n nextSourceOrder,\n acceptSameReferenceMutation: true,\n slots,\n instrumentation,\n });\n if (drafted.effective) {\n /*\n * The draft's visible index reuses trees whose comparators\n * captured the RETIRED plan, and that plan's store still holds\n * the pre-mutation keys for every in-place-mutated row object.\n * Rebuild the index under the fresh plan so every entry is\n * re-decorated with keys from the store that actually saw the\n * mutation. The draft emits no per-row operations, so the\n * rebuild is journal-invisible.\n */\n const records = [];\n // `range(0, size)`, not `entries()` — a full walk into an\n // array (see `iterateEntries`).\n for (const entry of drafted.sourceOrder.range(0, drafted.sourceOrder.size)) {\n const record = drafted.rows.get(entry.rowId);\n if (record !== undefined)\n records.push(record);\n }\n const rebuiltVisible = createVisibleIndex(records, nextPlan, aggregateFilteredRows, previousRoot.expansion.overrides);\n drafted = {\n ...drafted,\n visible: rebuiltVisible,\n // The rebuilt index resolves the same membership (same rows,\n // same query, fresh plan), but derive the bitset from the\n // tree that ships rather than carrying the draft's — the two\n // must never be allowed to drift.\n visibleSlots: nextPlan.query.rowGroups.length > 0\n ? EMPTY_MEMBERSHIP\n : membershipFromFlatTree(rebuiltVisible.rows, slots.capacity),\n };\n }\n }\n if (!drafted.effective) {\n return {\n result: mutationResult(previousRoot.revision, previousRoot.revision, drafted),\n notify: false,\n diagnostics: Object.freeze([]),\n };\n }\n const previousRevision = previousRoot.revision;\n const committedRoot = Object.freeze({\n revision: previousRevision + 1,\n parentRevision: previousRevision,\n rows: drafted.rows,\n sourceOrder: drafted.sourceOrder,\n recordsBySlot: drafted.recordsBySlot,\n // Commit-time capacity: nothing between the draft and this\n // commit allocates, so this is the capacity the vector above\n // was built for.\n slotCapacity: slots.capacity,\n visibleSlots: drafted.visibleSlots,\n visible: drafted.visible,\n queryPlan: nextPlan,\n expansion: previousRoot.expansion,\n cause: Object.freeze({ kind: \"set-rows\" }),\n });\n const result = mutationResult(previousRevision, committedRoot.revision, drafted);\n const distinctCommit = distinctValues.prepareCommit(committedRoot, drafted.affectedRowIds, \"set-rows\");\n queryPlan = nextPlan;\n nextSourceOrder = drafted.nextSourceOrder;\n appendTransitionDelta(committedRoot, drafted.affectedRowIds);\n commit(committedRoot);\n distinctValues.publishCommit(distinctCommit, committedRoot, drafted.affectedRowIds);\n changeJournal.appendBarrier(previousRevision, committedRoot.revision);\n return {\n result,\n notify: true,\n diagnostics: pendingDiagnostics,\n };\n });\n if (prepared.notify)\n notify();\n emitDiagnostics(prepared.diagnostics, diagnosticSink);\n return prepared.result;\n }\n catch (error) {\n throw remapSetRowsError(error);\n }\n },\n applyTransaction(transaction) {\n const prepared = guarded(\"apply-transaction\", () => {\n const previousRoot = root;\n const drafted = applyFlatTransactionDraft({\n root: previousRoot,\n transaction,\n getRowId,\n queryPlan,\n nextSourceOrder,\n slots,\n instrumentation,\n });\n const result = mutationResult(previousRoot.revision, drafted.effective ? previousRoot.revision + 1 : previousRoot.revision, drafted, drafted.issues);\n if (!drafted.effective) {\n return { result, notify: false, diagnostics: drafted.diagnostics };\n }\n const committedRoot = Object.freeze({\n revision: result.revision,\n parentRevision: previousRoot.revision,\n rows: drafted.rows,\n sourceOrder: drafted.sourceOrder,\n recordsBySlot: drafted.recordsBySlot,\n // Commit-time capacity (see the setRows commit above).\n slotCapacity: slots.capacity,\n visibleSlots: drafted.visibleSlots,\n visible: drafted.visible,\n queryPlan,\n expansion: previousRoot.expansion,\n cause: Object.freeze({ kind: \"set-rows\" }),\n });\n const distinctCommit = distinctValues.prepareCommit(committedRoot, drafted.affectedRowIds, \"apply-transaction\");\n nextSourceOrder = drafted.nextSourceOrder;\n appendTransitionDelta(committedRoot, drafted.affectedRowIds);\n commit(committedRoot);\n distinctValues.publishCommit(distinctCommit, committedRoot, drafted.affectedRowIds);\n changeJournal.appendChanges(previousRoot.revision, committedRoot.revision, drafted.operations);\n return { result, notify: true, diagnostics: drafted.diagnostics };\n });\n if (prepared.notify)\n notify();\n emitDiagnostics(prepared.diagnostics, diagnosticSink);\n return prepared.result;\n },\n setQuery(nextQuery) {\n const prepared = guarded(\"set-query\", () => {\n const id = nextTransitionId++;\n const nextPlan = compileQuery({\n derivations,\n query: nextQuery,\n previous: queryPlan,\n operation: \"set-query\",\n filterAuthority,\n sortAuthority,\n });\n if (nextPlan === queryPlan) {\n const superseded = cancelActiveTransition(\"superseded\") !== undefined;\n if (superseded)\n state = Object.freeze({ snapshot, status: READY });\n return {\n transition: Object.freeze({\n id,\n requestedQuery: queryPlan.query,\n finished: Promise.resolve(root.revision),\n cancel: () => cancelTransitionHandle(id, \"set-query\"),\n }),\n notify: superseded,\n };\n }\n // The two synchronous fast paths share one commit and error shape;\n // they differ only in the rebuild and the barrier reason, and each\n // reason is that path's exclusive promise. \"reorder\" is the sort\n // path's — the one commit that provably changes order and nothing\n // else. \"refilter\" is the filter path's — membership changed while\n // surviving rows kept their relative order and identities. Neither\n // may cross over: a \"reorder\" on a membership change would tell\n // renderers to permute retained rows over a different row set and\n // corrupt their layout, and vice versa.\n //\n // Each path is additionally size-gated (#488): the arc's bar is that\n // no single main-thread block exceeds 50ms, and both sync rebuilds\n // run on the caller's stack with cost bounded by the RESIDENT\n // population (exact for the filter rebuild's bulk verdict pass; an\n // upper bound for the sort rebuild, which sorts the visible set).\n // The count is `root.rows.size`, the committed population — never\n // `slotCapacity` (inflated by churn), and for the filter arm never\n // `visible.rows.size` (a widening filter would dispatch as\n // \"small\"). Above a path's measured limit the same change falls\n // through to the cooperative transition, which blocks ~0; the gate\n // only ever moves work from sync to cooperative. Grouped queries\n // stay first and never consult the count.\n const residentRowCount = root.rows.size;\n const fastPath = nextPlan.query.rowGroups.length > 0\n ? undefined\n : isSortOnlyChange(queryPlan, nextPlan)\n ? residentRowCount <= sortFastPathRowLimit\n ? Object.freeze({\n rebuild: rebuildRootForSortOnlyChange,\n barrierReason: \"reorder\",\n })\n : undefined\n : isFilterOnlyChange(queryPlan, nextPlan)\n ? residentRowCount <= filterFastPathRowLimit\n ? Object.freeze({\n rebuild: rebuildRootForFilterOnlyChange,\n barrierReason: \"refilter\",\n })\n : undefined\n : undefined;\n if (fastPath !== undefined) {\n cancelActiveTransition(\"superseded\");\n const previousRevision = root.revision;\n const revision = previousRevision + 1;\n let committedRoot;\n try {\n committedRoot = fastPath.rebuild({\n captured: root,\n nextPlan,\n revision,\n now: transitionRuntime.now,\n instrumentation,\n });\n }\n catch (error) {\n // Mirrors failTransition's observable semantics: an error status\n // carrying this transition's id, a rejected `finished`, and the\n // committed root left untouched.\n const typed = findPretableReentrantMutationError(error) ??\n transitionError(error, \"set-query\");\n state = Object.freeze({\n snapshot,\n status: Object.freeze({\n kind: \"error\",\n transitionId: id,\n error: typed,\n }),\n });\n const finished = Promise.reject(typed);\n void finished.catch(() => undefined);\n return {\n transition: Object.freeze({\n id,\n requestedQuery: nextPlan.query,\n finished,\n cancel: () => cancelTransitionHandle(id, \"set-query\"),\n }),\n notify: true,\n };\n }\n publishCommittedRoot(committedRoot, previousRevision, revision, fastPath.barrierReason);\n return {\n transition: Object.freeze({\n id,\n requestedQuery: nextPlan.query,\n finished: Promise.resolve(revision),\n cancel: () => cancelTransitionHandle(id, \"set-query\"),\n }),\n notify: true,\n };\n }\n const active = startTransition(id, \"set-query\", nextPlan);\n return {\n transition: Object.freeze({\n id,\n requestedQuery: nextPlan.query,\n finished: active.finished,\n cancel: () => cancelTransitionHandle(id, \"set-query\"),\n }),\n notify: true,\n };\n });\n if (prepared.notify)\n notify();\n return prepared.transition;\n },\n setDerivations(nextDerivations) {\n try {\n const prepared = guarded(\"set-derivations\", () => {\n const id = nextTransitionId++;\n const capturedPlan = compileQuery({\n derivations: nextDerivations,\n query,\n operation: \"set-derivations\",\n filterAuthority,\n sortAuthority,\n });\n const nextPlan = compileQuery({\n derivations: capturedPlan.derivations,\n query,\n previous: queryPlan,\n operation: \"set-derivations\",\n filterAuthority,\n sortAuthority,\n });\n if (nextPlan === queryPlan) {\n derivations = capturedPlan.derivations;\n distinctValues.publishTransitionRoot(root);\n const superseded = cancelActiveTransition(\"superseded\") !== undefined;\n if (superseded)\n state = Object.freeze({ snapshot, status: READY });\n return {\n transition: Object.freeze({\n id,\n requestedDerivations: capturedPlan.derivations,\n finished: Promise.resolve(root.revision),\n cancel: () => cancelTransitionHandle(id, \"set-derivations\"),\n }),\n notify: superseded,\n };\n }\n const active = startTransition(id, \"set-derivations\", nextPlan);\n return {\n transition: Object.freeze({\n id,\n requestedDerivations: nextPlan.derivations,\n finished: active.finished,\n cancel: () => cancelTransitionHandle(id, \"set-derivations\"),\n }),\n notify: true,\n };\n });\n if (prepared.notify)\n notify();\n return prepared.transition;\n }\n catch (error) {\n throw remapOperationError(error, \"set-derivations\");\n }\n },\n setGroupExpanded(groupId, expanded) {\n try {\n const prepared = guarded(\"set-group-expanded\", () => {\n const previousRoot = root;\n const groups = getGroupIndex(previousRoot.visible);\n const group = groups?.groups.get(groupId);\n if (groups === undefined || group === undefined) {\n return {\n result: mutationResult(previousRoot.revision, previousRoot.revision, { ignored: 1 }, [Object.freeze({ code: \"unknown-group-id\", groupId })]),\n notify: false,\n };\n }\n const defaultExpanded = previousRoot.expansion.default.kind === \"expanded\" ||\n (previousRoot.expansion.default.kind === \"through-depth\" &&\n group.depth <= previousRoot.expansion.default.depth);\n const override = expanded === defaultExpanded ? undefined : expanded;\n const current = previousRoot.expansion.overrides.get(groupId);\n const exists = previousRoot.expansion.overrides.has(groupId);\n if ((override === undefined && !exists) ||\n (override !== undefined && exists && current === override)) {\n return {\n result: mutationResult(previousRoot.revision, previousRoot.revision),\n notify: false,\n };\n }\n const overrides = override === undefined\n ? previousRoot.expansion.overrides.delete(groupId)\n : previousRoot.expansion.overrides.set(groupId, override);\n const nextGroups = setGroupOverride(groups, groupId, override, \"set-group-expanded\");\n const expansion = Object.freeze({\n default: previousRoot.expansion.default,\n overrides,\n state: Object.freeze({\n default: previousRoot.expansion.default,\n overrideCount: overrides.size,\n }),\n });\n const revision = previousRoot.revision + 1;\n const committedRoot = Object.freeze({\n ...previousRoot,\n revision,\n parentRevision: previousRoot.revision,\n visible: attachGroupIndex(previousRoot.visible.rows, nextGroups),\n expansion,\n });\n const previousSnapshot = snapshot;\n const nextSnapshot = createFlatSnapshot(committedRoot);\n const operations = expansionChangeOperations(previousSnapshot, nextSnapshot, groupId);\n appendTransitionDelta(committedRoot, []);\n commit(committedRoot);\n changeJournal.appendChanges(previousRoot.revision, revision, operations);\n return {\n result: mutationResult(previousRoot.revision, revision),\n notify: true,\n };\n });\n if (prepared.notify)\n notify();\n return prepared.result;\n }\n catch (error) {\n throw remapOperationError(error, \"set-group-expanded\");\n }\n },\n setExpansionDefault(policy, expansionOptions) {\n return applyExpansionDefault(\"set-expansion-default\", policy, expansionOptions);\n },\n expandAll() {\n return applyExpansionDefault(\"expand-all\", { kind: \"expanded\" });\n },\n collapseAll() {\n return applyExpansionDefault(\"collapse-all\", { kind: \"collapsed\" });\n },\n changesSince(revision) {\n assertCommandAllowed(\"changes-since\");\n return changeJournal.changesSince(revision, root.revision);\n },\n distinctValues(columnId, distinctOptions) {\n return guarded(\"distinct-values\", () => distinctValues.query(columnId, distinctOptions));\n },\n dispose() {\n if (activeMutation !== undefined) {\n throw new PretableReentrantMutationError(\"dispose\", activeMutation);\n }\n if (disposed)\n return;\n const current = guarded(\"dispose\", () => {\n cancelActiveTransition(\"disposed\");\n distinctValues.dispose(new PretableDisposedModelError(\"distinct-values\"));\n changeJournal.clear();\n disposed = true;\n state = Object.freeze({ snapshot, status: DISPOSED });\n if (instrumentation !== undefined)\n instrumentation.currentRevisionRoot = root;\n const captured = Array.from(listeners);\n listeners.clear();\n return captured;\n });\n for (const listener of current) {\n try {\n listener();\n }\n catch {\n // Disposal still detaches and wakes every listener exactly once.\n }\n }\n },\n };\n // Construction has no subscribers. Future ingestion diagnostics, if any,\n // are delivered only after the initial immutable state and model exist.\n modelChangeJournals.set(model, changeJournal);\n modelRevisionCauses.set(model, () => root.cause);\n modelActiveTransitionCandidates.set(model, () => activeTransition?.candidate);\n modelSlotInternals.set(model, () => ({ root: root, slots }));\n /*\n * Re-running `setQuery` with the query the model already holds is what makes\n * the flip take effect: the query is unchanged, so nothing reported moves,\n * while the plan differs by authority alone and `semanticallyMatches` now\n * refuses to reuse it. The rebuild is the ordinary cooperative transition,\n * cancellation and status included.\n */\n modelFilterAuthoritySetters.set(model, (authority) => {\n if (disposed || authority === filterAuthority)\n return;\n filterAuthority = authority;\n const transition = model.setQuery(query);\n void transition.finished.catch(() => undefined);\n });\n modelSortAuthoritySetters.set(model, (authority) => {\n if (disposed || authority === sortAuthority)\n return;\n sortAuthority = authority;\n const transition = model.setQuery(query);\n void transition.finished.catch(() => undefined);\n });\n distinctValues.attachModel(model);\n emitDiagnostics(initialStore.diagnostics, diagnosticSink);\n return model;\n}\n","/**\n * Per-column aggregate OVERRIDES, applied to a derivation list.\n *\n * grid-core stores what a tool panel chose (`PretableGridUiState`'s\n * `columnAggregates`); row-model resolves what an aggregate MEANS. Both layers\n * CAN see both halves — `createGridUiCore` takes a `rowModel` and that\n * interface exposes `setDerivations` — so this is a layering choice, not an\n * impossibility: row-model must not depend on grid-core's state shape, and\n * grid-core deliberately drives no derivations at all (it never calls\n * `setDerivations`). The merge is therefore a pure function that a composing\n * layer calls with both inputs, and the merged list travels the ordinary\n * `setDerivations` / `compileQuery` path from there.\n */\n/**\n * Apply `overrides` on top of the `aggregate` each derivation declares.\n *\n * IDS ARE THE SCHEMA VOCABULARY — the `id` on the derivations themselves, the\n * same ids `PretableQueryFor` and `RuntimeColumn` use. grid-core keys\n * `columnAggregates` by the LAYOUT column vocabulary instead (see its doc on\n * `PretableGridUiState.columnAggregates`), so a caller reading that state owes\n * the translation before calling this. Nothing in the signature enforces that:\n * both vocabularies are `string`, so the fence is this sentence.\n *\n * An override LAYER, not a replacement: a derivation whose id is absent from\n * `overrides` keeps whatever it declared, so clearing an override — which\n * strips the key rather than storing `undefined` — restores the declared\n * value. A key carrying `undefined` is likewise treated as no override, so\n * `undefined` never acquires a second meaning here. `null` is the value that\n * says \"draw NO aggregate for a column whose prop declares one\": the merge\n * strips the declared `aggregate` from that derivation, so `compileQuery`\n * never sees the sentinel and validates nothing new.\n *\n * An override for an id no derivation carries is ignored, never appended: this\n * function only ever rewrites the `aggregate` of derivations it was given, and\n * preserves their order, so a merged list stays positionally comparable with\n * the one it came from — which is what `derivationsEqualForPlan` needs to\n * decide plan reuse.\n *\n * TYPES DESCRIBE THE DECLARED SHAPE, NOT THE MERGED ONE. An override arrives\n * as `unknown`, so the returned list keeps the input's type: a column that\n * declared no `aggregate` but carries an override aggregates at runtime while\n * its type still says it does not, and an override of a different output type\n * is invisible to `PretableAggregatesFor`. The alternative — inferring a new\n * derivation type per override — cannot work off state grid-core stores as\n * `unknown`.\n *\n * IDENTITY: returns the INPUT ARRAY ITSELF when nothing applies, so a caller\n * memoising on identity (React) does not re-request derivations every render;\n * that covers a restated override too, since an override `Object.is`-equal to\n * the declared value changes nothing. It is NOT idempotent on the applying\n * path: two calls with equal inputs return two DISTINCT arrays whenever any\n * override actually applies. A React caller must therefore `useMemo` the merge\n * on `[derivations, overrides]` and hold the MERGED array as its\n * last-requested value, rather than calling this inline inside the effect that\n * compares against it — otherwise every render looks like a change and pays a\n * `compileQuery` before concluding no-op. That memo is sound because\n * grid-core's `columnAggregates` object identity is stable across publishes\n * that do not touch it.\n *\n * @public\n */\nexport function mergeColumnAggregateOverrides(derivations, overrides) {\n let changed = false;\n const merged = derivations.map((derivation) => {\n if (!Object.hasOwn(overrides, derivation.id))\n return derivation;\n const aggregate = overrides[derivation.id];\n if (aggregate === undefined)\n return derivation;\n const declared = derivation.aggregate;\n if (aggregate === null) {\n // The \"no aggregate\" sentinel: strip what the prop declared. A column\n // that declares none is already there — identity, not a change. That\n // covers an own `aggregate: undefined` key too: every consumer reads\n // the value, never key presence, so stripping it would churn identity\n // over a semantic no-op.\n if (declared === undefined)\n return derivation;\n changed = true;\n // Copy + delete rather than rest-destructuring: this repo's\n // no-unused-vars rule has no rest-sibling exemption.\n const stripped = { ...derivation };\n delete stripped.aggregate;\n return stripped;\n }\n if (Object.is(declared, aggregate))\n return derivation;\n changed = true;\n return { ...derivation, aggregate };\n });\n return changed ? merged : derivations;\n}\n","const MAX_REPRESENTATIVE_LEAVES = 8;\nconst DEVELOPMENT = process.env.NODE_ENV !== \"production\";\nfunction sameLeafId(left, right) {\n return left === right || (left !== left && right !== right);\n}\nfunction clonedContext(context) {\n return {\n leftToRight: new Map(context.leftToRight),\n rightToLeft: new Map(context.rightToLeft),\n };\n}\nfunction commitContext(target, source) {\n target.leftToRight = source.leftToRight;\n target.rightToLeft = source.rightToLeft;\n}\nfunction equalBytes(left, right) {\n if (left.byteLength !== right.byteLength)\n return false;\n const leftBytes = new Uint8Array(left.buffer, left.byteOffset, left.byteLength);\n const rightBytes = new Uint8Array(right.buffer, right.byteOffset, right.byteLength);\n return leftBytes.every((value, index) => value === rightBytes[index]);\n}\nfunction boxedPrimitiveValue(value) {\n switch (Object.prototype.toString.call(value)) {\n case \"[object Boolean]\":\n return Boolean.prototype.valueOf.call(value);\n case \"[object Number]\":\n return Number.prototype.valueOf.call(value);\n case \"[object String]\":\n return String.prototype.valueOf.call(value);\n case \"[object BigInt]\":\n return BigInt.prototype.valueOf.call(value);\n case \"[object Symbol]\":\n return Symbol.prototype.valueOf.call(value);\n default:\n return undefined;\n }\n}\nfunction structuredEqual(left, right, context) {\n if (Object.is(left, right))\n return true;\n if (left === null ||\n right === null ||\n typeof left !== \"object\" ||\n typeof right !== \"object\") {\n return false;\n }\n const knownRight = context.leftToRight.get(left);\n if (knownRight !== undefined)\n return knownRight === right;\n const knownLeft = context.rightToLeft.get(right);\n if (knownLeft !== undefined)\n return knownLeft === left;\n if (Object.getPrototypeOf(left) !== Object.getPrototypeOf(right))\n return false;\n const leftBoxed = boxedPrimitiveValue(left);\n const rightBoxed = boxedPrimitiveValue(right);\n if (leftBoxed !== undefined || rightBoxed !== undefined) {\n return Object.is(leftBoxed, rightBoxed);\n }\n if (left instanceof Date && right instanceof Date) {\n return Object.is(left.getTime(), right.getTime());\n }\n if (left instanceof RegExp && right instanceof RegExp) {\n return (left.source === right.source &&\n left.flags === right.flags &&\n left.lastIndex === right.lastIndex);\n }\n if (left instanceof ArrayBuffer && right instanceof ArrayBuffer) {\n return equalBytes(new Uint8Array(left), new Uint8Array(right));\n }\n if (typeof SharedArrayBuffer !== \"undefined\" &&\n left instanceof SharedArrayBuffer &&\n right instanceof SharedArrayBuffer) {\n return equalBytes(new Uint8Array(left), new Uint8Array(right));\n }\n if (ArrayBuffer.isView(left) && ArrayBuffer.isView(right)) {\n return equalBytes(left, right);\n }\n context.leftToRight.set(left, right);\n context.rightToLeft.set(right, left);\n if (left instanceof Map && right instanceof Map) {\n if (left.size !== right.size)\n return false;\n const unmatched = [...right.entries()];\n for (const [leftKey, leftValue] of left) {\n let matched = false;\n for (let index = 0; index < unmatched.length; index += 1) {\n const rightEntry = unmatched[index];\n const trial = clonedContext(context);\n if (structuredEqual(leftKey, rightEntry[0], trial) &&\n structuredEqual(leftValue, rightEntry[1], trial)) {\n commitContext(context, trial);\n unmatched.splice(index, 1);\n matched = true;\n break;\n }\n }\n if (!matched)\n return false;\n }\n return true;\n }\n if (left instanceof Set && right instanceof Set) {\n if (left.size !== right.size)\n return false;\n const unmatched = [...right.values()];\n for (const leftValue of left) {\n let matched = false;\n for (let index = 0; index < unmatched.length; index += 1) {\n const trial = clonedContext(context);\n if (structuredEqual(leftValue, unmatched[index], trial)) {\n commitContext(context, trial);\n unmatched.splice(index, 1);\n matched = true;\n break;\n }\n }\n if (!matched)\n return false;\n }\n return true;\n }\n const leftKeys = Reflect.ownKeys(left);\n const rightKeys = Reflect.ownKeys(right);\n if (leftKeys.length !== rightKeys.length)\n return false;\n for (const key of leftKeys) {\n if (!Object.prototype.hasOwnProperty.call(right, key))\n return false;\n const leftDescriptor = Object.getOwnPropertyDescriptor(left, key);\n const rightDescriptor = Object.getOwnPropertyDescriptor(right, key);\n if (leftDescriptor === undefined || rightDescriptor === undefined)\n return false;\n if (leftDescriptor.enumerable !== rightDescriptor.enumerable ||\n leftDescriptor.configurable !== rightDescriptor.configurable) {\n return false;\n }\n const leftIsData = \"value\" in leftDescriptor;\n const rightIsData = \"value\" in rightDescriptor;\n if (leftIsData !== rightIsData)\n return false;\n if (leftIsData && rightIsData) {\n if (!structuredEqual(leftDescriptor.value, rightDescriptor.value, context)) {\n return false;\n }\n }\n else if (leftDescriptor.get !== rightDescriptor.get ||\n leftDescriptor.set !== rightDescriptor.set) {\n return false;\n }\n }\n return true;\n}\n/** Compares scalar and common structured finalized outputs by value. */\nexport function defaultAggregatorOutputEquality(left, right) {\n return structuredEqual(left, right, {\n leftToRight: new Map(),\n rightToLeft: new Map(),\n });\n}\nconst productionValidator = Object.freeze({\n observe: () => undefined,\n});\n/**\n * Creates development-only validation for the custom aggregator merge law.\n * Production replacements of `process.env.NODE_ENV` eliminate the sampling\n * branch, and the runtime fallback is a shared no-op validator.\n */\nexport function createAggregatorLawValidator(options) {\n if (!DEVELOPMENT)\n return productionValidator;\n const states = new WeakMap();\n const equals = options.equals ?? defaultAggregatorOutputEquality;\n return {\n observe(observation) {\n const aggregatorObject = observation.aggregator;\n let columns = states.get(aggregatorObject);\n if (columns === undefined) {\n columns = new Map();\n states.set(aggregatorObject, columns);\n }\n let state = columns.get(observation.columnId);\n if (state === undefined) {\n state = { samples: [], warned: false };\n columns.set(observation.columnId, state);\n }\n if (state.warned)\n return;\n const existingIndex = state.samples.findIndex((sample) => sameLeafId(sample.id, observation.leafId));\n if (existingIndex >= 0) {\n state.samples[existingIndex] = {\n id: observation.leafId,\n row: observation.row,\n value: observation.value,\n };\n }\n else {\n if (state.samples.length >= MAX_REPRESENTATIVE_LEAVES)\n return;\n state.samples.push({\n id: observation.leafId,\n row: observation.row,\n value: observation.value,\n });\n }\n if (state.samples.length < 2)\n return;\n const aggregator = observation.aggregator;\n try {\n let sequential = aggregator.init();\n const partitions = [];\n for (const sample of state.samples) {\n sequential = aggregator.accumulate(sequential, sample.value, sample.row);\n partitions.push(aggregator.accumulate(aggregator.init(), sample.value, sample.row));\n }\n let merged = partitions[0];\n for (let index = 1; index < partitions.length; index += 1) {\n merged = aggregator.merge(merged, partitions[index]);\n }\n const sequentialOutput = aggregator.finalize(sequential);\n const mergedOutput = aggregator.finalize(merged);\n if (equals(sequentialOutput, mergedOutput))\n return;\n state.warned = true;\n options.sink({\n code: \"aggregator-law-violation\",\n law: \"sequential-vs-merged-one-row-partitions\",\n columnId: observation.columnId,\n sampleSize: state.samples.length,\n sequentialOutput,\n mergedOutput,\n });\n }\n catch {\n // Development diagnostics must not add a new failure mode to updates.\n }\n },\n };\n}\n","import {\n createColumnHelper as createInternalColumnHelper,\n type PretableColumnHelper,\n} from \"@pretable-internal/row-model\";\n\n/**\n * Creates a typed column-definition helper for an ordinary row object.\n *\n * @public\n */\nexport function createColumnHelper<\n TRow extends object,\n>(): PretableColumnHelper<TRow> {\n return createInternalColumnHelper<TRow>();\n}\n","import {\n createLocalRowModel as createInternalLocalRowModel,\n type CreateLocalRowModelOptions as InternalCreateLocalRowModelOptions,\n type PretableDerivationsFor,\n type PretableExpansionDefault,\n type PretableQueryFor,\n type Prettify,\n type PretableRowId,\n type PretableRowModel,\n} from \"@pretable-internal/row-model\";\n\n/** Options for a local row model with an explicit row-ID accessor. @public */\nexport interface CreateLocalRowModelOptions<\n TColumns,\n TRowId extends PretableRowId,\n> {\n readonly rows: readonly (TColumns extends readonly [\n infer TFirstColumn,\n ...(readonly unknown[]),\n ]\n ? TFirstColumn extends {\n readonly accessor: (row: infer TRow extends object) => infer TValue;\n }\n ? [TValue] extends [unknown]\n ? TRow\n : never\n : never\n : never)[];\n readonly columns: TColumns & {\n readonly [K in keyof TColumns]: TColumns[K] extends {\n readonly accessor: (\n row: infer TColumnRow extends object,\n ) => infer TColumnValue;\n }\n ? [TColumnValue] extends [unknown]\n ? TColumns extends readonly [\n infer TFirstColumn,\n ...(readonly unknown[]),\n ]\n ? TFirstColumn extends {\n readonly accessor: (\n row: infer TFirstRow extends object,\n ) => infer TFirstValue;\n }\n ? [TFirstValue] extends [unknown]\n ? [TColumnRow] extends [TFirstRow]\n ? [TFirstRow] extends [TColumnRow]\n ? TColumns[K]\n : never\n : never\n : never\n : never\n : never\n : never\n : never;\n };\n readonly derivations?: PretableDerivationsFor<TColumns>;\n readonly query?: PretableQueryFor<TColumns>;\n readonly initialExpansion?: PretableExpansionDefault;\n readonly aggregateFilteredRows?: boolean;\n readonly getRowId: (\n row: TColumns extends readonly [infer TFirstColumn, ...(readonly unknown[])]\n ? TFirstColumn extends {\n readonly accessor: (row: infer TRow extends object) => infer TValue;\n }\n ? [TValue] extends [unknown]\n ? TRow\n : never\n : never\n : never,\n ) => TRowId;\n}\n\n/** Options for a local row model using the conventional `row.id`. @public */\nexport type CreateLocalRowModelWithDefaultIdOptions<TColumns> = (\n TColumns extends readonly [infer TFirstColumn, ...(readonly unknown[])]\n ? TFirstColumn extends {\n readonly accessor: (row: infer TRow extends object) => infer TValue;\n }\n ? [TValue] extends [unknown]\n ? TRow\n : never\n : never\n : never\n) extends { readonly id: PretableRowId }\n ? Prettify<{\n readonly rows: readonly (TColumns extends readonly [\n infer TFirstColumn,\n ...(readonly unknown[]),\n ]\n ? TFirstColumn extends {\n readonly accessor: (row: infer TRow extends object) => infer TValue;\n }\n ? [TValue] extends [unknown]\n ? TRow\n : never\n : never\n : never)[];\n readonly columns: TColumns & {\n readonly [K in keyof TColumns]: TColumns[K] extends {\n readonly accessor: (\n row: infer TColumnRow extends object,\n ) => infer TColumnValue;\n }\n ? [TColumnValue] extends [unknown]\n ? TColumns extends readonly [\n infer TFirstColumn,\n ...(readonly unknown[]),\n ]\n ? TFirstColumn extends {\n readonly accessor: (\n row: infer TFirstRow extends object,\n ) => infer TFirstValue;\n }\n ? [TFirstValue] extends [unknown]\n ? [TColumnRow] extends [TFirstRow]\n ? [TFirstRow] extends [TColumnRow]\n ? TColumns[K]\n : never\n : never\n : never\n : never\n : never\n : never\n : never;\n };\n readonly derivations?: PretableDerivationsFor<TColumns>;\n readonly query?: PretableQueryFor<TColumns>;\n readonly initialExpansion?: PretableExpansionDefault;\n readonly aggregateFilteredRows?: boolean;\n readonly getRowId?: undefined;\n }>\n : never;\n\n/**\n * Creates a local row model using the conventional `row.id` field.\n *\n * @public\n */\nexport function createLocalRowModel<\n const TColumns extends readonly [unknown, ...(readonly unknown[])],\n>(\n options: CreateLocalRowModelWithDefaultIdOptions<TColumns>,\n): PretableRowModel<\n CreateLocalRowModelWithDefaultIdOptions<TColumns>[\"rows\"][number],\n CreateLocalRowModelWithDefaultIdOptions<TColumns>[\"rows\"][number] extends {\n readonly id: infer TRowId extends PretableRowId;\n }\n ? TRowId\n : never,\n TColumns\n>;\n/**\n * Creates a local row model using an explicit string or number row ID.\n *\n * @public\n */\nexport function createLocalRowModel<\n const TColumns extends readonly [unknown, ...(readonly unknown[])],\n const TRowId extends PretableRowId,\n>(\n options: CreateLocalRowModelOptions<TColumns, TRowId>,\n): PretableRowModel<\n CreateLocalRowModelOptions<TColumns, TRowId>[\"rows\"][number],\n TRowId,\n TColumns\n>;\nexport function createLocalRowModel<\n const TColumns extends readonly unknown[],\n const TRowId extends PretableRowId,\n>(\n options:\n | CreateLocalRowModelWithDefaultIdOptions<TColumns>\n | CreateLocalRowModelOptions<TColumns, TRowId>,\n): unknown {\n return createInternalLocalRowModel(\n options as unknown as InternalCreateLocalRowModelOptions<TColumns, TRowId>,\n );\n}\n","/**\n * Options for Pretable's currency number-format presets.\n *\n * @public\n */\nexport type PretableCurrencyFormatOptions = Omit<\n Intl.NumberFormatOptions,\n \"style\" | \"currency\" | \"currencySign\"\n> & {\n currency: string;\n};\n\nfunction currencyOptions(\n options: PretableCurrencyFormatOptions,\n currencySign: \"standard\" | \"accounting\",\n): Intl.NumberFormatOptions {\n return {\n ...options,\n style: \"currency\",\n currency: options.currency,\n currencySign,\n };\n}\n\n/**\n * Native number-format presets for money and accounting presentation.\n *\n * @public\n */\nexport const numberFormats = {\n money(options: PretableCurrencyFormatOptions): Intl.NumberFormatOptions {\n return currencyOptions(options, \"standard\");\n },\n accounting(options: PretableCurrencyFormatOptions): Intl.NumberFormatOptions {\n return currencyOptions(options, \"accounting\");\n },\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,SAAgB,sBAAsB,UAAU;CAC5C,OAAO,IAAI,YAAa,WAAW,OAAQ,CAAC;AAChD;;AAEA,SAAgB,qBAAqB,MAAM,UAAU;CACjD,MAAM,QAAQ,KAAK,IAAI,KAAK,QAAS,WAAW,OAAQ,CAAC;CACzD,MAAM,OAAO,IAAI,YAAY,KAAK;CAClC,KAAK,IAAI,IAAI;CACb,OAAO;AACX;AACA,SAAgB,YAAY,MAAM,MAAM;CACpC,KAAK,SAAS,MAAM,MAAM,OAAO;AACrC;AACA,SAAgB,cAAc,MAAM,MAAM;CACtC,KAAK,SAAS,MAAM,EAAE,MAAM,OAAO;AACvC;;AAEA,SAAgB,aAAa,MAAM,MAAM;CACrC,MAAM,OAAO,KAAK,SAAS;CAC3B,OAAO,SAAS,SAAY,SAAU,UAAU,OAAO,MAAO,OAAO;AACzE;;;;AC9BA,IAAIA;AAEJ,SAAS,WAAW,iBAAiB,GAAG;CACpC,OAAO;EACH,cAAc;EACd;EACA,iBAAiB;EACjB,qBAAqB;EACrB,2BAA2B;EAC3B,wBAAwB;EACxB,iBAAiB;EACjB,sBAAsB;EACtB,0BAA0B;EAC1B,uBAAuB;EACvB,yBAAyB;EACzB,wBAAwB;CAC5B;AACJ;AAEA,MAAM,mBAAmB,OAAO,OAAO,gBAAgB,CAAC,CAAC;AACzD,IAAa,qCAAb,cAAwD,MAAM;CAE1D,YAAY,MAAM,SAAS;EACvB,MAAM,OAAO;wBAFjB;EAGI,KAAK,OAAO;EACZ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