@powerhousedao/reactor-hypercore 6.2.3-dev.44 → 6.2.3-dev.46

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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["trim"],"sources":["../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/object-utils.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/identifier-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/schemable-identifier-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/alias-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/table-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-source.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-modifier-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/and-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/or-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/on-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/join-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/binary-operation-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operator-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/column-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-all-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/reference-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-reference-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-item-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/raw-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/collate-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/order-by-item-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/log-once.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/order-by-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-reference-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-operator-chain-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/reference-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/primitive-value-list-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-list-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/value-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/value-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/parens-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/binary-operation-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/order-by-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/over-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/from-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/having-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/insert-query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/list-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/update-query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/using-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/delete-query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/where-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/returning-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/explain-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/when-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/merge-query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/output-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/select-query-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/join-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/partition-by-item-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/partition-by-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/over-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/selection-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/select-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/no-result-error.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/top-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/top-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/limit-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/random-string.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/query-id.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/require-all-props.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/operation-node-transformer.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-transformer.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/plugin/with-schema/with-schema-plugin.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/deferred.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/util/provide-controlled-connection.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/query-executor-base.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-executor/noop-query-executor.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/parse-utils.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/join-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/offset-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/group-by-item-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/group-by-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/set-operation-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/set-operation-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-wrapper.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/fetch-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/fetch-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/select-query-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/aggregate-function-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/function-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/aggregate-function-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/function-module.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/unary-operation-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/unary-operation-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/case-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/case-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/json-path-leg-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/query-builder/json-path-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/tuple-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/data-type-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/data-type-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/operation-node/cast-node.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/expression/expression-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/expression-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/dynamic/dynamic-table-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/parser/table-parser.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/raw-builder.js","../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/raw-builder/sql.js","../../reactor/dist/forwarding-logger-BKDP4JnD.js","../src/hypercore-atomic-transaction.ts","../src/key-encoding.ts","../src/hypercore-operation-store.ts","../src/storage-manager.ts"],"sourcesContent":["/// <reference types=\"./object-utils.d.ts\" />\nexport function isEmpty(obj) {\n if (Array.isArray(obj) || isString(obj) || isBuffer(obj)) {\n return obj.length === 0;\n }\n else if (obj) {\n return Object.keys(obj).length === 0;\n }\n return false;\n}\nexport function isUndefined(obj) {\n return typeof obj === 'undefined' || obj === undefined;\n}\nexport function isString(obj) {\n return typeof obj === 'string';\n}\nexport function isNumber(obj) {\n return typeof obj === 'number';\n}\nexport function isBoolean(obj) {\n return typeof obj === 'boolean';\n}\nexport function isNull(obj) {\n return obj === null;\n}\nexport function isDate(obj) {\n return obj instanceof Date;\n}\nexport function isBigInt(obj) {\n return typeof obj === 'bigint';\n}\n// Don't change the returnd type to `obj is Buffer` to not create a\n// hard dependency to node.\nexport function isBuffer(obj) {\n return typeof Buffer !== 'undefined' && Buffer.isBuffer(obj);\n}\nexport function isFunction(obj) {\n return typeof obj === 'function';\n}\nexport function isObject(obj) {\n return typeof obj === 'object' && obj !== null;\n}\nexport function isArrayBufferOrView(obj) {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\nexport function isPlainObject(obj) {\n if (!isObject(obj) || getTag(obj) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(obj) === null) {\n return true;\n }\n let proto = obj;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(obj) === proto;\n}\nexport function getLast(arr) {\n return arr[arr.length - 1];\n}\nexport function freeze(obj) {\n return Object.freeze(obj);\n}\nexport function asArray(arg) {\n if (isReadonlyArray(arg)) {\n return arg;\n }\n else {\n return [arg];\n }\n}\nexport function asReadonlyArray(arg) {\n if (isReadonlyArray(arg)) {\n return arg;\n }\n else {\n return freeze([arg]);\n }\n}\nexport function isReadonlyArray(arg) {\n return Array.isArray(arg);\n}\nexport function noop(obj) {\n return obj;\n}\nexport function compare(obj1, obj2) {\n if (isReadonlyArray(obj1) && isReadonlyArray(obj2)) {\n return compareArrays(obj1, obj2);\n }\n else if (isObject(obj1) && isObject(obj2)) {\n return compareObjects(obj1, obj2);\n }\n return obj1 === obj2;\n}\nfunction compareArrays(arr1, arr2) {\n if (arr1.length !== arr2.length) {\n return false;\n }\n for (let i = 0; i < arr1.length; ++i) {\n if (!compare(arr1[i], arr2[i])) {\n return false;\n }\n }\n return true;\n}\nfunction compareObjects(obj1, obj2) {\n if (isBuffer(obj1) && isBuffer(obj2)) {\n return compareBuffers(obj1, obj2);\n }\n else if (isDate(obj1) && isDate(obj2)) {\n return compareDates(obj1, obj2);\n }\n return compareGenericObjects(obj1, obj2);\n}\nfunction compareBuffers(buf1, buf2) {\n return Buffer.compare(buf1, buf2) === 0;\n}\nfunction compareDates(date1, date2) {\n return date1.getTime() === date2.getTime();\n}\nfunction compareGenericObjects(obj1, obj2) {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length) {\n return false;\n }\n for (const key of keys1) {\n if (!compare(obj1[key], obj2[key])) {\n return false;\n }\n }\n return true;\n}\nconst toString = Object.prototype.toString;\nfunction getTag(value) {\n if (value == null) {\n return value === undefined ? '[object Undefined]' : '[object Null]';\n }\n return toString.call(value);\n}\n","/// <reference types=\"./identifier-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const IdentifierNode = freeze({\n is(node) {\n return node.kind === 'IdentifierNode';\n },\n create(name) {\n return freeze({\n kind: 'IdentifierNode',\n name,\n });\n },\n});\n","/// <reference types=\"./schemable-identifier-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const SchemableIdentifierNode = freeze({\n is(node) {\n return node.kind === 'SchemableIdentifierNode';\n },\n create(identifier) {\n return freeze({\n kind: 'SchemableIdentifierNode',\n identifier: IdentifierNode.create(identifier),\n });\n },\n createWithSchema(schema, identifier) {\n return freeze({\n kind: 'SchemableIdentifierNode',\n schema: IdentifierNode.create(schema),\n identifier: IdentifierNode.create(identifier),\n });\n },\n});\n","/// <reference types=\"./alias-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AliasNode = freeze({\n is(node) {\n return node.kind === 'AliasNode';\n },\n create(node, alias) {\n return freeze({\n kind: 'AliasNode',\n node,\n alias,\n });\n },\n});\n","/// <reference types=\"./table-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { SchemableIdentifierNode } from './schemable-identifier-node.js';\n/**\n * @internal\n */\nexport const TableNode = freeze({\n is(node) {\n return node.kind === 'TableNode';\n },\n create(table) {\n return freeze({\n kind: 'TableNode',\n table: SchemableIdentifierNode.create(table),\n });\n },\n createWithSchema(schema, table) {\n return freeze({\n kind: 'TableNode',\n table: SchemableIdentifierNode.createWithSchema(schema, table),\n });\n },\n});\n","/// <reference types=\"./operation-node-source.d.ts\" />\nimport { isFunction, isObject } from '../util/object-utils.js';\nexport function isOperationNodeSource(obj) {\n return isObject(obj) && isFunction(obj.toOperationNode);\n}\n","/// <reference types=\"./expression.d.ts\" />\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport function isExpression(obj) {\n return isObject(obj) && 'expressionType' in obj && isOperationNodeSource(obj);\n}\nexport function isAliasedExpression(obj) {\n return (isObject(obj) &&\n 'expression' in obj &&\n isString(obj.alias) &&\n isOperationNodeSource(obj));\n}\n","/// <reference types=\"./select-modifier-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SelectModifierNode = freeze({\n is(node) {\n return node.kind === 'SelectModifierNode';\n },\n create(modifier, of) {\n return freeze({\n kind: 'SelectModifierNode',\n modifier,\n of,\n });\n },\n createWithExpression(modifier) {\n return freeze({\n kind: 'SelectModifierNode',\n rawModifier: modifier,\n });\n },\n});\n","/// <reference types=\"./and-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const AndNode = freeze({\n is(node) {\n return node.kind === 'AndNode';\n },\n create(left, right) {\n return freeze({\n kind: 'AndNode',\n left,\n right,\n });\n },\n});\n","/// <reference types=\"./or-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrNode = freeze({\n is(node) {\n return node.kind === 'OrNode';\n },\n create(left, right) {\n return freeze({\n kind: 'OrNode',\n left,\n right,\n });\n },\n});\n","/// <reference types=\"./on-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const OnNode = freeze({\n is(node) {\n return node.kind === 'OnNode';\n },\n create(filter) {\n return freeze({\n kind: 'OnNode',\n on: filter,\n });\n },\n cloneWithOperation(onNode, operator, operation) {\n return freeze({\n ...onNode,\n on: operator === 'And'\n ? AndNode.create(onNode.on, operation)\n : OrNode.create(onNode.on, operation),\n });\n },\n});\n","/// <reference types=\"./join-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { OnNode } from './on-node.js';\n/**\n * @internal\n */\nexport const JoinNode = freeze({\n is(node) {\n return node.kind === 'JoinNode';\n },\n create(joinType, table) {\n return freeze({\n kind: 'JoinNode',\n joinType,\n table,\n on: undefined,\n });\n },\n createWithOn(joinType, table, on) {\n return freeze({\n kind: 'JoinNode',\n joinType,\n table,\n on: OnNode.create(on),\n });\n },\n cloneWithOn(joinNode, operation) {\n return freeze({\n ...joinNode,\n on: joinNode.on\n ? OnNode.cloneWithOperation(joinNode.on, 'And', operation)\n : OnNode.create(operation),\n });\n },\n});\n","/// <reference types=\"./binary-operation-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const BinaryOperationNode = freeze({\n is(node) {\n return node.kind === 'BinaryOperationNode';\n },\n create(leftOperand, operator, rightOperand) {\n return freeze({\n kind: 'BinaryOperationNode',\n leftOperand,\n operator,\n rightOperand,\n });\n },\n});\n","/// <reference types=\"./operator-node.d.ts\" />\nimport { freeze, isString } from '../util/object-utils.js';\nexport const COMPARISON_OPERATORS = [\n '=',\n '==',\n '!=',\n '<>',\n '>',\n '>=',\n '<',\n '<=',\n 'in',\n 'not in',\n 'is',\n 'is not',\n 'like',\n 'not like',\n 'match',\n 'ilike',\n 'not ilike',\n '@>',\n '<@',\n '^@',\n '&&',\n '?',\n '?&',\n '?|',\n '!<',\n '!>',\n '<=>',\n '!~',\n '~',\n '~*',\n '!~*',\n '@@',\n '@@@',\n '!!',\n '<->',\n 'regexp',\n 'is distinct from',\n 'is not distinct from',\n];\nexport const ARITHMETIC_OPERATORS = [\n '+',\n '-',\n '*',\n '/',\n '%',\n '^',\n '&',\n '|',\n '#',\n '<<',\n '>>',\n];\nexport const JSON_OPERATORS = ['->', '->>'];\nexport const BINARY_OPERATORS = [\n ...COMPARISON_OPERATORS,\n ...ARITHMETIC_OPERATORS,\n '&&',\n '||',\n];\nexport const UNARY_FILTER_OPERATORS = ['exists', 'not exists'];\nexport const UNARY_OPERATORS = ['not', '-', ...UNARY_FILTER_OPERATORS];\nexport const OPERATORS = [\n ...BINARY_OPERATORS,\n ...JSON_OPERATORS,\n ...UNARY_OPERATORS,\n 'between',\n 'between symmetric',\n];\n/**\n * @internal\n */\nexport const OperatorNode = freeze({\n is(node) {\n return node.kind === 'OperatorNode';\n },\n create(operator) {\n return freeze({\n kind: 'OperatorNode',\n operator,\n });\n },\n});\nexport function isOperator(op) {\n return isString(op) && OPERATORS.includes(op);\n}\nexport function isBinaryOperator(op) {\n return isString(op) && BINARY_OPERATORS.includes(op);\n}\nexport function isComparisonOperator(op) {\n return isString(op) && COMPARISON_OPERATORS.includes(op);\n}\nexport function isArithmeticOperator(op) {\n return isString(op) && ARITHMETIC_OPERATORS.includes(op);\n}\nexport function isJSONOperator(op) {\n return isString(op) && JSON_OPERATORS.includes(op);\n}\n","/// <reference types=\"./column-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const ColumnNode = freeze({\n is(node) {\n return node.kind === 'ColumnNode';\n },\n create(column) {\n return freeze({\n kind: 'ColumnNode',\n column: IdentifierNode.create(column),\n });\n },\n});\n","/// <reference types=\"./select-all-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SelectAllNode = freeze({\n is(node) {\n return node.kind === 'SelectAllNode';\n },\n create() {\n return freeze({\n kind: 'SelectAllNode',\n });\n },\n});\n","/// <reference types=\"./reference-node.d.ts\" />\nimport { SelectAllNode } from './select-all-node.js';\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ReferenceNode = freeze({\n is(node) {\n return node.kind === 'ReferenceNode';\n },\n create(column, table) {\n return freeze({\n kind: 'ReferenceNode',\n table,\n column,\n });\n },\n createSelectAll(table) {\n return freeze({\n kind: 'ReferenceNode',\n table,\n column: SelectAllNode.create(),\n });\n },\n});\n","/// <reference types=\"./dynamic-reference-builder.d.ts\" />\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { parseSimpleReferenceExpression } from '../parser/reference-parser.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport class DynamicReferenceBuilder {\n #dynamicReference;\n get dynamicReference() {\n return this.#dynamicReference;\n }\n /**\n * @private\n *\n * This needs to be here just so that the typings work. Without this\n * the generated .d.ts file contains no reference to the type param R\n * which causes this type to be equal to DynamicReferenceBuilder with\n * any R.\n */\n get refType() {\n return undefined;\n }\n constructor(reference) {\n this.#dynamicReference = reference;\n }\n toOperationNode() {\n return parseSimpleReferenceExpression(this.#dynamicReference);\n }\n}\nexport function isDynamicReferenceBuilder(obj) {\n return (isObject(obj) &&\n isOperationNodeSource(obj) &&\n isString(obj.dynamicReference));\n}\n","/// <reference types=\"./order-by-item-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrderByItemNode = freeze({\n is(node) {\n return node.kind === 'OrderByItemNode';\n },\n create(orderBy, direction) {\n return freeze({\n kind: 'OrderByItemNode',\n orderBy,\n direction,\n });\n },\n cloneWith(node, props) {\n return freeze({\n ...node,\n ...props,\n });\n },\n});\n","/// <reference types=\"./raw-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const RawNode = freeze({\n is(node) {\n return node.kind === 'RawNode';\n },\n create(sqlFragments, parameters) {\n return freeze({\n kind: 'RawNode',\n sqlFragments: freeze(sqlFragments),\n parameters: freeze(parameters),\n });\n },\n createWithSql(sql) {\n return RawNode.create([sql], []);\n },\n createWithChild(child) {\n return RawNode.create(['', ''], [child]);\n },\n createWithChildren(children) {\n return RawNode.create(new Array(children.length + 1).fill(''), children);\n },\n});\n","/// <reference types=\"./collate-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { IdentifierNode } from './identifier-node.js';\n/**\n * @internal\n */\nexport const CollateNode = freeze({\n is(node) {\n return node.kind === 'CollateNode';\n },\n create(collation) {\n return freeze({\n kind: 'CollateNode',\n collation: IdentifierNode.create(collation),\n });\n },\n});\n","/// <reference types=\"./order-by-item-builder.d.ts\" />\nimport { CollateNode } from '../operation-node/collate-node.js';\nimport { OrderByItemNode } from '../operation-node/order-by-item-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OrderByItemBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /**\n * Adds `desc` to the `order by` item.\n *\n * See {@link asc} for the opposite.\n */\n desc() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n direction: RawNode.createWithSql('desc'),\n }),\n });\n }\n /**\n * Adds `asc` to the `order by` item.\n *\n * See {@link desc} for the opposite.\n */\n asc() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n direction: RawNode.createWithSql('asc'),\n }),\n });\n }\n /**\n * Adds `nulls last` to the `order by` item.\n *\n * This is only supported by some dialects like PostgreSQL and SQLite.\n *\n * See {@link nullsFirst} for the opposite.\n */\n nullsLast() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, { nulls: 'last' }),\n });\n }\n /**\n * Adds `nulls first` to the `order by` item.\n *\n * This is only supported by some dialects like PostgreSQL and SQLite.\n *\n * See {@link nullsLast} for the opposite.\n */\n nullsFirst() {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, { nulls: 'first' }),\n });\n }\n /**\n * Adds `collate <collationName>` to the `order by` item.\n */\n collate(collation) {\n return new OrderByItemBuilder({\n node: OrderByItemNode.cloneWith(this.#props.node, {\n collation: CollateNode.create(collation),\n }),\n });\n }\n toOperationNode() {\n return this.#props.node;\n }\n}\n","/// <reference types=\"./log-once.d.ts\" />\nconst LOGGED_MESSAGES = new Set();\n/**\n * Use for system-level logging, such as deprecation messages.\n * Logs a message and ensures it won't be logged again.\n */\nexport function logOnce(message) {\n if (LOGGED_MESSAGES.has(message)) {\n return;\n }\n LOGGED_MESSAGES.add(message);\n console.log(message);\n}\n","/// <reference types=\"./order-by-parser.d.ts\" />\nimport { isDynamicReferenceBuilder, } from '../dynamic/dynamic-reference-builder.js';\nimport { isExpression } from '../expression/expression.js';\nimport { OrderByItemNode } from '../operation-node/order-by-item-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { OrderByItemBuilder } from '../query-builder/order-by-item-builder.js';\nimport { logOnce } from '../util/log-once.js';\nimport { isExpressionOrFactory, parseExpression, } from './expression-parser.js';\nimport { parseStringReference, } from './reference-parser.js';\nexport function isOrderByDirection(thing) {\n return thing === 'asc' || thing === 'desc';\n}\nexport function parseOrderBy(args) {\n if (args.length === 2) {\n return [parseOrderByItem(args[0], args[1])];\n }\n if (args.length === 1) {\n const [orderBy] = args;\n if (Array.isArray(orderBy)) {\n logOnce('orderBy(array) is deprecated, use multiple orderBy calls instead.');\n return orderBy.map((item) => parseOrderByItem(item));\n }\n return [parseOrderByItem(orderBy)];\n }\n throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${args.length}`);\n}\nexport function parseOrderByItem(expr, modifiers) {\n const parsedRef = parseOrderByExpression(expr);\n if (OrderByItemNode.is(parsedRef)) {\n if (modifiers) {\n throw new Error('Cannot specify direction twice!');\n }\n return parsedRef;\n }\n return parseOrderByWithModifiers(parsedRef, modifiers);\n}\nfunction parseOrderByExpression(expr) {\n if (isExpressionOrFactory(expr)) {\n return parseExpression(expr);\n }\n if (isDynamicReferenceBuilder(expr)) {\n return expr.toOperationNode();\n }\n const [ref, direction] = expr.split(' ');\n if (direction) {\n logOnce(\"`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead.\");\n return parseOrderByWithModifiers(parseStringReference(ref), direction);\n }\n return parseStringReference(expr);\n}\nfunction parseOrderByWithModifiers(expr, modifiers) {\n if (typeof modifiers === 'string') {\n if (!isOrderByDirection(modifiers)) {\n throw new Error(`Invalid order by direction: ${modifiers}`);\n }\n return OrderByItemNode.create(expr, RawNode.createWithSql(modifiers));\n }\n if (isExpression(modifiers)) {\n logOnce(\"`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead.\");\n return OrderByItemNode.create(expr, modifiers.toOperationNode());\n }\n const node = OrderByItemNode.create(expr);\n if (!modifiers) {\n return node;\n }\n return modifiers(new OrderByItemBuilder({ node })).toOperationNode();\n}\n","/// <reference types=\"./json-reference-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONReferenceNode = freeze({\n is(node) {\n return node.kind === 'JSONReferenceNode';\n },\n create(reference, traversal) {\n return freeze({\n kind: 'JSONReferenceNode',\n reference,\n traversal,\n });\n },\n cloneWithTraversal(node, traversal) {\n return freeze({\n ...node,\n traversal,\n });\n },\n});\n","/// <reference types=\"./json-operator-chain-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONOperatorChainNode = freeze({\n is(node) {\n return node.kind === 'JSONOperatorChainNode';\n },\n create(operator) {\n return freeze({\n kind: 'JSONOperatorChainNode',\n operator,\n values: freeze([]),\n });\n },\n cloneWithValue(node, value) {\n return freeze({\n ...node,\n values: freeze([...node.values, value]),\n });\n },\n});\n","/// <reference types=\"./json-path-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONPathNode = freeze({\n is(node) {\n return node.kind === 'JSONPathNode';\n },\n create(inOperator) {\n return freeze({\n kind: 'JSONPathNode',\n inOperator,\n pathLegs: freeze([]),\n });\n },\n cloneWithLeg(jsonPathNode, pathLeg) {\n return freeze({\n ...jsonPathNode,\n pathLegs: freeze([...jsonPathNode.pathLegs, pathLeg]),\n });\n },\n});\n","/// <reference types=\"./reference-parser.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { ColumnNode } from '../operation-node/column-node.js';\nimport { ReferenceNode } from '../operation-node/reference-node.js';\nimport { TableNode } from '../operation-node/table-node.js';\nimport { isReadonlyArray, isString } from '../util/object-utils.js';\nimport { parseExpression, isExpressionOrFactory, } from './expression-parser.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOrderByDirection, parseOrderBy, } from './order-by-parser.js';\nimport { OperatorNode, isJSONOperator, } from '../operation-node/operator-node.js';\nimport { JSONReferenceNode } from '../operation-node/json-reference-node.js';\nimport { JSONOperatorChainNode } from '../operation-node/json-operator-chain-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nexport function parseSimpleReferenceExpression(exp) {\n if (isString(exp)) {\n return parseStringReference(exp);\n }\n return exp.toOperationNode();\n}\nexport function parseReferenceExpressionOrList(arg) {\n if (isReadonlyArray(arg)) {\n return arg.map((it) => parseReferenceExpression(it));\n }\n else {\n return [parseReferenceExpression(arg)];\n }\n}\nexport function parseReferenceExpression(exp) {\n if (isExpressionOrFactory(exp)) {\n return parseExpression(exp);\n }\n return parseSimpleReferenceExpression(exp);\n}\nexport function parseJSONReference(ref, op) {\n const referenceNode = parseStringReference(ref);\n if (isJSONOperator(op)) {\n return JSONReferenceNode.create(referenceNode, JSONOperatorChainNode.create(OperatorNode.create(op)));\n }\n const opWithoutLastChar = op.slice(0, -1);\n if (isJSONOperator(opWithoutLastChar)) {\n return JSONReferenceNode.create(referenceNode, JSONPathNode.create(OperatorNode.create(opWithoutLastChar)));\n }\n throw new Error(`Invalid JSON operator: ${op}`);\n}\nexport function parseStringReference(ref) {\n const COLUMN_SEPARATOR = '.';\n if (!ref.includes(COLUMN_SEPARATOR)) {\n return ReferenceNode.create(ColumnNode.create(ref));\n }\n const parts = ref.split(COLUMN_SEPARATOR).map(trim);\n if (parts.length === 3) {\n return parseStringReferenceWithTableAndSchema(parts);\n }\n if (parts.length === 2) {\n return parseStringReferenceWithTable(parts);\n }\n throw new Error(`invalid column reference ${ref}`);\n}\nexport function parseAliasedStringReference(ref) {\n const ALIAS_SEPARATOR = ' as ';\n if (ref.includes(ALIAS_SEPARATOR)) {\n const [columnRef, alias] = ref.split(ALIAS_SEPARATOR).map(trim);\n return AliasNode.create(parseStringReference(columnRef), IdentifierNode.create(alias));\n }\n else {\n return parseStringReference(ref);\n }\n}\nexport function parseColumnName(column) {\n return ColumnNode.create(column);\n}\nexport function parseOrderedColumnName(column) {\n const ORDER_SEPARATOR = ' ';\n if (column.includes(ORDER_SEPARATOR)) {\n const [columnName, order] = column.split(ORDER_SEPARATOR).map(trim);\n if (!isOrderByDirection(order)) {\n throw new Error(`invalid order direction \"${order}\" next to \"${columnName}\"`);\n }\n return parseOrderBy([columnName, order])[0];\n }\n else {\n return parseColumnName(column);\n }\n}\nfunction parseStringReferenceWithTableAndSchema(parts) {\n const [schema, table, column] = parts;\n return ReferenceNode.create(ColumnNode.create(column), TableNode.createWithSchema(schema, table));\n}\nfunction parseStringReferenceWithTable(parts) {\n const [table, column] = parts;\n return ReferenceNode.create(ColumnNode.create(column), TableNode.create(table));\n}\nfunction trim(str) {\n return str.trim();\n}\n","/// <reference types=\"./primitive-value-list-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PrimitiveValueListNode = freeze({\n is(node) {\n return node.kind === 'PrimitiveValueListNode';\n },\n create(values) {\n return freeze({\n kind: 'PrimitiveValueListNode',\n values: freeze([...values]),\n });\n },\n});\n","/// <reference types=\"./value-list-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValueListNode = freeze({\n is(node) {\n return node.kind === 'ValueListNode';\n },\n create(values) {\n return freeze({\n kind: 'ValueListNode',\n values: freeze(values),\n });\n },\n});\n","/// <reference types=\"./value-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ValueNode = freeze({\n is(node) {\n return node.kind === 'ValueNode';\n },\n create(value) {\n return freeze({\n kind: 'ValueNode',\n value,\n });\n },\n createImmediate(value) {\n return freeze({\n kind: 'ValueNode',\n value,\n immediate: true,\n });\n },\n});\n","/// <reference types=\"./value-parser.d.ts\" />\nimport { PrimitiveValueListNode } from '../operation-node/primitive-value-list-node.js';\nimport { ValueListNode } from '../operation-node/value-list-node.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { isBoolean, isNull, isNumber, isReadonlyArray, } from '../util/object-utils.js';\nimport { parseExpression, isExpressionOrFactory, } from './expression-parser.js';\nexport function parseValueExpressionOrList(arg) {\n if (isReadonlyArray(arg)) {\n return parseValueExpressionList(arg);\n }\n return parseValueExpression(arg);\n}\nexport function parseValueExpression(exp) {\n if (isExpressionOrFactory(exp)) {\n return parseExpression(exp);\n }\n return ValueNode.create(exp);\n}\nexport function isSafeImmediateValue(value) {\n return isNumber(value) || isBoolean(value) || isNull(value);\n}\nexport function parseSafeImmediateValue(value) {\n if (!isSafeImmediateValue(value)) {\n throw new Error(`unsafe immediate value ${JSON.stringify(value)}`);\n }\n return ValueNode.createImmediate(value);\n}\nfunction parseValueExpressionList(arg) {\n if (arg.some(isExpressionOrFactory)) {\n return ValueListNode.create(arg.map((it) => parseValueExpression(it)));\n }\n return PrimitiveValueListNode.create(arg);\n}\n","/// <reference types=\"./parens-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ParensNode = freeze({\n is(node) {\n return node.kind === 'ParensNode';\n },\n create(node) {\n return freeze({\n kind: 'ParensNode',\n node,\n });\n },\n});\n","/// <reference types=\"./binary-operation-parser.d.ts\" />\nimport { BinaryOperationNode } from '../operation-node/binary-operation-node.js';\nimport { isBoolean, isNull, isString, isUndefined, } from '../util/object-utils.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { OperatorNode, OPERATORS, } from '../operation-node/operator-node.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nimport { parseValueExpression, parseValueExpressionOrList, } from './value-parser.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { OrNode } from '../operation-node/or-node.js';\nexport function parseValueBinaryOperationOrExpression(args) {\n if (args.length === 3) {\n return parseValueBinaryOperation(args[0], args[1], args[2]);\n }\n else if (args.length === 1) {\n return parseValueExpression(args[0]);\n }\n throw new Error(`invalid arguments: ${JSON.stringify(args)}`);\n}\nexport function parseValueBinaryOperation(left, operator, right) {\n if (isIsOperator(operator) && needsIsOperator(right)) {\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), ValueNode.createImmediate(right));\n }\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseValueExpressionOrList(right));\n}\nexport function parseReferentialBinaryOperation(left, operator, right) {\n return BinaryOperationNode.create(parseReferenceExpression(left), parseOperator(operator), parseReferenceExpression(right));\n}\nexport function parseFilterObject(obj, combinator) {\n return parseFilterList(Object.entries(obj)\n .filter(([, v]) => !isUndefined(v))\n .map(([k, v]) => parseValueBinaryOperation(k, needsIsOperator(v) ? 'is' : '=', v)), combinator);\n}\nexport function parseFilterList(list, combinator, withParens = true) {\n const combine = combinator === 'and' ? AndNode.create : OrNode.create;\n if (list.length === 0) {\n return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create('='), ValueNode.createImmediate(combinator === 'and' ? 1 : 0));\n }\n let node = toOperationNode(list[0]);\n for (let i = 1; i < list.length; ++i) {\n node = combine(node, toOperationNode(list[i]));\n }\n if (list.length > 1 && withParens) {\n return ParensNode.create(node);\n }\n return node;\n}\nfunction isIsOperator(operator) {\n return operator === 'is' || operator === 'is not';\n}\nfunction needsIsOperator(value) {\n return isNull(value) || isBoolean(value);\n}\nfunction parseOperator(operator) {\n if (isString(operator) && OPERATORS.includes(operator)) {\n return OperatorNode.create(operator);\n }\n if (isOperationNodeSource(operator)) {\n return operator.toOperationNode();\n }\n throw new Error(`invalid operator ${JSON.stringify(operator)}`);\n}\nfunction toOperationNode(nodeOrSource) {\n return isOperationNodeSource(nodeOrSource)\n ? nodeOrSource.toOperationNode()\n : nodeOrSource;\n}\n","/// <reference types=\"./order-by-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OrderByNode = freeze({\n is(node) {\n return node.kind === 'OrderByNode';\n },\n create(items) {\n return freeze({\n kind: 'OrderByNode',\n items: freeze([...items]),\n });\n },\n cloneWithItems(orderBy, items) {\n return freeze({\n ...orderBy,\n items: freeze([...orderBy.items, ...items]),\n });\n },\n});\n","/// <reference types=\"./partition-by-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PartitionByNode = freeze({\n is(node) {\n return node.kind === 'PartitionByNode';\n },\n create(items) {\n return freeze({\n kind: 'PartitionByNode',\n items: freeze(items),\n });\n },\n cloneWithItems(partitionBy, items) {\n return freeze({\n ...partitionBy,\n items: freeze([...partitionBy.items, ...items]),\n });\n },\n});\n","/// <reference types=\"./over-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { OrderByNode } from './order-by-node.js';\nimport { PartitionByNode } from './partition-by-node.js';\n/**\n * @internal\n */\nexport const OverNode = freeze({\n is(node) {\n return node.kind === 'OverNode';\n },\n create() {\n return freeze({\n kind: 'OverNode',\n });\n },\n cloneWithOrderByItems(overNode, items) {\n return freeze({\n ...overNode,\n orderBy: overNode.orderBy\n ? OrderByNode.cloneWithItems(overNode.orderBy, items)\n : OrderByNode.create(items),\n });\n },\n cloneWithPartitionByItems(overNode, items) {\n return freeze({\n ...overNode,\n partitionBy: overNode.partitionBy\n ? PartitionByNode.cloneWithItems(overNode.partitionBy, items)\n : PartitionByNode.create(items),\n });\n },\n});\n","/// <reference types=\"./from-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const FromNode = freeze({\n is(node) {\n return node.kind === 'FromNode';\n },\n create(froms) {\n return freeze({\n kind: 'FromNode',\n froms: freeze(froms),\n });\n },\n cloneWithFroms(from, froms) {\n return freeze({\n ...from,\n froms: freeze([...from.froms, ...froms]),\n });\n },\n});\n","/// <reference types=\"./group-by-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GroupByNode = freeze({\n is(node) {\n return node.kind === 'GroupByNode';\n },\n create(items) {\n return freeze({\n kind: 'GroupByNode',\n items: freeze(items),\n });\n },\n cloneWithItems(groupBy, items) {\n return freeze({\n ...groupBy,\n items: freeze([...groupBy.items, ...items]),\n });\n },\n});\n","/// <reference types=\"./having-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const HavingNode = freeze({\n is(node) {\n return node.kind === 'HavingNode';\n },\n create(filter) {\n return freeze({\n kind: 'HavingNode',\n having: filter,\n });\n },\n cloneWithOperation(havingNode, operator, operation) {\n return freeze({\n ...havingNode,\n having: operator === 'And'\n ? AndNode.create(havingNode.having, operation)\n : OrNode.create(havingNode.having, operation),\n });\n },\n});\n","/// <reference types=\"./insert-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const InsertQueryNode = freeze({\n is(node) {\n return node.kind === 'InsertQueryNode';\n },\n create(into, withNode, replace) {\n return freeze({\n kind: 'InsertQueryNode',\n into,\n ...(withNode && { with: withNode }),\n replace,\n });\n },\n createWithoutInto() {\n return freeze({\n kind: 'InsertQueryNode',\n });\n },\n cloneWith(insertQuery, props) {\n return freeze({\n ...insertQuery,\n ...props,\n });\n },\n});\n","/// <reference types=\"./list-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ListNode = freeze({\n is(node) {\n return node.kind === 'ListNode';\n },\n create(items) {\n return freeze({\n kind: 'ListNode',\n items: freeze(items),\n });\n },\n});\n","/// <reference types=\"./update-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { ListNode } from './list-node.js';\n/**\n * @internal\n */\nexport const UpdateQueryNode = freeze({\n is(node) {\n return node.kind === 'UpdateQueryNode';\n },\n create(tables, withNode) {\n return freeze({\n kind: 'UpdateQueryNode',\n // For backwards compatibility, use the raw table node when there's only one table\n // and don't rename the property to something like `tables`.\n table: tables.length === 1 ? tables[0] : ListNode.create(tables),\n ...(withNode && { with: withNode }),\n });\n },\n createWithoutTable() {\n return freeze({\n kind: 'UpdateQueryNode',\n });\n },\n cloneWithFromItems(updateQuery, fromItems) {\n return freeze({\n ...updateQuery,\n from: updateQuery.from\n ? FromNode.cloneWithFroms(updateQuery.from, fromItems)\n : FromNode.create(fromItems),\n });\n },\n cloneWithUpdates(updateQuery, updates) {\n return freeze({\n ...updateQuery,\n updates: updateQuery.updates\n ? freeze([...updateQuery.updates, ...updates])\n : updates,\n });\n },\n cloneWithLimit(updateQuery, limit) {\n return freeze({\n ...updateQuery,\n limit,\n });\n },\n});\n","/// <reference types=\"./using-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const UsingNode = freeze({\n is(node) {\n return node.kind === 'UsingNode';\n },\n create(tables) {\n return freeze({\n kind: 'UsingNode',\n tables: freeze(tables),\n });\n },\n cloneWithTables(using, tables) {\n return freeze({\n ...using,\n tables: freeze([...using.tables, ...tables]),\n });\n },\n});\n","/// <reference types=\"./delete-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { UsingNode } from './using-node.js';\nimport { QueryNode } from './query-node.js';\n/**\n * @internal\n */\nexport const DeleteQueryNode = freeze({\n is(node) {\n return node.kind === 'DeleteQueryNode';\n },\n create(fromItems, withNode) {\n return freeze({\n kind: 'DeleteQueryNode',\n from: FromNode.create(fromItems),\n ...(withNode && { with: withNode }),\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),\n cloneWithLimit(deleteNode, limit) {\n return freeze({\n ...deleteNode,\n limit,\n });\n },\n cloneWithoutLimit(deleteNode) {\n return freeze({\n ...deleteNode,\n limit: undefined,\n });\n },\n cloneWithUsing(deleteNode, tables) {\n return freeze({\n ...deleteNode,\n using: deleteNode.using !== undefined\n ? UsingNode.cloneWithTables(deleteNode.using, tables)\n : UsingNode.create(tables),\n });\n },\n});\n","/// <reference types=\"./where-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AndNode } from './and-node.js';\nimport { OrNode } from './or-node.js';\n/**\n * @internal\n */\nexport const WhereNode = freeze({\n is(node) {\n return node.kind === 'WhereNode';\n },\n create(filter) {\n return freeze({\n kind: 'WhereNode',\n where: filter,\n });\n },\n cloneWithOperation(whereNode, operator, operation) {\n return freeze({\n ...whereNode,\n where: operator === 'And'\n ? AndNode.create(whereNode.where, operation)\n : OrNode.create(whereNode.where, operation),\n });\n },\n});\n","/// <reference types=\"./returning-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ReturningNode = freeze({\n is(node) {\n return node.kind === 'ReturningNode';\n },\n create(selections) {\n return freeze({\n kind: 'ReturningNode',\n selections: freeze(selections),\n });\n },\n cloneWithSelections(returning, selections) {\n return freeze({\n ...returning,\n selections: returning.selections\n ? freeze([...returning.selections, ...selections])\n : freeze(selections),\n });\n },\n});\n","/// <reference types=\"./explain-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const ExplainNode = freeze({\n is(node) {\n return node.kind === 'ExplainNode';\n },\n create(format, options) {\n return freeze({\n kind: 'ExplainNode',\n format,\n options,\n });\n },\n});\n","/// <reference types=\"./when-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const WhenNode = freeze({\n is(node) {\n return node.kind === 'WhenNode';\n },\n create(condition) {\n return freeze({\n kind: 'WhenNode',\n condition,\n });\n },\n cloneWithResult(whenNode, result) {\n return freeze({\n ...whenNode,\n result,\n });\n },\n});\n","/// <reference types=\"./merge-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { WhenNode } from './when-node.js';\n/**\n * @internal\n */\nexport const MergeQueryNode = freeze({\n is(node) {\n return node.kind === 'MergeQueryNode';\n },\n create(into, withNode) {\n return freeze({\n kind: 'MergeQueryNode',\n into,\n ...(withNode && { with: withNode }),\n });\n },\n cloneWithUsing(mergeNode, using) {\n return freeze({\n ...mergeNode,\n using,\n });\n },\n cloneWithWhen(mergeNode, when) {\n return freeze({\n ...mergeNode,\n whens: mergeNode.whens\n ? freeze([...mergeNode.whens, when])\n : freeze([when]),\n });\n },\n cloneWithThen(mergeNode, then) {\n return freeze({\n ...mergeNode,\n whens: mergeNode.whens\n ? freeze([\n ...mergeNode.whens.slice(0, -1),\n WhenNode.cloneWithResult(mergeNode.whens[mergeNode.whens.length - 1], then),\n ])\n : undefined,\n });\n },\n});\n","/// <reference types=\"./output-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OutputNode = freeze({\n is(node) {\n return node.kind === 'OutputNode';\n },\n create(selections) {\n return freeze({\n kind: 'OutputNode',\n selections: freeze(selections),\n });\n },\n cloneWithSelections(output, selections) {\n return freeze({\n ...output,\n selections: output.selections\n ? freeze([...output.selections, ...selections])\n : freeze(selections),\n });\n },\n});\n","/// <reference types=\"./query-node.d.ts\" />\nimport { InsertQueryNode } from './insert-query-node.js';\nimport { SelectQueryNode } from './select-query-node.js';\nimport { UpdateQueryNode } from './update-query-node.js';\nimport { DeleteQueryNode } from './delete-query-node.js';\nimport { WhereNode } from './where-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { ReturningNode } from './returning-node.js';\nimport { ExplainNode } from './explain-node.js';\nimport { MergeQueryNode } from './merge-query-node.js';\nimport { OutputNode } from './output-node.js';\nimport { OrderByNode } from './order-by-node.js';\n/**\n * @internal\n */\nexport const QueryNode = freeze({\n is(node) {\n return (SelectQueryNode.is(node) ||\n InsertQueryNode.is(node) ||\n UpdateQueryNode.is(node) ||\n DeleteQueryNode.is(node) ||\n MergeQueryNode.is(node));\n },\n cloneWithEndModifier(node, modifier) {\n return freeze({\n ...node,\n endModifiers: node.endModifiers\n ? freeze([...node.endModifiers, modifier])\n : freeze([modifier]),\n });\n },\n cloneWithWhere(node, operation) {\n return freeze({\n ...node,\n where: node.where\n ? WhereNode.cloneWithOperation(node.where, 'And', operation)\n : WhereNode.create(operation),\n });\n },\n cloneWithJoin(node, join) {\n return freeze({\n ...node,\n joins: node.joins ? freeze([...node.joins, join]) : freeze([join]),\n });\n },\n cloneWithReturning(node, selections) {\n return freeze({\n ...node,\n returning: node.returning\n ? ReturningNode.cloneWithSelections(node.returning, selections)\n : ReturningNode.create(selections),\n });\n },\n cloneWithoutReturning(node) {\n return freeze({\n ...node,\n returning: undefined,\n });\n },\n cloneWithoutWhere(node) {\n return freeze({\n ...node,\n where: undefined,\n });\n },\n cloneWithExplain(node, format, options) {\n return freeze({\n ...node,\n explain: ExplainNode.create(format, options?.toOperationNode()),\n });\n },\n cloneWithTop(node, top) {\n return freeze({\n ...node,\n top,\n });\n },\n cloneWithOutput(node, selections) {\n return freeze({\n ...node,\n output: node.output\n ? OutputNode.cloneWithSelections(node.output, selections)\n : OutputNode.create(selections),\n });\n },\n cloneWithOrderByItems(node, items) {\n return freeze({\n ...node,\n orderBy: node.orderBy\n ? OrderByNode.cloneWithItems(node.orderBy, items)\n : OrderByNode.create(items),\n });\n },\n cloneWithoutOrderBy(node) {\n return freeze({\n ...node,\n orderBy: undefined,\n });\n },\n});\n","/// <reference types=\"./select-query-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { FromNode } from './from-node.js';\nimport { GroupByNode } from './group-by-node.js';\nimport { HavingNode } from './having-node.js';\nimport { QueryNode } from './query-node.js';\n/**\n * @internal\n */\nexport const SelectQueryNode = freeze({\n is(node) {\n return node.kind === 'SelectQueryNode';\n },\n create(withNode) {\n return freeze({\n kind: 'SelectQueryNode',\n ...(withNode && { with: withNode }),\n });\n },\n createFrom(fromItems, withNode) {\n return freeze({\n kind: 'SelectQueryNode',\n from: FromNode.create(fromItems),\n ...(withNode && { with: withNode }),\n });\n },\n cloneWithSelections(select, selections) {\n return freeze({\n ...select,\n selections: select.selections\n ? freeze([...select.selections, ...selections])\n : freeze(selections),\n });\n },\n cloneWithDistinctOn(select, expressions) {\n return freeze({\n ...select,\n distinctOn: select.distinctOn\n ? freeze([...select.distinctOn, ...expressions])\n : freeze(expressions),\n });\n },\n cloneWithFrontModifier(select, modifier) {\n return freeze({\n ...select,\n frontModifiers: select.frontModifiers\n ? freeze([...select.frontModifiers, modifier])\n : freeze([modifier]),\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),\n cloneWithGroupByItems(selectNode, items) {\n return freeze({\n ...selectNode,\n groupBy: selectNode.groupBy\n ? GroupByNode.cloneWithItems(selectNode.groupBy, items)\n : GroupByNode.create(items),\n });\n },\n cloneWithLimit(selectNode, limit) {\n return freeze({\n ...selectNode,\n limit,\n });\n },\n cloneWithOffset(selectNode, offset) {\n return freeze({\n ...selectNode,\n offset,\n });\n },\n cloneWithFetch(selectNode, fetch) {\n return freeze({\n ...selectNode,\n fetch,\n });\n },\n cloneWithHaving(selectNode, operation) {\n return freeze({\n ...selectNode,\n having: selectNode.having\n ? HavingNode.cloneWithOperation(selectNode.having, 'And', operation)\n : HavingNode.create(operation),\n });\n },\n cloneWithSetOperations(selectNode, setOperations) {\n return freeze({\n ...selectNode,\n setOperations: selectNode.setOperations\n ? freeze([...selectNode.setOperations, ...setOperations])\n : freeze([...setOperations]),\n });\n },\n cloneWithoutSelections(select) {\n return freeze({\n ...select,\n selections: [],\n });\n },\n cloneWithoutLimit(select) {\n return freeze({\n ...select,\n limit: undefined,\n });\n },\n cloneWithoutOffset(select) {\n return freeze({\n ...select,\n offset: undefined,\n });\n },\n // TODO: remove in v0.29\n /**\n * @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.\n */\n cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),\n cloneWithoutGroupBy(select) {\n return freeze({\n ...select,\n groupBy: undefined,\n });\n },\n});\n","/// <reference types=\"./join-builder.d.ts\" />\nimport { JoinNode } from '../operation-node/join-node.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class JoinBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n on(...args) {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Just like {@link WhereInterface.whereRef} but adds an item to the join's\n * `on` clause instead.\n *\n * See {@link WhereInterface.whereRef} for documentation and examples.\n */\n onRef(lhs, op, rhs) {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n /**\n * Adds `on true`.\n */\n onTrue() {\n return new JoinBuilder({\n ...this.#props,\n joinNode: JoinNode.cloneWithOn(this.#props.joinNode, RawNode.createWithSql('true')),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.joinNode;\n }\n}\n","/// <reference types=\"./partition-by-item-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const PartitionByItemNode = freeze({\n is(node) {\n return node.kind === 'PartitionByItemNode';\n },\n create(partitionBy) {\n return freeze({\n kind: 'PartitionByItemNode',\n partitionBy,\n });\n },\n});\n","/// <reference types=\"./partition-by-parser.d.ts\" />\nimport { PartitionByItemNode } from '../operation-node/partition-by-item-node.js';\nimport { parseReferenceExpressionOrList, } from './reference-parser.js';\nexport function parsePartitionBy(partitionBy) {\n return parseReferenceExpressionOrList(partitionBy).map(PartitionByItemNode.create);\n}\n","/// <reference types=\"./over-builder.d.ts\" />\nimport { OverNode } from '../operation-node/over-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { parsePartitionBy, } from '../parser/partition-by-parser.js';\nimport { freeze } from '../util/object-utils.js';\nexport class OverBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n orderBy(...args) {\n return new OverBuilder({\n overNode: OverNode.cloneWithOrderByItems(this.#props.overNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new OverBuilder({\n overNode: QueryNode.cloneWithoutOrderBy(this.#props.overNode),\n });\n }\n partitionBy(partitionBy) {\n return new OverBuilder({\n overNode: OverNode.cloneWithPartitionByItems(this.#props.overNode, parsePartitionBy(partitionBy)),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n toOperationNode() {\n return this.#props.overNode;\n }\n}\n","/// <reference types=\"./selection-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { ReferenceNode } from './reference-node.js';\nimport { SelectAllNode } from './select-all-node.js';\n/**\n * @internal\n */\nexport const SelectionNode = freeze({\n is(node) {\n return node.kind === 'SelectionNode';\n },\n create(selection) {\n return freeze({\n kind: 'SelectionNode',\n selection: selection,\n });\n },\n createSelectAll() {\n return freeze({\n kind: 'SelectionNode',\n selection: SelectAllNode.create(),\n });\n },\n createSelectAllFromTable(table) {\n return freeze({\n kind: 'SelectionNode',\n selection: ReferenceNode.createSelectAll(table),\n });\n },\n});\n","/// <reference types=\"./select-parser.d.ts\" />\nimport { isFunction, isReadonlyArray, isString } from '../util/object-utils.js';\nimport { SelectionNode } from '../operation-node/selection-node.js';\nimport { parseAliasedStringReference } from './reference-parser.js';\nimport { isDynamicReferenceBuilder, } from '../dynamic/dynamic-reference-builder.js';\nimport { parseAliasedExpression, } from './expression-parser.js';\nimport { parseTable } from './table-parser.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nexport function parseSelectArg(selection) {\n if (isFunction(selection)) {\n return parseSelectArg(selection(expressionBuilder()));\n }\n else if (isReadonlyArray(selection)) {\n return selection.map((it) => parseSelectExpression(it));\n }\n else {\n return [parseSelectExpression(selection)];\n }\n}\nfunction parseSelectExpression(selection) {\n if (isString(selection)) {\n return SelectionNode.create(parseAliasedStringReference(selection));\n }\n else if (isDynamicReferenceBuilder(selection)) {\n return SelectionNode.create(selection.toOperationNode());\n }\n else {\n return SelectionNode.create(parseAliasedExpression(selection));\n }\n}\nexport function parseSelectAll(table) {\n if (!table) {\n return [SelectionNode.createSelectAll()];\n }\n else if (Array.isArray(table)) {\n return table.map(parseSelectAllArg);\n }\n else {\n return [parseSelectAllArg(table)];\n }\n}\nfunction parseSelectAllArg(table) {\n if (isString(table)) {\n return SelectionNode.createSelectAllFromTable(parseTable(table));\n }\n throw new Error(`invalid value selectAll expression: ${JSON.stringify(table)}`);\n}\n","/// <reference types=\"./no-result-error.d.ts\" />\nexport class NoResultError extends Error {\n /**\n * The operation node tree of the query that was executed.\n */\n node;\n constructor(node) {\n super('no result');\n this.node = node;\n }\n}\nexport function isNoResultErrorConstructor(fn) {\n return Object.prototype.hasOwnProperty.call(fn, 'prototype');\n}\n","/// <reference types=\"./top-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const TopNode = freeze({\n is(node) {\n return node.kind === 'TopNode';\n },\n create(expression, modifiers) {\n return freeze({\n kind: 'TopNode',\n expression,\n modifiers,\n });\n },\n});\n","/// <reference types=\"./top-parser.d.ts\" />\nimport { TopNode } from '../operation-node/top-node.js';\nimport { isBigInt, isNumber, isUndefined } from '../util/object-utils.js';\nexport function parseTop(expression, modifiers) {\n if (!isNumber(expression) && !isBigInt(expression)) {\n throw new Error(`Invalid top expression: ${expression}`);\n }\n if (!isUndefined(modifiers) && !isTopModifiers(modifiers)) {\n throw new Error(`Invalid top modifiers: ${modifiers}`);\n }\n return TopNode.create(expression, modifiers);\n}\nfunction isTopModifiers(modifiers) {\n return (modifiers === 'percent' ||\n modifiers === 'with ties' ||\n modifiers === 'percent with ties');\n}\n","/// <reference types=\"./limit-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const LimitNode = freeze({\n is(node) {\n return node.kind === 'LimitNode';\n },\n create(limit) {\n return freeze({\n kind: 'LimitNode',\n limit,\n });\n },\n});\n","/// <reference types=\"./random-string.d.ts\" />\nconst CHARS = [\n 'A',\n 'B',\n 'C',\n 'D',\n 'E',\n 'F',\n 'G',\n 'H',\n 'I',\n 'J',\n 'K',\n 'L',\n 'M',\n 'N',\n 'O',\n 'P',\n 'Q',\n 'R',\n 'S',\n 'T',\n 'U',\n 'V',\n 'W',\n 'X',\n 'Y',\n 'Z',\n 'a',\n 'b',\n 'c',\n 'd',\n 'e',\n 'f',\n 'g',\n 'h',\n 'i',\n 'j',\n 'k',\n 'l',\n 'm',\n 'n',\n 'o',\n 'p',\n 'q',\n 'r',\n 's',\n 't',\n 'u',\n 'v',\n 'w',\n 'x',\n 'y',\n 'z',\n '0',\n '1',\n '2',\n '3',\n '4',\n '5',\n '6',\n '7',\n '8',\n '9',\n];\nexport function randomString(length) {\n let chars = '';\n for (let i = 0; i < length; ++i) {\n chars += randomChar();\n }\n return chars;\n}\nfunction randomChar() {\n return CHARS[~~(Math.random() * CHARS.length)];\n}\n","/// <reference types=\"./query-id.d.ts\" />\nimport { randomString } from './random-string.js';\nexport function createQueryId() {\n return new LazyQueryId();\n}\nclass LazyQueryId {\n #queryId;\n get queryId() {\n if (this.#queryId === undefined) {\n this.#queryId = randomString(8);\n }\n return this.#queryId;\n }\n}\n","/// <reference types=\"./require-all-props.d.ts\" />\n/**\n * Helper function to check listed properties according to given type. Check if all properties has been used when object is initialised.\n *\n * Example use:\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n *\n * // propB has to be mentioned even it is optional. It still should be initialized with undefined.\n * const a: SomeType = requireAllProps<SomeType>({ propA: \"value A\", propB: undefined });\n *\n * // checked type is implicit for variable.\n * const b = requireAllProps<SomeType>({ propA: \"value A\", propB: undefined });\n * ```\n *\n * Wrong use of this helper:\n *\n * 1. Omit checked type - all checked properties will be expect as of type never\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n * // const z: SomeType = requireAllProps({ propC: \"no type will work\" }); // Property 'propA' is missing in type '{ propC: string; }' but required in type 'SomeType'.\n * ```\n *\n * 2. Apply to spreaded object - there is no way how to check in compile time if spreaded object contains all properties\n *\n * ```ts\n * type SomeType = { propA: string; propB?: number; }\n * const y: SomeType = { propA: \"\" }; // valid object according to SomeType declaration\n * // const x = requireAllProps<SomeType>({ ...y }); // Argument of type '{ propA: string; propB?: number; }' is not assignable to parameter of type 'AllProps<SomeType>'.\n * ```\n *\n * @param obj object to check if all properties has been used\n * @returns untouched obj parameter is returned\n */\nexport function requireAllProps(obj) {\n return obj;\n}\n","/// <reference types=\"./operation-node-transformer.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { requireAllProps } from '../util/require-all-props.js';\n/**\n * Transforms an operation node tree into another one.\n *\n * Kysely queries are expressed internally as a tree of objects (operation nodes).\n * `OperationNodeTransformer` takes such a tree as its input and returns a\n * transformed deep copy of it. By default the `OperationNodeTransformer`\n * does nothing. You need to override one or more methods to make it do\n * something.\n *\n * There's a method for each node type. For example if you'd like to convert\n * each identifier (table name, column name, alias etc.) from camelCase to\n * snake_case, you'd do something like this:\n *\n * ```ts\n * import { type IdentifierNode, OperationNodeTransformer } from 'kysely'\n * import snakeCase from 'lodash/snakeCase'\n *\n * class CamelCaseTransformer extends OperationNodeTransformer {\n * override transformIdentifier(node: IdentifierNode): IdentifierNode {\n * node = super.transformIdentifier(node)\n *\n * return {\n * ...node,\n * name: snakeCase(node.name),\n * }\n * }\n * }\n *\n * const transformer = new CamelCaseTransformer()\n *\n * const query = db.selectFrom('person').select(['first_name', 'last_name'])\n *\n * const tree = transformer.transformNode(query.toOperationNode())\n * ```\n */\nexport class OperationNodeTransformer {\n nodeStack = [];\n #transformers = freeze({\n AliasNode: this.transformAlias.bind(this),\n ColumnNode: this.transformColumn.bind(this),\n IdentifierNode: this.transformIdentifier.bind(this),\n SchemableIdentifierNode: this.transformSchemableIdentifier.bind(this),\n RawNode: this.transformRaw.bind(this),\n ReferenceNode: this.transformReference.bind(this),\n SelectQueryNode: this.transformSelectQuery.bind(this),\n SelectionNode: this.transformSelection.bind(this),\n TableNode: this.transformTable.bind(this),\n FromNode: this.transformFrom.bind(this),\n SelectAllNode: this.transformSelectAll.bind(this),\n AndNode: this.transformAnd.bind(this),\n OrNode: this.transformOr.bind(this),\n ValueNode: this.transformValue.bind(this),\n ValueListNode: this.transformValueList.bind(this),\n PrimitiveValueListNode: this.transformPrimitiveValueList.bind(this),\n ParensNode: this.transformParens.bind(this),\n JoinNode: this.transformJoin.bind(this),\n OperatorNode: this.transformOperator.bind(this),\n WhereNode: this.transformWhere.bind(this),\n InsertQueryNode: this.transformInsertQuery.bind(this),\n DeleteQueryNode: this.transformDeleteQuery.bind(this),\n ReturningNode: this.transformReturning.bind(this),\n CreateTableNode: this.transformCreateTable.bind(this),\n AddColumnNode: this.transformAddColumn.bind(this),\n ColumnDefinitionNode: this.transformColumnDefinition.bind(this),\n DropTableNode: this.transformDropTable.bind(this),\n DataTypeNode: this.transformDataType.bind(this),\n OrderByNode: this.transformOrderBy.bind(this),\n OrderByItemNode: this.transformOrderByItem.bind(this),\n GroupByNode: this.transformGroupBy.bind(this),\n GroupByItemNode: this.transformGroupByItem.bind(this),\n UpdateQueryNode: this.transformUpdateQuery.bind(this),\n ColumnUpdateNode: this.transformColumnUpdate.bind(this),\n LimitNode: this.transformLimit.bind(this),\n OffsetNode: this.transformOffset.bind(this),\n OnConflictNode: this.transformOnConflict.bind(this),\n OnDuplicateKeyNode: this.transformOnDuplicateKey.bind(this),\n CreateIndexNode: this.transformCreateIndex.bind(this),\n DropIndexNode: this.transformDropIndex.bind(this),\n ListNode: this.transformList.bind(this),\n PrimaryKeyConstraintNode: this.transformPrimaryKeyConstraint.bind(this),\n UniqueConstraintNode: this.transformUniqueConstraint.bind(this),\n ReferencesNode: this.transformReferences.bind(this),\n CheckConstraintNode: this.transformCheckConstraint.bind(this),\n WithNode: this.transformWith.bind(this),\n CommonTableExpressionNode: this.transformCommonTableExpression.bind(this),\n CommonTableExpressionNameNode: this.transformCommonTableExpressionName.bind(this),\n HavingNode: this.transformHaving.bind(this),\n CreateSchemaNode: this.transformCreateSchema.bind(this),\n DropSchemaNode: this.transformDropSchema.bind(this),\n AlterTableNode: this.transformAlterTable.bind(this),\n DropColumnNode: this.transformDropColumn.bind(this),\n RenameColumnNode: this.transformRenameColumn.bind(this),\n AlterColumnNode: this.transformAlterColumn.bind(this),\n ModifyColumnNode: this.transformModifyColumn.bind(this),\n AddConstraintNode: this.transformAddConstraint.bind(this),\n DropConstraintNode: this.transformDropConstraint.bind(this),\n RenameConstraintNode: this.transformRenameConstraint.bind(this),\n ForeignKeyConstraintNode: this.transformForeignKeyConstraint.bind(this),\n CreateViewNode: this.transformCreateView.bind(this),\n RefreshMaterializedViewNode: this.transformRefreshMaterializedView.bind(this),\n DropViewNode: this.transformDropView.bind(this),\n GeneratedNode: this.transformGenerated.bind(this),\n DefaultValueNode: this.transformDefaultValue.bind(this),\n OnNode: this.transformOn.bind(this),\n ValuesNode: this.transformValues.bind(this),\n SelectModifierNode: this.transformSelectModifier.bind(this),\n CreateTypeNode: this.transformCreateType.bind(this),\n DropTypeNode: this.transformDropType.bind(this),\n ExplainNode: this.transformExplain.bind(this),\n DefaultInsertValueNode: this.transformDefaultInsertValue.bind(this),\n AggregateFunctionNode: this.transformAggregateFunction.bind(this),\n OverNode: this.transformOver.bind(this),\n PartitionByNode: this.transformPartitionBy.bind(this),\n PartitionByItemNode: this.transformPartitionByItem.bind(this),\n SetOperationNode: this.transformSetOperation.bind(this),\n BinaryOperationNode: this.transformBinaryOperation.bind(this),\n UnaryOperationNode: this.transformUnaryOperation.bind(this),\n UsingNode: this.transformUsing.bind(this),\n FunctionNode: this.transformFunction.bind(this),\n CaseNode: this.transformCase.bind(this),\n WhenNode: this.transformWhen.bind(this),\n JSONReferenceNode: this.transformJSONReference.bind(this),\n JSONPathNode: this.transformJSONPath.bind(this),\n JSONPathLegNode: this.transformJSONPathLeg.bind(this),\n JSONOperatorChainNode: this.transformJSONOperatorChain.bind(this),\n TupleNode: this.transformTuple.bind(this),\n MergeQueryNode: this.transformMergeQuery.bind(this),\n MatchedNode: this.transformMatched.bind(this),\n AddIndexNode: this.transformAddIndex.bind(this),\n CastNode: this.transformCast.bind(this),\n FetchNode: this.transformFetch.bind(this),\n TopNode: this.transformTop.bind(this),\n OutputNode: this.transformOutput.bind(this),\n OrActionNode: this.transformOrAction.bind(this),\n CollateNode: this.transformCollate.bind(this),\n });\n transformNode(node, queryId) {\n if (!node) {\n return node;\n }\n this.nodeStack.push(node);\n const out = this.transformNodeImpl(node, queryId);\n this.nodeStack.pop();\n return freeze(out);\n }\n transformNodeImpl(node, queryId) {\n return this.#transformers[node.kind](node, queryId);\n }\n transformNodeList(list, queryId) {\n if (!list) {\n return list;\n }\n return freeze(list.map((node) => this.transformNode(node, queryId)));\n }\n transformSelectQuery(node, queryId) {\n return requireAllProps({\n kind: 'SelectQueryNode',\n from: this.transformNode(node.from, queryId),\n selections: this.transformNodeList(node.selections, queryId),\n distinctOn: this.transformNodeList(node.distinctOn, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n groupBy: this.transformNode(node.groupBy, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n where: this.transformNode(node.where, queryId),\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n limit: this.transformNode(node.limit, queryId),\n offset: this.transformNode(node.offset, queryId),\n with: this.transformNode(node.with, queryId),\n having: this.transformNode(node.having, queryId),\n explain: this.transformNode(node.explain, queryId),\n setOperations: this.transformNodeList(node.setOperations, queryId),\n fetch: this.transformNode(node.fetch, queryId),\n top: this.transformNode(node.top, queryId),\n });\n }\n transformSelection(node, queryId) {\n return requireAllProps({\n kind: 'SelectionNode',\n selection: this.transformNode(node.selection, queryId),\n });\n }\n transformColumn(node, queryId) {\n return requireAllProps({\n kind: 'ColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformAlias(node, queryId) {\n return requireAllProps({\n kind: 'AliasNode',\n node: this.transformNode(node.node, queryId),\n alias: this.transformNode(node.alias, queryId),\n });\n }\n transformTable(node, queryId) {\n return requireAllProps({\n kind: 'TableNode',\n table: this.transformNode(node.table, queryId),\n });\n }\n transformFrom(node, queryId) {\n return requireAllProps({\n kind: 'FromNode',\n froms: this.transformNodeList(node.froms, queryId),\n });\n }\n transformReference(node, queryId) {\n return requireAllProps({\n kind: 'ReferenceNode',\n column: this.transformNode(node.column, queryId),\n table: this.transformNode(node.table, queryId),\n });\n }\n transformAnd(node, queryId) {\n return requireAllProps({\n kind: 'AndNode',\n left: this.transformNode(node.left, queryId),\n right: this.transformNode(node.right, queryId),\n });\n }\n transformOr(node, queryId) {\n return requireAllProps({\n kind: 'OrNode',\n left: this.transformNode(node.left, queryId),\n right: this.transformNode(node.right, queryId),\n });\n }\n transformValueList(node, queryId) {\n return requireAllProps({\n kind: 'ValueListNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformParens(node, queryId) {\n return requireAllProps({\n kind: 'ParensNode',\n node: this.transformNode(node.node, queryId),\n });\n }\n transformJoin(node, queryId) {\n return requireAllProps({\n kind: 'JoinNode',\n joinType: node.joinType,\n table: this.transformNode(node.table, queryId),\n on: this.transformNode(node.on, queryId),\n });\n }\n transformRaw(node, queryId) {\n return requireAllProps({\n kind: 'RawNode',\n sqlFragments: freeze([...node.sqlFragments]),\n parameters: this.transformNodeList(node.parameters, queryId),\n });\n }\n transformWhere(node, queryId) {\n return requireAllProps({\n kind: 'WhereNode',\n where: this.transformNode(node.where, queryId),\n });\n }\n transformInsertQuery(node, queryId) {\n return requireAllProps({\n kind: 'InsertQueryNode',\n into: this.transformNode(node.into, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n values: this.transformNode(node.values, queryId),\n returning: this.transformNode(node.returning, queryId),\n onConflict: this.transformNode(node.onConflict, queryId),\n onDuplicateKey: this.transformNode(node.onDuplicateKey, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n ignore: node.ignore,\n orAction: this.transformNode(node.orAction, queryId),\n replace: node.replace,\n explain: this.transformNode(node.explain, queryId),\n defaultValues: node.defaultValues,\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n });\n }\n transformValues(node, queryId) {\n return requireAllProps({\n kind: 'ValuesNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformDeleteQuery(node, queryId) {\n return requireAllProps({\n kind: 'DeleteQueryNode',\n from: this.transformNode(node.from, queryId),\n using: this.transformNode(node.using, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n where: this.transformNode(node.where, queryId),\n returning: this.transformNode(node.returning, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n limit: this.transformNode(node.limit, queryId),\n explain: this.transformNode(node.explain, queryId),\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n });\n }\n transformReturning(node, queryId) {\n return requireAllProps({\n kind: 'ReturningNode',\n selections: this.transformNodeList(node.selections, queryId),\n });\n }\n transformCreateTable(node, queryId) {\n return requireAllProps({\n kind: 'CreateTableNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n constraints: this.transformNodeList(node.constraints, queryId),\n temporary: node.temporary,\n ifNotExists: node.ifNotExists,\n onCommit: node.onCommit,\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n selectQuery: this.transformNode(node.selectQuery, queryId),\n });\n }\n transformColumnDefinition(node, queryId) {\n return requireAllProps({\n kind: 'ColumnDefinitionNode',\n column: this.transformNode(node.column, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n references: this.transformNode(node.references, queryId),\n primaryKey: node.primaryKey,\n autoIncrement: node.autoIncrement,\n unique: node.unique,\n notNull: node.notNull,\n unsigned: node.unsigned,\n defaultTo: this.transformNode(node.defaultTo, queryId),\n check: this.transformNode(node.check, queryId),\n generated: this.transformNode(node.generated, queryId),\n frontModifiers: this.transformNodeList(node.frontModifiers, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n identity: node.identity,\n ifNotExists: node.ifNotExists,\n });\n }\n transformAddColumn(node, queryId) {\n return requireAllProps({\n kind: 'AddColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformDropTable(node, queryId) {\n return requireAllProps({\n kind: 'DropTableNode',\n table: this.transformNode(node.table, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformOrderBy(node, queryId) {\n return requireAllProps({\n kind: 'OrderByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformOrderByItem(node, queryId) {\n return requireAllProps({\n kind: 'OrderByItemNode',\n orderBy: this.transformNode(node.orderBy, queryId),\n direction: this.transformNode(node.direction, queryId),\n collation: this.transformNode(node.collation, queryId),\n nulls: node.nulls,\n });\n }\n transformGroupBy(node, queryId) {\n return requireAllProps({\n kind: 'GroupByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformGroupByItem(node, queryId) {\n return requireAllProps({\n kind: 'GroupByItemNode',\n groupBy: this.transformNode(node.groupBy, queryId),\n });\n }\n transformUpdateQuery(node, queryId) {\n return requireAllProps({\n kind: 'UpdateQueryNode',\n table: this.transformNode(node.table, queryId),\n from: this.transformNode(node.from, queryId),\n joins: this.transformNodeList(node.joins, queryId),\n where: this.transformNode(node.where, queryId),\n updates: this.transformNodeList(node.updates, queryId),\n returning: this.transformNode(node.returning, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n with: this.transformNode(node.with, queryId),\n explain: this.transformNode(node.explain, queryId),\n limit: this.transformNode(node.limit, queryId),\n top: this.transformNode(node.top, queryId),\n output: this.transformNode(node.output, queryId),\n orderBy: this.transformNode(node.orderBy, queryId),\n });\n }\n transformColumnUpdate(node, queryId) {\n return requireAllProps({\n kind: 'ColumnUpdateNode',\n column: this.transformNode(node.column, queryId),\n value: this.transformNode(node.value, queryId),\n });\n }\n transformLimit(node, queryId) {\n return requireAllProps({\n kind: 'LimitNode',\n limit: this.transformNode(node.limit, queryId),\n });\n }\n transformOffset(node, queryId) {\n return requireAllProps({\n kind: 'OffsetNode',\n offset: this.transformNode(node.offset, queryId),\n });\n }\n transformOnConflict(node, queryId) {\n return requireAllProps({\n kind: 'OnConflictNode',\n columns: this.transformNodeList(node.columns, queryId),\n constraint: this.transformNode(node.constraint, queryId),\n indexExpression: this.transformNode(node.indexExpression, queryId),\n indexWhere: this.transformNode(node.indexWhere, queryId),\n updates: this.transformNodeList(node.updates, queryId),\n updateWhere: this.transformNode(node.updateWhere, queryId),\n doNothing: node.doNothing,\n });\n }\n transformOnDuplicateKey(node, queryId) {\n return requireAllProps({\n kind: 'OnDuplicateKeyNode',\n updates: this.transformNodeList(node.updates, queryId),\n });\n }\n transformCreateIndex(node, queryId) {\n return requireAllProps({\n kind: 'CreateIndexNode',\n name: this.transformNode(node.name, queryId),\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n unique: node.unique,\n using: this.transformNode(node.using, queryId),\n ifNotExists: node.ifNotExists,\n where: this.transformNode(node.where, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n });\n }\n transformList(node, queryId) {\n return requireAllProps({\n kind: 'ListNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformDropIndex(node, queryId) {\n return requireAllProps({\n kind: 'DropIndexNode',\n name: this.transformNode(node.name, queryId),\n table: this.transformNode(node.table, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformPrimaryKeyConstraint(node, queryId) {\n return requireAllProps({\n kind: 'PrimaryKeyConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n name: this.transformNode(node.name, queryId),\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformUniqueConstraint(node, queryId) {\n return requireAllProps({\n kind: 'UniqueConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n name: this.transformNode(node.name, queryId),\n nullsNotDistinct: node.nullsNotDistinct,\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformForeignKeyConstraint(node, queryId) {\n return requireAllProps({\n kind: 'ForeignKeyConstraintNode',\n columns: this.transformNodeList(node.columns, queryId),\n references: this.transformNode(node.references, queryId),\n name: this.transformNode(node.name, queryId),\n onDelete: node.onDelete,\n onUpdate: node.onUpdate,\n deferrable: node.deferrable,\n initiallyDeferred: node.initiallyDeferred,\n });\n }\n transformSetOperation(node, queryId) {\n return requireAllProps({\n kind: 'SetOperationNode',\n operator: node.operator,\n expression: this.transformNode(node.expression, queryId),\n all: node.all,\n });\n }\n transformReferences(node, queryId) {\n return requireAllProps({\n kind: 'ReferencesNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n onDelete: node.onDelete,\n onUpdate: node.onUpdate,\n });\n }\n transformCheckConstraint(node, queryId) {\n return requireAllProps({\n kind: 'CheckConstraintNode',\n expression: this.transformNode(node.expression, queryId),\n name: this.transformNode(node.name, queryId),\n });\n }\n transformWith(node, queryId) {\n return requireAllProps({\n kind: 'WithNode',\n expressions: this.transformNodeList(node.expressions, queryId),\n recursive: node.recursive,\n });\n }\n transformCommonTableExpression(node, queryId) {\n return requireAllProps({\n kind: 'CommonTableExpressionNode',\n name: this.transformNode(node.name, queryId),\n materialized: node.materialized,\n expression: this.transformNode(node.expression, queryId),\n });\n }\n transformCommonTableExpressionName(node, queryId) {\n return requireAllProps({\n kind: 'CommonTableExpressionNameNode',\n table: this.transformNode(node.table, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n });\n }\n transformHaving(node, queryId) {\n return requireAllProps({\n kind: 'HavingNode',\n having: this.transformNode(node.having, queryId),\n });\n }\n transformCreateSchema(node, queryId) {\n return requireAllProps({\n kind: 'CreateSchemaNode',\n schema: this.transformNode(node.schema, queryId),\n ifNotExists: node.ifNotExists,\n });\n }\n transformDropSchema(node, queryId) {\n return requireAllProps({\n kind: 'DropSchemaNode',\n schema: this.transformNode(node.schema, queryId),\n ifExists: node.ifExists,\n cascade: node.cascade,\n });\n }\n transformAlterTable(node, queryId) {\n return requireAllProps({\n kind: 'AlterTableNode',\n table: this.transformNode(node.table, queryId),\n renameTo: this.transformNode(node.renameTo, queryId),\n setSchema: this.transformNode(node.setSchema, queryId),\n columnAlterations: this.transformNodeList(node.columnAlterations, queryId),\n addConstraint: this.transformNode(node.addConstraint, queryId),\n dropConstraint: this.transformNode(node.dropConstraint, queryId),\n renameConstraint: this.transformNode(node.renameConstraint, queryId),\n addIndex: this.transformNode(node.addIndex, queryId),\n dropIndex: this.transformNode(node.dropIndex, queryId),\n });\n }\n transformDropColumn(node, queryId) {\n return requireAllProps({\n kind: 'DropColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformRenameColumn(node, queryId) {\n return requireAllProps({\n kind: 'RenameColumnNode',\n column: this.transformNode(node.column, queryId),\n renameTo: this.transformNode(node.renameTo, queryId),\n });\n }\n transformAlterColumn(node, queryId) {\n return requireAllProps({\n kind: 'AlterColumnNode',\n column: this.transformNode(node.column, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n dataTypeExpression: this.transformNode(node.dataTypeExpression, queryId),\n setDefault: this.transformNode(node.setDefault, queryId),\n dropDefault: node.dropDefault,\n setNotNull: node.setNotNull,\n dropNotNull: node.dropNotNull,\n });\n }\n transformModifyColumn(node, queryId) {\n return requireAllProps({\n kind: 'ModifyColumnNode',\n column: this.transformNode(node.column, queryId),\n });\n }\n transformAddConstraint(node, queryId) {\n return requireAllProps({\n kind: 'AddConstraintNode',\n constraint: this.transformNode(node.constraint, queryId),\n });\n }\n transformDropConstraint(node, queryId) {\n return requireAllProps({\n kind: 'DropConstraintNode',\n constraintName: this.transformNode(node.constraintName, queryId),\n ifExists: node.ifExists,\n modifier: node.modifier,\n });\n }\n transformRenameConstraint(node, queryId) {\n return requireAllProps({\n kind: 'RenameConstraintNode',\n oldName: this.transformNode(node.oldName, queryId),\n newName: this.transformNode(node.newName, queryId),\n });\n }\n transformCreateView(node, queryId) {\n return requireAllProps({\n kind: 'CreateViewNode',\n name: this.transformNode(node.name, queryId),\n temporary: node.temporary,\n orReplace: node.orReplace,\n ifNotExists: node.ifNotExists,\n materialized: node.materialized,\n columns: this.transformNodeList(node.columns, queryId),\n as: this.transformNode(node.as, queryId),\n });\n }\n transformRefreshMaterializedView(node, queryId) {\n return requireAllProps({\n kind: 'RefreshMaterializedViewNode',\n name: this.transformNode(node.name, queryId),\n concurrently: node.concurrently,\n withNoData: node.withNoData,\n });\n }\n transformDropView(node, queryId) {\n return requireAllProps({\n kind: 'DropViewNode',\n name: this.transformNode(node.name, queryId),\n ifExists: node.ifExists,\n materialized: node.materialized,\n cascade: node.cascade,\n });\n }\n transformGenerated(node, queryId) {\n return requireAllProps({\n kind: 'GeneratedNode',\n byDefault: node.byDefault,\n always: node.always,\n identity: node.identity,\n stored: node.stored,\n expression: this.transformNode(node.expression, queryId),\n });\n }\n transformDefaultValue(node, queryId) {\n return requireAllProps({\n kind: 'DefaultValueNode',\n defaultValue: this.transformNode(node.defaultValue, queryId),\n });\n }\n transformOn(node, queryId) {\n return requireAllProps({\n kind: 'OnNode',\n on: this.transformNode(node.on, queryId),\n });\n }\n transformSelectModifier(node, queryId) {\n return requireAllProps({\n kind: 'SelectModifierNode',\n modifier: node.modifier,\n rawModifier: this.transformNode(node.rawModifier, queryId),\n of: this.transformNodeList(node.of, queryId),\n });\n }\n transformCreateType(node, queryId) {\n return requireAllProps({\n kind: 'CreateTypeNode',\n name: this.transformNode(node.name, queryId),\n enum: this.transformNode(node.enum, queryId),\n });\n }\n transformDropType(node, queryId) {\n return requireAllProps({\n kind: 'DropTypeNode',\n name: this.transformNode(node.name, queryId),\n ifExists: node.ifExists,\n });\n }\n transformExplain(node, queryId) {\n return requireAllProps({\n kind: 'ExplainNode',\n format: node.format,\n options: this.transformNode(node.options, queryId),\n });\n }\n transformSchemableIdentifier(node, queryId) {\n return requireAllProps({\n kind: 'SchemableIdentifierNode',\n schema: this.transformNode(node.schema, queryId),\n identifier: this.transformNode(node.identifier, queryId),\n });\n }\n transformAggregateFunction(node, queryId) {\n return requireAllProps({\n kind: 'AggregateFunctionNode',\n func: node.func,\n aggregated: this.transformNodeList(node.aggregated, queryId),\n distinct: node.distinct,\n orderBy: this.transformNode(node.orderBy, queryId),\n withinGroup: this.transformNode(node.withinGroup, queryId),\n filter: this.transformNode(node.filter, queryId),\n over: this.transformNode(node.over, queryId),\n });\n }\n transformOver(node, queryId) {\n return requireAllProps({\n kind: 'OverNode',\n orderBy: this.transformNode(node.orderBy, queryId),\n partitionBy: this.transformNode(node.partitionBy, queryId),\n });\n }\n transformPartitionBy(node, queryId) {\n return requireAllProps({\n kind: 'PartitionByNode',\n items: this.transformNodeList(node.items, queryId),\n });\n }\n transformPartitionByItem(node, queryId) {\n return requireAllProps({\n kind: 'PartitionByItemNode',\n partitionBy: this.transformNode(node.partitionBy, queryId),\n });\n }\n transformBinaryOperation(node, queryId) {\n return requireAllProps({\n kind: 'BinaryOperationNode',\n leftOperand: this.transformNode(node.leftOperand, queryId),\n operator: this.transformNode(node.operator, queryId),\n rightOperand: this.transformNode(node.rightOperand, queryId),\n });\n }\n transformUnaryOperation(node, queryId) {\n return requireAllProps({\n kind: 'UnaryOperationNode',\n operator: this.transformNode(node.operator, queryId),\n operand: this.transformNode(node.operand, queryId),\n });\n }\n transformUsing(node, queryId) {\n return requireAllProps({\n kind: 'UsingNode',\n tables: this.transformNodeList(node.tables, queryId),\n });\n }\n transformFunction(node, queryId) {\n return requireAllProps({\n kind: 'FunctionNode',\n func: node.func,\n arguments: this.transformNodeList(node.arguments, queryId),\n });\n }\n transformCase(node, queryId) {\n return requireAllProps({\n kind: 'CaseNode',\n value: this.transformNode(node.value, queryId),\n when: this.transformNodeList(node.when, queryId),\n else: this.transformNode(node.else, queryId),\n isStatement: node.isStatement,\n });\n }\n transformWhen(node, queryId) {\n return requireAllProps({\n kind: 'WhenNode',\n condition: this.transformNode(node.condition, queryId),\n result: this.transformNode(node.result, queryId),\n });\n }\n transformJSONReference(node, queryId) {\n return requireAllProps({\n kind: 'JSONReferenceNode',\n reference: this.transformNode(node.reference, queryId),\n traversal: this.transformNode(node.traversal, queryId),\n });\n }\n transformJSONPath(node, queryId) {\n return requireAllProps({\n kind: 'JSONPathNode',\n inOperator: this.transformNode(node.inOperator, queryId),\n pathLegs: this.transformNodeList(node.pathLegs, queryId),\n });\n }\n transformJSONPathLeg(node, _queryId) {\n return requireAllProps({\n kind: 'JSONPathLegNode',\n type: node.type,\n value: node.value,\n });\n }\n transformJSONOperatorChain(node, queryId) {\n return requireAllProps({\n kind: 'JSONOperatorChainNode',\n operator: this.transformNode(node.operator, queryId),\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformTuple(node, queryId) {\n return requireAllProps({\n kind: 'TupleNode',\n values: this.transformNodeList(node.values, queryId),\n });\n }\n transformMergeQuery(node, queryId) {\n return requireAllProps({\n kind: 'MergeQueryNode',\n into: this.transformNode(node.into, queryId),\n using: this.transformNode(node.using, queryId),\n whens: this.transformNodeList(node.whens, queryId),\n with: this.transformNode(node.with, queryId),\n top: this.transformNode(node.top, queryId),\n endModifiers: this.transformNodeList(node.endModifiers, queryId),\n output: this.transformNode(node.output, queryId),\n returning: this.transformNode(node.returning, queryId),\n });\n }\n transformMatched(node, _queryId) {\n return requireAllProps({\n kind: 'MatchedNode',\n not: node.not,\n bySource: node.bySource,\n });\n }\n transformAddIndex(node, queryId) {\n return requireAllProps({\n kind: 'AddIndexNode',\n name: this.transformNode(node.name, queryId),\n columns: this.transformNodeList(node.columns, queryId),\n unique: node.unique,\n using: this.transformNode(node.using, queryId),\n ifNotExists: node.ifNotExists,\n });\n }\n transformCast(node, queryId) {\n return requireAllProps({\n kind: 'CastNode',\n expression: this.transformNode(node.expression, queryId),\n dataType: this.transformNode(node.dataType, queryId),\n });\n }\n transformFetch(node, queryId) {\n return requireAllProps({\n kind: 'FetchNode',\n rowCount: this.transformNode(node.rowCount, queryId),\n modifier: node.modifier,\n });\n }\n transformTop(node, _queryId) {\n return requireAllProps({\n kind: 'TopNode',\n expression: node.expression,\n modifiers: node.modifiers,\n });\n }\n transformOutput(node, queryId) {\n return requireAllProps({\n kind: 'OutputNode',\n selections: this.transformNodeList(node.selections, queryId),\n });\n }\n transformDataType(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformSelectAll(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformIdentifier(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformValue(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformPrimitiveValueList(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformOperator(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformDefaultInsertValue(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformOrAction(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n transformCollate(node, _queryId) {\n // An Object.freezed leaf node. No need to clone.\n return node;\n }\n}\n","/// <reference types=\"./with-schema-transformer.d.ts\" />\nimport { AliasNode } from '../../operation-node/alias-node.js';\nimport { IdentifierNode } from '../../operation-node/identifier-node.js';\nimport { JoinNode } from '../../operation-node/join-node.js';\nimport { ListNode } from '../../operation-node/list-node.js';\nimport { OperationNodeTransformer } from '../../operation-node/operation-node-transformer.js';\nimport { SchemableIdentifierNode } from '../../operation-node/schemable-identifier-node.js';\nimport { TableNode } from '../../operation-node/table-node.js';\nimport { UsingNode } from '../../operation-node/using-node.js';\nimport { freeze } from '../../util/object-utils.js';\n// This object exist only so that we get a type error when a new RootOperationNode\n// is added. If you get a type error here, make sure to add the new root node and\n// handle it correctly in the transformer.\n//\n// DO NOT REFACTOR THIS EVEN IF IT SEEMS USELESS TO YOU!\nconst ROOT_OPERATION_NODES = freeze({\n AlterTableNode: true,\n CreateIndexNode: true,\n CreateSchemaNode: true,\n CreateTableNode: true,\n CreateTypeNode: true,\n CreateViewNode: true,\n RefreshMaterializedViewNode: true,\n DeleteQueryNode: true,\n DropIndexNode: true,\n DropSchemaNode: true,\n DropTableNode: true,\n DropTypeNode: true,\n DropViewNode: true,\n InsertQueryNode: true,\n RawNode: true,\n SelectQueryNode: true,\n UpdateQueryNode: true,\n MergeQueryNode: true,\n});\nconst SCHEMALESS_FUNCTIONS = {\n json_agg: true,\n to_json: true,\n};\nexport class WithSchemaTransformer extends OperationNodeTransformer {\n #schema;\n #schemableIds = new Set();\n #ctes = new Set();\n constructor(schema) {\n super();\n this.#schema = schema;\n }\n transformNodeImpl(node, queryId) {\n if (!this.#isRootOperationNode(node)) {\n return super.transformNodeImpl(node, queryId);\n }\n const ctes = this.#collectCTEs(node);\n for (const cte of ctes) {\n this.#ctes.add(cte);\n }\n const tables = this.#collectSchemableIds(node);\n for (const table of tables) {\n this.#schemableIds.add(table);\n }\n const transformed = super.transformNodeImpl(node, queryId);\n for (const table of tables) {\n this.#schemableIds.delete(table);\n }\n for (const cte of ctes) {\n this.#ctes.delete(cte);\n }\n return transformed;\n }\n transformSchemableIdentifier(node, queryId) {\n const transformed = super.transformSchemableIdentifier(node, queryId);\n if (transformed.schema || !this.#schemableIds.has(node.identifier.name)) {\n return transformed;\n }\n return {\n ...transformed,\n schema: IdentifierNode.create(this.#schema),\n };\n }\n transformReferences(node, queryId) {\n const transformed = super.transformReferences(node, queryId);\n if (transformed.table.table.schema) {\n return transformed;\n }\n return {\n ...transformed,\n table: TableNode.createWithSchema(this.#schema, transformed.table.table.identifier.name),\n };\n }\n transformAggregateFunction(node, queryId) {\n return {\n ...super.transformAggregateFunction({ ...node, aggregated: [] }, queryId),\n aggregated: this.#transformTableArgsWithoutSchemas(node, queryId, 'aggregated'),\n };\n }\n transformFunction(node, queryId) {\n return {\n ...super.transformFunction({ ...node, arguments: [] }, queryId),\n arguments: this.#transformTableArgsWithoutSchemas(node, queryId, 'arguments'),\n };\n }\n transformSelectModifier(node, queryId) {\n return {\n ...super.transformSelectModifier({ ...node, of: undefined }, queryId),\n of: node.of?.map((item) => TableNode.is(item) && !item.table.schema\n ? {\n ...item,\n table: this.transformIdentifier(item.table.identifier, queryId),\n }\n : this.transformNode(item, queryId)),\n };\n }\n #transformTableArgsWithoutSchemas(node, queryId, argsKey) {\n return SCHEMALESS_FUNCTIONS[node.func]\n ? node[argsKey].map((arg) => !TableNode.is(arg) || arg.table.schema\n ? this.transformNode(arg, queryId)\n : {\n ...arg,\n table: this.transformIdentifier(arg.table.identifier, queryId),\n })\n : this.transformNodeList(node[argsKey], queryId);\n }\n #isRootOperationNode(node) {\n return node.kind in ROOT_OPERATION_NODES;\n }\n #collectSchemableIds(node) {\n const schemableIds = new Set();\n if ('name' in node && node.name && SchemableIdentifierNode.is(node.name)) {\n this.#collectSchemableId(node.name, schemableIds);\n }\n if ('from' in node && node.from) {\n for (const from of node.from.froms) {\n this.#collectSchemableIdsFromTableExpr(from, schemableIds);\n }\n }\n if ('into' in node && node.into) {\n this.#collectSchemableIdsFromTableExpr(node.into, schemableIds);\n }\n if ('table' in node && node.table) {\n this.#collectSchemableIdsFromTableExpr(node.table, schemableIds);\n }\n if ('joins' in node && node.joins) {\n for (const join of node.joins) {\n this.#collectSchemableIdsFromTableExpr(join.table, schemableIds);\n }\n }\n if ('using' in node && node.using) {\n if (JoinNode.is(node.using)) {\n this.#collectSchemableIdsFromTableExpr(node.using.table, schemableIds);\n }\n else {\n this.#collectSchemableIdsFromTableExpr(node.using, schemableIds);\n }\n }\n return schemableIds;\n }\n #collectCTEs(node) {\n const ctes = new Set();\n if ('with' in node && node.with) {\n this.#collectCTEIds(node.with, ctes);\n }\n return ctes;\n }\n #collectSchemableIdsFromTableExpr(node, schemableIds) {\n if (TableNode.is(node)) {\n return this.#collectSchemableId(node.table, schemableIds);\n }\n if (AliasNode.is(node) && TableNode.is(node.node)) {\n return this.#collectSchemableId(node.node.table, schemableIds);\n }\n if (ListNode.is(node)) {\n for (const table of node.items) {\n this.#collectSchemableIdsFromTableExpr(table, schemableIds);\n }\n return;\n }\n if (UsingNode.is(node)) {\n for (const table of node.tables) {\n this.#collectSchemableIdsFromTableExpr(table, schemableIds);\n }\n return;\n }\n }\n #collectSchemableId(node, schemableIds) {\n const id = node.identifier.name;\n if (!this.#schemableIds.has(id) && !this.#ctes.has(id)) {\n schemableIds.add(id);\n }\n }\n #collectCTEIds(node, ctes) {\n for (const expr of node.expressions) {\n const cteId = expr.name.table.table.identifier.name;\n if (!this.#ctes.has(cteId)) {\n ctes.add(cteId);\n }\n }\n }\n}\n","/// <reference types=\"./with-schema-plugin.d.ts\" />\nimport { WithSchemaTransformer } from './with-schema-transformer.js';\nexport class WithSchemaPlugin {\n #transformer;\n constructor(schema) {\n this.#transformer = new WithSchemaTransformer(schema);\n }\n transformQuery(args) {\n return this.#transformer.transformNode(args.node, args.queryId);\n }\n async transformResult(args) {\n return args.result;\n }\n}\n","/// <reference types=\"./deferred.d.ts\" />\nexport class Deferred {\n #promise;\n #resolve;\n #reject;\n constructor() {\n this.#promise = new Promise((resolve, reject) => {\n this.#reject = reject;\n this.#resolve = resolve;\n });\n }\n get promise() {\n return this.#promise;\n }\n resolve = (value) => {\n if (this.#resolve) {\n this.#resolve(value);\n }\n };\n reject = (reason) => {\n if (this.#reject) {\n this.#reject(reason);\n }\n };\n}\n","/// <reference types=\"./provide-controlled-connection.d.ts\" />\nimport { Deferred } from './deferred.js';\nimport { freeze } from './object-utils.js';\nexport async function provideControlledConnection(connectionProvider) {\n const connectionDefer = new Deferred();\n const connectionReleaseDefer = new Deferred();\n connectionProvider\n .provideConnection(async (connection) => {\n connectionDefer.resolve(connection);\n return await connectionReleaseDefer.promise;\n })\n .catch((ex) => connectionDefer.reject(ex));\n // Create composite of the connection and the release method instead of\n // modifying the connection or creating a new nesting `DatabaseConnection`.\n // This way we don't accidentally override any methods of 3rd party\n // connections and don't return wrapped connections to drivers that\n // expect a certain specific connection class.\n return freeze({\n connection: await connectionDefer.promise,\n release: connectionReleaseDefer.resolve,\n });\n}\n","/// <reference types=\"./query-executor-base.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { provideControlledConnection } from '../util/provide-controlled-connection.js';\nimport { logOnce } from '../util/log-once.js';\nconst NO_PLUGINS = freeze([]);\nexport class QueryExecutorBase {\n #plugins;\n constructor(plugins = NO_PLUGINS) {\n this.#plugins = plugins;\n }\n get plugins() {\n return this.#plugins;\n }\n transformQuery(node, queryId) {\n for (const plugin of this.#plugins) {\n const transformedNode = plugin.transformQuery({ node, queryId });\n // We need to do a runtime check here. There is no good way\n // to write types that enforce this constraint.\n if (transformedNode.kind === node.kind) {\n node = transformedNode;\n }\n else {\n throw new Error([\n `KyselyPlugin.transformQuery must return a node`,\n `of the same kind that was given to it.`,\n `The plugin was given a ${node.kind}`,\n `but it returned a ${transformedNode.kind}`,\n ].join(' '));\n }\n }\n return node;\n }\n async executeQuery(compiledQuery) {\n return await this.provideConnection(async (connection) => {\n const result = await connection.executeQuery(compiledQuery);\n if ('numUpdatedOrDeletedRows' in result) {\n logOnce('kysely:warning: outdated driver/plugin detected! `QueryResult.numUpdatedOrDeletedRows` has been replaced with `QueryResult.numAffectedRows`.');\n }\n return await this.#transformResult(result, compiledQuery.queryId);\n });\n }\n async *stream(compiledQuery, chunkSize) {\n const { connection, release } = await provideControlledConnection(this);\n try {\n for await (const result of connection.streamQuery(compiledQuery, chunkSize)) {\n yield await this.#transformResult(result, compiledQuery.queryId);\n }\n }\n finally {\n release();\n }\n }\n async #transformResult(result, queryId) {\n for (const plugin of this.#plugins) {\n result = await plugin.transformResult({ result, queryId });\n }\n return result;\n }\n}\n","/// <reference types=\"./noop-query-executor.d.ts\" />\nimport { QueryExecutorBase } from './query-executor-base.js';\n/**\n * A {@link QueryExecutor} subclass that can be used when you don't\n * have a {@link QueryCompiler}, {@link ConnectionProvider} or any\n * other needed things to actually execute queries.\n */\nexport class NoopQueryExecutor extends QueryExecutorBase {\n get adapter() {\n throw new Error('this query cannot be compiled to SQL');\n }\n compileQuery() {\n throw new Error('this query cannot be compiled to SQL');\n }\n provideConnection() {\n throw new Error('this query cannot be executed');\n }\n withConnectionProvider() {\n throw new Error('this query cannot have a connection provider');\n }\n withPlugin(plugin) {\n return new NoopQueryExecutor([...this.plugins, plugin]);\n }\n withPlugins(plugins) {\n return new NoopQueryExecutor([...this.plugins, ...plugins]);\n }\n withPluginAtFront(plugin) {\n return new NoopQueryExecutor([plugin, ...this.plugins]);\n }\n withoutPlugins() {\n return new NoopQueryExecutor([]);\n }\n}\nexport const NOOP_QUERY_EXECUTOR = new NoopQueryExecutor();\n","/// <reference types=\"./parse-utils.d.ts\" />\nimport { JoinNode } from '../operation-node/join-node.js';\nimport { OverNode } from '../operation-node/over-node.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { JoinBuilder } from '../query-builder/join-builder.js';\nimport { OverBuilder } from '../query-builder/over-builder.js';\nimport { createSelectQueryBuilder as newSelectQueryBuilder, } from '../query-builder/select-query-builder.js';\nimport { QueryCreator } from '../query-creator.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { parseTableExpression, parseTableExpressionOrList, } from './table-parser.js';\nexport function createSelectQueryBuilder() {\n return newSelectQueryBuilder({\n queryId: createQueryId(),\n executor: NOOP_QUERY_EXECUTOR,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList([])),\n });\n}\nexport function createQueryCreator() {\n return new QueryCreator({\n executor: NOOP_QUERY_EXECUTOR,\n });\n}\nexport function createJoinBuilder(joinType, table) {\n return new JoinBuilder({\n joinNode: JoinNode.create(joinType, parseTableExpression(table)),\n });\n}\nexport function createOverBuilder() {\n return new OverBuilder({\n overNode: OverNode.create(),\n });\n}\n","/// <reference types=\"./join-parser.d.ts\" />\nimport { JoinNode } from '../operation-node/join-node.js';\nimport { parseReferentialBinaryOperation } from './binary-operation-parser.js';\nimport { createJoinBuilder } from './parse-utils.js';\nimport { parseTableExpression, } from './table-parser.js';\nexport function parseJoin(joinType, args) {\n if (args.length === 3) {\n return parseSingleOnJoin(joinType, args[0], args[1], args[2]);\n }\n else if (args.length === 2) {\n return parseCallbackJoin(joinType, args[0], args[1]);\n }\n else if (args.length === 1) {\n return parseOnlessJoin(joinType, args[0]);\n }\n else {\n throw new Error('not implemented');\n }\n}\nfunction parseCallbackJoin(joinType, from, callback) {\n return callback(createJoinBuilder(joinType, from)).toOperationNode();\n}\nfunction parseSingleOnJoin(joinType, from, lhsColumn, rhsColumn) {\n return JoinNode.createWithOn(joinType, parseTableExpression(from), parseReferentialBinaryOperation(lhsColumn, '=', rhsColumn));\n}\nfunction parseOnlessJoin(joinType, from) {\n return JoinNode.create(joinType, parseTableExpression(from));\n}\n","/// <reference types=\"./offset-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const OffsetNode = freeze({\n is(node) {\n return node.kind === 'OffsetNode';\n },\n create(offset) {\n return freeze({\n kind: 'OffsetNode',\n offset,\n });\n },\n});\n","/// <reference types=\"./group-by-item-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const GroupByItemNode = freeze({\n is(node) {\n return node.kind === 'GroupByItemNode';\n },\n create(groupBy) {\n return freeze({\n kind: 'GroupByItemNode',\n groupBy,\n });\n },\n});\n","/// <reference types=\"./group-by-parser.d.ts\" />\nimport { GroupByItemNode } from '../operation-node/group-by-item-node.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nimport { parseReferenceExpressionOrList, } from './reference-parser.js';\nexport function parseGroupBy(groupBy) {\n groupBy = isFunction(groupBy) ? groupBy(expressionBuilder()) : groupBy;\n return parseReferenceExpressionOrList(groupBy).map(GroupByItemNode.create);\n}\n","/// <reference types=\"./set-operation-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const SetOperationNode = freeze({\n is(node) {\n return node.kind === 'SetOperationNode';\n },\n create(operator, expression, all) {\n return freeze({\n kind: 'SetOperationNode',\n operator,\n expression,\n all,\n });\n },\n});\n","/// <reference types=\"./set-operation-parser.d.ts\" />\nimport { createExpressionBuilder, } from '../expression/expression-builder.js';\nimport { SetOperationNode, } from '../operation-node/set-operation-node.js';\nimport { isFunction, isReadonlyArray } from '../util/object-utils.js';\nimport { parseExpression } from './expression-parser.js';\nexport function parseSetOperations(operator, expression, all) {\n if (isFunction(expression)) {\n expression = expression(createExpressionBuilder());\n }\n if (!isReadonlyArray(expression)) {\n expression = [expression];\n }\n return expression.map((expr) => SetOperationNode.create(operator, parseExpression(expr), all));\n}\n","/// <reference types=\"./expression-wrapper.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { OrNode } from '../operation-node/or-node.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nexport class ExpressionWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n or(...args) {\n return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n and(...args) {\n return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `ExpressionWrapper` with a new output type.\n */\n $castTo() {\n return new ExpressionWrapper(this.#node);\n }\n /**\n * Omit null from the expression's type.\n *\n * This function can be useful in cases where you know an expression can't be\n * null, but Kysely is unable to infer it.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of `this` with a new output type.\n */\n $notNull() {\n return new ExpressionWrapper(this.#node);\n }\n toOperationNode() {\n return this.#node;\n }\n}\nexport class AliasedExpressionWrapper {\n #expr;\n #alias;\n constructor(expr, alias) {\n this.#expr = expr;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#expr;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#expr.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\nexport class OrWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n or(...args) {\n return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `OrWrapper` with a new output type.\n */\n $castTo() {\n return new OrWrapper(this.#node);\n }\n toOperationNode() {\n return ParensNode.create(this.#node);\n }\n}\nexport class AndWrapper {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedExpressionWrapper(this, alias);\n }\n and(...args) {\n return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));\n }\n /**\n * Change the output type of the expression.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `AndWrapper` with a new output type.\n */\n $castTo() {\n return new AndWrapper(this.#node);\n }\n toOperationNode() {\n return ParensNode.create(this.#node);\n }\n}\n","/// <reference types=\"./fetch-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { ValueNode } from './value-node.js';\n/**\n * @internal\n */\nexport const FetchNode = freeze({\n is(node) {\n return node.kind === 'FetchNode';\n },\n create(rowCount, modifier) {\n return {\n kind: 'FetchNode',\n rowCount: ValueNode.create(rowCount),\n modifier,\n };\n },\n});\n","/// <reference types=\"./fetch-parser.d.ts\" />\nimport { FetchNode } from '../operation-node/fetch-node.js';\nimport { isBigInt, isNumber } from '../util/object-utils.js';\nexport function parseFetch(rowCount, modifier) {\n if (!isNumber(rowCount) && !isBigInt(rowCount)) {\n throw new Error(`Invalid fetch row count: ${rowCount}`);\n }\n if (!isFetchModifier(modifier)) {\n throw new Error(`Invalid fetch modifier: ${modifier}`);\n }\n return FetchNode.create(rowCount, modifier);\n}\nfunction isFetchModifier(value) {\n return value === 'only' || value === 'with ties';\n}\n","/// <reference types=\"./select-query-builder.d.ts\" />\nvar _a;\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { SelectModifierNode } from '../operation-node/select-modifier-node.js';\nimport { parseJoin, } from '../parser/join-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseSelectArg, parseSelectAll, } from '../parser/select-parser.js';\nimport { parseReferenceExpressionOrList, } from '../parser/reference-parser.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { LimitNode } from '../operation-node/limit-node.js';\nimport { OffsetNode } from '../operation-node/offset-node.js';\nimport { asArray, freeze } from '../util/object-utils.js';\nimport { parseGroupBy } from '../parser/group-by-parser.js';\nimport { isNoResultErrorConstructor, NoResultError, } from './no-result-error.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { parseSetOperations, } from '../parser/set-operation-parser.js';\nimport { parseValueBinaryOperationOrExpression, parseReferentialBinaryOperation, } from '../parser/binary-operation-parser.js';\nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { parseValueExpression, } from '../parser/value-parser.js';\nimport { parseFetch } from '../parser/fetch-parser.js';\nimport { parseTop } from '../parser/top-parser.js';\nclass SelectQueryBuilderImpl {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n get expressionType() {\n return undefined;\n }\n get isSelectQueryBuilder() {\n return true;\n }\n where(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n whereRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n having(...args) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n havingRef(lhs, op, rhs) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n select(selection) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectArg(selection)),\n });\n }\n distinctOn(selection) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithDistinctOn(this.#props.queryNode, parseReferenceExpressionOrList(selection)),\n });\n }\n modifyFront(modifier) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())),\n });\n }\n modifyEnd(modifier) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode())),\n });\n }\n distinct() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.create('Distinct')),\n });\n }\n forUpdate(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForUpdate', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forShare(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForShare', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forKeyShare(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForKeyShare', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n forNoKeyUpdate(of) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('ForNoKeyUpdate', of ? asArray(of).map(parseTable) : undefined)),\n });\n }\n skipLocked() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('SkipLocked')),\n });\n }\n noWait() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create('NoWait')),\n });\n }\n selectAll(table) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectAll(table)),\n });\n }\n innerJoin(...args) {\n return this.#join('InnerJoin', args);\n }\n leftJoin(...args) {\n return this.#join('LeftJoin', args);\n }\n rightJoin(...args) {\n return this.#join('RightJoin', args);\n }\n fullJoin(...args) {\n return this.#join('FullJoin', args);\n }\n crossJoin(...args) {\n return this.#join('CrossJoin', args);\n }\n innerJoinLateral(...args) {\n return this.#join('LateralInnerJoin', args);\n }\n leftJoinLateral(...args) {\n return this.#join('LateralLeftJoin', args);\n }\n crossJoinLateral(...args) {\n return this.#join('LateralCrossJoin', args);\n }\n crossApply(...args) {\n return this.#join('CrossApply', args);\n }\n outerApply(...args) {\n return this.#join('OuterApply', args);\n }\n #join(joinType, args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args)),\n });\n }\n orderBy(...args) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args)),\n });\n }\n groupBy(groupBy) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithGroupByItems(this.#props.queryNode, parseGroupBy(groupBy)),\n });\n }\n limit(limit) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit))),\n });\n }\n offset(offset) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithOffset(this.#props.queryNode, OffsetNode.create(parseValueExpression(offset))),\n });\n }\n fetch(rowCount, modifier = 'only') {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithFetch(this.#props.queryNode, parseFetch(rowCount, modifier)),\n });\n }\n top(expression, modifiers) {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers)),\n });\n }\n union(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('union', expression, false)),\n });\n }\n unionAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('union', expression, true)),\n });\n }\n intersect(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('intersect', expression, false)),\n });\n }\n intersectAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('intersect', expression, true)),\n });\n }\n except(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('except', expression, false)),\n });\n }\n exceptAll(expression) {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations('except', expression, true)),\n });\n }\n as(alias) {\n return new AliasedSelectQueryBuilderImpl(this, alias);\n }\n clearSelect() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutSelections(this.#props.queryNode),\n });\n }\n clearWhere() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode),\n });\n }\n clearLimit() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutLimit(this.#props.queryNode),\n });\n }\n clearOffset() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutOffset(this.#props.queryNode),\n });\n }\n clearOrderBy() {\n return new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode),\n });\n }\n clearGroupBy() {\n return new _a({\n ...this.#props,\n queryNode: SelectQueryNode.cloneWithoutGroupBy(this.#props.queryNode),\n });\n }\n $call(func) {\n return func(this);\n }\n $if(condition, func) {\n if (condition) {\n return func(this);\n }\n return new _a({\n ...this.#props,\n });\n }\n $castTo() {\n return new _a(this.#props);\n }\n $narrowType() {\n return new _a(this.#props);\n }\n $assertType() {\n return new _a(this.#props);\n }\n $asTuple() {\n return new ExpressionWrapper(this.toOperationNode());\n }\n $asScalar() {\n return new ExpressionWrapper(this.toOperationNode());\n }\n withPlugin(plugin) {\n return new _a({\n ...this.#props,\n executor: this.#props.executor.withPlugin(plugin),\n });\n }\n toOperationNode() {\n return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);\n }\n compile() {\n return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);\n }\n async execute() {\n const compiledQuery = this.compile();\n const result = await this.#props.executor.executeQuery(compiledQuery);\n return result.rows;\n }\n async executeTakeFirst() {\n const [result] = await this.execute();\n return result;\n }\n async executeTakeFirstOrThrow(errorConstructor = NoResultError) {\n const result = await this.executeTakeFirst();\n if (result === undefined) {\n const error = isNoResultErrorConstructor(errorConstructor)\n ? new errorConstructor(this.toOperationNode())\n : errorConstructor(this.toOperationNode());\n throw error;\n }\n return result;\n }\n async *stream(chunkSize = 100) {\n const compiledQuery = this.compile();\n const stream = this.#props.executor.stream(compiledQuery, chunkSize);\n for await (const item of stream) {\n yield* item.rows;\n }\n }\n async explain(format, options) {\n const builder = new _a({\n ...this.#props,\n queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options),\n });\n return await builder.execute();\n }\n}\n_a = SelectQueryBuilderImpl;\nexport function createSelectQueryBuilder(props) {\n return new SelectQueryBuilderImpl(props);\n}\n/**\n * {@link SelectQueryBuilder} with an alias. The result of calling {@link SelectQueryBuilder.as}.\n */\nclass AliasedSelectQueryBuilderImpl {\n #queryBuilder;\n #alias;\n constructor(queryBuilder, alias) {\n this.#queryBuilder = queryBuilder;\n this.#alias = alias;\n }\n get expression() {\n return this.#queryBuilder;\n }\n get alias() {\n return this.#alias;\n }\n get isAliasedSelectQueryBuilder() {\n return true;\n }\n toOperationNode() {\n return AliasNode.create(this.#queryBuilder.toOperationNode(), IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./aggregate-function-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { WhereNode } from './where-node.js';\nimport { OrderByNode } from './order-by-node.js';\n/**\n * @internal\n */\nexport const AggregateFunctionNode = freeze({\n is(node) {\n return node.kind === 'AggregateFunctionNode';\n },\n create(aggregateFunction, aggregated = []) {\n return freeze({\n kind: 'AggregateFunctionNode',\n func: aggregateFunction,\n aggregated,\n });\n },\n cloneWithDistinct(aggregateFunctionNode) {\n return freeze({\n ...aggregateFunctionNode,\n distinct: true,\n });\n },\n cloneWithOrderBy(aggregateFunctionNode, orderItems, withinGroup = false) {\n const prop = withinGroup ? 'withinGroup' : 'orderBy';\n return freeze({\n ...aggregateFunctionNode,\n [prop]: aggregateFunctionNode[prop]\n ? OrderByNode.cloneWithItems(aggregateFunctionNode[prop], orderItems)\n : OrderByNode.create(orderItems),\n });\n },\n cloneWithFilter(aggregateFunctionNode, filter) {\n return freeze({\n ...aggregateFunctionNode,\n filter: aggregateFunctionNode.filter\n ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, 'And', filter)\n : WhereNode.create(filter),\n });\n },\n cloneWithOrFilter(aggregateFunctionNode, filter) {\n return freeze({\n ...aggregateFunctionNode,\n filter: aggregateFunctionNode.filter\n ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, 'Or', filter)\n : WhereNode.create(filter),\n });\n },\n cloneWithOver(aggregateFunctionNode, over) {\n return freeze({\n ...aggregateFunctionNode,\n over,\n });\n },\n});\n","/// <reference types=\"./function-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const FunctionNode = freeze({\n is(node) {\n return node.kind === 'FunctionNode';\n },\n create(func, args) {\n return freeze({\n kind: 'FunctionNode',\n func,\n arguments: args,\n });\n },\n});\n","/// <reference types=\"./aggregate-function-builder.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { AggregateFunctionNode } from '../operation-node/aggregate-function-node.js';\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { createOverBuilder } from '../parser/parse-utils.js';\nimport { parseReferentialBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { parseOrderBy, } from '../parser/order-by-parser.js';\nimport { QueryNode } from '../operation-node/query-node.js';\nexport class AggregateFunctionBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n /**\n * Returns an aliased version of the function.\n *\n * In addition to slapping `as \"the_alias\"` to the end of the SQL,\n * this method also provides strict typing:\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.count<number>('id').as('person_count')\n * )\n * .executeTakeFirstOrThrow()\n *\n * // `person_count: number` field exists in the result type.\n * console.log(result.person_count)\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select count(\"id\") as \"person_count\"\n * from \"person\"\n * ```\n */\n as(alias) {\n return new AliasedAggregateFunctionBuilder(this, alias);\n }\n /**\n * Adds a `distinct` clause inside the function.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select((eb) =>\n * eb.fn.count<number>('first_name').distinct().as('first_name_count')\n * )\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select count(distinct \"first_name\") as \"first_name_count\"\n * from \"person\"\n * ```\n */\n distinct() {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithDistinct(this.#props.aggregateFunctionNode),\n });\n }\n orderBy(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: QueryNode.cloneWithOrderByItems(this.#props.aggregateFunctionNode, parseOrderBy(args)),\n });\n }\n clearOrderBy() {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: QueryNode.cloneWithoutOrderBy(this.#props.aggregateFunctionNode),\n });\n }\n withinGroupOrderBy(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithOrderBy(this.#props.aggregateFunctionNode, parseOrderBy(args), true),\n });\n }\n filterWhere(...args) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseValueBinaryOperationOrExpression(args)),\n });\n }\n /**\n * Adds a `filter` clause with a nested `where` clause after the function, where\n * both sides of the operator are references to columns.\n *\n * Similar to {@link WhereInterface}'s `whereRef` method.\n *\n * ### Examples\n *\n * Count people with same first and last names versus general public:\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select((eb) => [\n * eb.fn\n * .count<number>('id')\n * .filterWhereRef('first_name', '=', 'last_name')\n * .as('repeat_name_count'),\n * eb.fn.count<number>('id').as('total_count'),\n * ])\n * .executeTakeFirstOrThrow()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select\n * count(\"id\") filter(where \"first_name\" = \"last_name\") as \"repeat_name_count\",\n * count(\"id\") as \"total_count\"\n * from \"person\"\n * ```\n */\n filterWhereRef(lhs, op, rhs) {\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseReferentialBinaryOperation(lhs, op, rhs)),\n });\n }\n /**\n * Adds an `over` clause (window functions) after the function.\n *\n * ### Examples\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.avg<number>('age').over().as('average_age')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select avg(\"age\") over() as \"average_age\"\n * from \"person\"\n * ```\n *\n * Also supports passing a callback that returns an over builder,\n * allowing to add partition by and sort by clauses inside over.\n *\n * ```ts\n * const result = await db\n * .selectFrom('person')\n * .select(\n * (eb) => eb.fn.avg<number>('age').over(\n * ob => ob.partitionBy('last_name').orderBy('first_name', 'asc')\n * ).as('average_age')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select avg(\"age\") over(partition by \"last_name\" order by \"first_name\" asc) as \"average_age\"\n * from \"person\"\n * ```\n */\n over(over) {\n const builder = createOverBuilder();\n return new AggregateFunctionBuilder({\n ...this.#props,\n aggregateFunctionNode: AggregateFunctionNode.cloneWithOver(this.#props.aggregateFunctionNode, (over ? over(builder) : builder).toOperationNode()),\n });\n }\n /**\n * Simply calls the provided function passing `this` as the only argument. `$call` returns\n * what the provided function returns.\n */\n $call(func) {\n return func(this);\n }\n /**\n * Casts the expression to the given type.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `AggregateFunctionBuilder` with a new output type.\n */\n $castTo() {\n return new AggregateFunctionBuilder(this.#props);\n }\n /**\n * Omit null from the expression's type.\n *\n * This function can be useful in cases where you know an expression can't be\n * null, but Kysely is unable to infer it.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of `this` with a new output type.\n */\n $notNull() {\n return new AggregateFunctionBuilder(this.#props);\n }\n toOperationNode() {\n return this.#props.aggregateFunctionNode;\n }\n}\n/**\n * {@link AggregateFunctionBuilder} with an alias. The result of calling {@link AggregateFunctionBuilder.as}.\n */\nexport class AliasedAggregateFunctionBuilder {\n #aggregateFunctionBuilder;\n #alias;\n constructor(aggregateFunctionBuilder, alias) {\n this.#aggregateFunctionBuilder = aggregateFunctionBuilder;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#aggregateFunctionBuilder;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#aggregateFunctionBuilder.toOperationNode(), IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./function-module.d.ts\" />\nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { AggregateFunctionNode } from '../operation-node/aggregate-function-node.js';\nimport { FunctionNode } from '../operation-node/function-node.js';\nimport { parseReferenceExpressionOrList, } from '../parser/reference-parser.js';\nimport { parseSelectAll } from '../parser/select-parser.js';\nimport { AggregateFunctionBuilder } from './aggregate-function-builder.js';\nimport { isString } from '../util/object-utils.js';\nimport { parseTable } from '../parser/table-parser.js';\nexport function createFunctionModule() {\n const fn = (name, args) => {\n return new ExpressionWrapper(FunctionNode.create(name, parseReferenceExpressionOrList(args ?? [])));\n };\n const agg = (name, args) => {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create(name, args ? parseReferenceExpressionOrList(args) : undefined),\n });\n };\n return Object.assign(fn, {\n agg,\n avg(column) {\n return agg('avg', [column]);\n },\n coalesce(...values) {\n return fn('coalesce', values);\n },\n count(column) {\n return agg('count', [column]);\n },\n countAll(table) {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create('count', parseSelectAll(table)),\n });\n },\n max(column) {\n return agg('max', [column]);\n },\n min(column) {\n return agg('min', [column]);\n },\n sum(column) {\n return agg('sum', [column]);\n },\n any(column) {\n return fn('any', [column]);\n },\n jsonAgg(table) {\n return new AggregateFunctionBuilder({\n aggregateFunctionNode: AggregateFunctionNode.create('json_agg', [\n isString(table) ? parseTable(table) : table.toOperationNode(),\n ]),\n });\n },\n toJson(table) {\n return new ExpressionWrapper(FunctionNode.create('to_json', [\n isString(table) ? parseTable(table) : table.toOperationNode(),\n ]));\n },\n });\n}\n","/// <reference types=\"./unary-operation-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const UnaryOperationNode = freeze({\n is(node) {\n return node.kind === 'UnaryOperationNode';\n },\n create(operator, operand) {\n return freeze({\n kind: 'UnaryOperationNode',\n operator,\n operand,\n });\n },\n});\n","/// <reference types=\"./unary-operation-parser.d.ts\" />\nimport { OperatorNode, } from '../operation-node/operator-node.js';\nimport { UnaryOperationNode } from '../operation-node/unary-operation-node.js';\nimport { parseReferenceExpression, } from './reference-parser.js';\nexport function parseExists(operand) {\n return parseUnaryOperation('exists', operand);\n}\nexport function parseNotExists(operand) {\n return parseUnaryOperation('not exists', operand);\n}\nexport function parseUnaryOperation(operator, operand) {\n return UnaryOperationNode.create(OperatorNode.create(operator), parseReferenceExpression(operand));\n}\n","/// <reference types=\"./case-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nimport { WhenNode } from './when-node.js';\n/**\n * @internal\n */\nexport const CaseNode = freeze({\n is(node) {\n return node.kind === 'CaseNode';\n },\n create(value) {\n return freeze({\n kind: 'CaseNode',\n value,\n });\n },\n cloneWithWhen(caseNode, when) {\n return freeze({\n ...caseNode,\n when: freeze(caseNode.when ? [...caseNode.when, when] : [when]),\n });\n },\n cloneWithThen(caseNode, then) {\n return freeze({\n ...caseNode,\n when: caseNode.when\n ? freeze([\n ...caseNode.when.slice(0, -1),\n WhenNode.cloneWithResult(caseNode.when[caseNode.when.length - 1], then),\n ])\n : undefined,\n });\n },\n cloneWith(caseNode, props) {\n return freeze({\n ...caseNode,\n ...props,\n });\n },\n});\n","/// <reference types=\"./case-builder.d.ts\" />\nimport { ExpressionWrapper } from '../expression/expression-wrapper.js';\nimport { freeze } from '../util/object-utils.js';\nimport { CaseNode } from '../operation-node/case-node.js';\nimport { WhenNode } from '../operation-node/when-node.js';\nimport { parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { isSafeImmediateValue, parseSafeImmediateValue, parseValueExpression, } from '../parser/value-parser.js';\nexport class CaseBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n when(...args) {\n return new CaseThenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))),\n });\n }\n}\nexport class CaseThenBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n then(valueExpression) {\n return new CaseWhenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithThen(this.#props.node, isSafeImmediateValue(valueExpression)\n ? parseSafeImmediateValue(valueExpression)\n : parseValueExpression(valueExpression)),\n });\n }\n}\nexport class CaseWhenBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n when(...args) {\n return new CaseThenBuilder({\n ...this.#props,\n node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args))),\n });\n }\n else(valueExpression) {\n return new CaseEndBuilder({\n ...this.#props,\n node: CaseNode.cloneWith(this.#props.node, {\n else: isSafeImmediateValue(valueExpression)\n ? parseSafeImmediateValue(valueExpression)\n : parseValueExpression(valueExpression),\n }),\n });\n }\n end() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));\n }\n endCase() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));\n }\n}\nexport class CaseEndBuilder {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n end() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));\n }\n endCase() {\n return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));\n }\n}\n","/// <reference types=\"./json-path-leg-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const JSONPathLegNode = freeze({\n is(node) {\n return node.kind === 'JSONPathLegNode';\n },\n create(type, value) {\n return freeze({\n kind: 'JSONPathLegNode',\n type,\n value,\n });\n },\n});\n","/// <reference types=\"./json-path-builder.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { JSONOperatorChainNode } from '../operation-node/json-operator-chain-node.js';\nimport { JSONPathLegNode, } from '../operation-node/json-path-leg-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nimport { JSONReferenceNode } from '../operation-node/json-reference-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nexport class JSONPathBuilder {\n #node;\n constructor(node) {\n this.#node = node;\n }\n /**\n * Access an element of a JSON array in a specific location.\n *\n * Since there's no guarantee an element exists in the given array location, the\n * resulting type is always nullable. If you're sure the element exists, you\n * should use {@link SelectQueryBuilder.$assertType} to narrow the type safely.\n *\n * See also {@link key} to access properties of JSON objects.\n *\n * ### Examples\n *\n * ```ts\n * await db.selectFrom('person')\n * .select(eb =>\n * eb.ref('nicknames', '->').at(0).as('primary_nickname')\n * )\n * .execute()\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"nicknames\"->0 as \"primary_nickname\" from \"person\"\n *```\n *\n * Combined with {@link key}:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('experience', '->').at(0).key('role').as('first_role')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"experience\"->0->'role' as \"first_role\" from \"person\"\n * ```\n *\n * You can use `'last'` to access the last element of the array in MySQL:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('nicknames', '->$').at('last').as('last_nickname')\n * )\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * select `nicknames`->'$[last]' as `last_nickname` from `person`\n * ```\n *\n * Or `'#-1'` in SQLite:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('nicknames', '->>$').at('#-1').as('last_nickname')\n * )\n * ```\n *\n * The generated SQL (SQLite):\n *\n * ```sql\n * select \"nicknames\"->>'$[#-1]' as `last_nickname` from `person`\n * ```\n */\n at(index) {\n return this.#createBuilderWithPathLeg('ArrayLocation', index);\n }\n /**\n * Access a property of a JSON object.\n *\n * If a field is optional, the resulting type will be nullable.\n *\n * See also {@link at} to access elements of JSON arrays.\n *\n * ### Examples\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('address', '->').key('city').as('city')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"address\"->'city' as \"city\" from \"person\"\n * ```\n *\n * Going deeper:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('profile', '->$').key('website').key('url').as('website_url')\n * )\n * ```\n *\n * The generated SQL (MySQL):\n *\n * ```sql\n * select `profile`->'$.website.url' as `website_url` from `person`\n * ```\n *\n * Combined with {@link at}:\n *\n * ```ts\n * db.selectFrom('person').select(eb =>\n * eb.ref('profile', '->').key('addresses').at(0).key('city').as('city')\n * )\n * ```\n *\n * The generated SQL (PostgreSQL):\n *\n * ```sql\n * select \"profile\"->'addresses'->0->'city' as \"city\" from \"person\"\n * ```\n */\n key(key) {\n return this.#createBuilderWithPathLeg('Member', key);\n }\n #createBuilderWithPathLeg(legType, value) {\n if (JSONReferenceNode.is(this.#node)) {\n return new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(this.#node, JSONPathNode.is(this.#node.traversal)\n ? JSONPathNode.cloneWithLeg(this.#node.traversal, JSONPathLegNode.create(legType, value))\n : JSONOperatorChainNode.cloneWithValue(this.#node.traversal, ValueNode.createImmediate(value))));\n }\n return new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(this.#node, JSONPathLegNode.create(legType, value)));\n }\n}\nexport class TraversedJSONPathBuilder extends JSONPathBuilder {\n #node;\n constructor(node) {\n super(node);\n this.#node = node;\n }\n /** @private */\n get expressionType() {\n return undefined;\n }\n as(alias) {\n return new AliasedJSONPathBuilder(this, alias);\n }\n /**\n * Change the output type of the json path.\n *\n * This method call doesn't change the SQL in any way. This methods simply\n * returns a copy of this `JSONPathBuilder` with a new output type.\n */\n $castTo() {\n return new TraversedJSONPathBuilder(this.#node);\n }\n $notNull() {\n return new TraversedJSONPathBuilder(this.#node);\n }\n toOperationNode() {\n return this.#node;\n }\n}\nexport class AliasedJSONPathBuilder {\n #jsonPath;\n #alias;\n constructor(jsonPath, alias) {\n this.#jsonPath = jsonPath;\n this.#alias = alias;\n }\n /** @private */\n get expression() {\n return this.#jsonPath;\n }\n /** @private */\n get alias() {\n return this.#alias;\n }\n toOperationNode() {\n return AliasNode.create(this.#jsonPath.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./tuple-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const TupleNode = freeze({\n is(node) {\n return node.kind === 'TupleNode';\n },\n create(values) {\n return freeze({\n kind: 'TupleNode',\n values: freeze(values),\n });\n },\n});\n","/// <reference types=\"./data-type-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\nconst SIMPLE_COLUMN_DATA_TYPES = [\n 'varchar',\n 'char',\n 'text',\n 'integer',\n 'int2',\n 'int4',\n 'int8',\n 'smallint',\n 'bigint',\n 'boolean',\n 'real',\n 'double precision',\n 'float4',\n 'float8',\n 'decimal',\n 'numeric',\n 'binary',\n 'bytea',\n 'date',\n 'datetime',\n 'time',\n 'timetz',\n 'timestamp',\n 'timestamptz',\n 'serial',\n 'bigserial',\n 'uuid',\n 'json',\n 'jsonb',\n 'blob',\n 'varbinary',\n 'int4range',\n 'int4multirange',\n 'int8range',\n 'int8multirange',\n 'numrange',\n 'nummultirange',\n 'tsrange',\n 'tsmultirange',\n 'tstzrange',\n 'tstzmultirange',\n 'daterange',\n 'datemultirange',\n];\nconst COLUMN_DATA_TYPE_REGEX = [\n /^varchar\\(\\d+\\)$/,\n /^char\\(\\d+\\)$/,\n /^decimal\\(\\d+, \\d+\\)$/,\n /^numeric\\(\\d+, \\d+\\)$/,\n /^binary\\(\\d+\\)$/,\n /^datetime\\(\\d+\\)$/,\n /^time\\(\\d+\\)$/,\n /^timetz\\(\\d+\\)$/,\n /^timestamp\\(\\d+\\)$/,\n /^timestamptz\\(\\d+\\)$/,\n /^varbinary\\(\\d+\\)$/,\n];\n/**\n * @internal\n */\nexport const DataTypeNode = freeze({\n is(node) {\n return node.kind === 'DataTypeNode';\n },\n create(dataType) {\n return freeze({\n kind: 'DataTypeNode',\n dataType,\n });\n },\n});\nexport function isColumnDataType(dataType) {\n if (SIMPLE_COLUMN_DATA_TYPES.includes(dataType)) {\n return true;\n }\n if (COLUMN_DATA_TYPE_REGEX.some((r) => r.test(dataType))) {\n return true;\n }\n return false;\n}\n","/// <reference types=\"./data-type-parser.d.ts\" />\nimport { DataTypeNode, isColumnDataType, } from '../operation-node/data-type-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nexport function parseDataTypeExpression(dataType) {\n if (isOperationNodeSource(dataType)) {\n return dataType.toOperationNode();\n }\n if (isColumnDataType(dataType)) {\n return DataTypeNode.create(dataType);\n }\n throw new Error(`invalid column data type ${JSON.stringify(dataType)}`);\n}\n","/// <reference types=\"./cast-node.d.ts\" />\nimport { freeze } from '../util/object-utils.js';\n/**\n * @internal\n */\nexport const CastNode = freeze({\n is(node) {\n return node.kind === 'CastNode';\n },\n create(expression, dataType) {\n return freeze({\n kind: 'CastNode',\n expression,\n dataType,\n });\n },\n});\n","/// <reference types=\"./expression-builder.d.ts\" />\nimport { createSelectQueryBuilder, } from '../query-builder/select-query-builder.js';\nimport { SelectQueryNode } from '../operation-node/select-query-node.js';\nimport { parseTableExpressionOrList, parseTable, } from '../parser/table-parser.js';\nimport { WithSchemaPlugin } from '../plugin/with-schema/with-schema-plugin.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { createFunctionModule, } from '../query-builder/function-module.js';\nimport { parseJSONReference, parseReferenceExpression, parseStringReference, } from '../parser/reference-parser.js';\nimport { parseFilterList, parseFilterObject, parseValueBinaryOperation, parseValueBinaryOperationOrExpression, } from '../parser/binary-operation-parser.js';\nimport { ParensNode } from '../operation-node/parens-node.js';\nimport { ExpressionWrapper } from './expression-wrapper.js';\nimport { OperatorNode, } from '../operation-node/operator-node.js';\nimport { parseUnaryOperation } from '../parser/unary-operation-parser.js';\nimport { parseSafeImmediateValue, parseValueExpression, } from '../parser/value-parser.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { CaseBuilder } from '../query-builder/case-builder.js';\nimport { CaseNode } from '../operation-node/case-node.js';\nimport { isReadonlyArray, isUndefined } from '../util/object-utils.js';\nimport { JSONPathBuilder } from '../query-builder/json-path-builder.js';\nimport { BinaryOperationNode } from '../operation-node/binary-operation-node.js';\nimport { AndNode } from '../operation-node/and-node.js';\nimport { TupleNode } from '../operation-node/tuple-node.js';\nimport { JSONPathNode } from '../operation-node/json-path-node.js';\nimport { parseDataTypeExpression, } from '../parser/data-type-parser.js';\nimport { CastNode } from '../operation-node/cast-node.js';\nexport function createExpressionBuilder(executor = NOOP_QUERY_EXECUTOR) {\n function binary(lhs, op, rhs) {\n return new ExpressionWrapper(parseValueBinaryOperation(lhs, op, rhs));\n }\n function unary(op, expr) {\n return new ExpressionWrapper(parseUnaryOperation(op, expr));\n }\n const eb = Object.assign(binary, {\n fn: undefined,\n eb: undefined,\n selectFrom(table) {\n return createSelectQueryBuilder({\n queryId: createQueryId(),\n executor,\n queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(table)),\n });\n },\n case(reference) {\n return new CaseBuilder({\n node: CaseNode.create(isUndefined(reference)\n ? undefined\n : parseReferenceExpression(reference)),\n });\n },\n ref(reference, op) {\n if (isUndefined(op)) {\n return new ExpressionWrapper(parseStringReference(reference));\n }\n return new JSONPathBuilder(parseJSONReference(reference, op));\n },\n jsonPath() {\n return new JSONPathBuilder(JSONPathNode.create());\n },\n table(table) {\n return new ExpressionWrapper(parseTable(table));\n },\n val(value) {\n return new ExpressionWrapper(parseValueExpression(value));\n },\n refTuple(...values) {\n return new ExpressionWrapper(TupleNode.create(values.map(parseReferenceExpression)));\n },\n tuple(...values) {\n return new ExpressionWrapper(TupleNode.create(values.map(parseValueExpression)));\n },\n lit(value) {\n return new ExpressionWrapper(parseSafeImmediateValue(value));\n },\n unary,\n not(expr) {\n return unary('not', expr);\n },\n exists(expr) {\n return unary('exists', expr);\n },\n neg(expr) {\n return unary('-', expr);\n },\n between(expr, start, end) {\n return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create('between'), AndNode.create(parseValueExpression(start), parseValueExpression(end))));\n },\n betweenSymmetric(expr, start, end) {\n return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create('between symmetric'), AndNode.create(parseValueExpression(start), parseValueExpression(end))));\n },\n and(exprs) {\n if (isReadonlyArray(exprs)) {\n return new ExpressionWrapper(parseFilterList(exprs, 'and'));\n }\n return new ExpressionWrapper(parseFilterObject(exprs, 'and'));\n },\n or(exprs) {\n if (isReadonlyArray(exprs)) {\n return new ExpressionWrapper(parseFilterList(exprs, 'or'));\n }\n return new ExpressionWrapper(parseFilterObject(exprs, 'or'));\n },\n parens(...args) {\n const node = parseValueBinaryOperationOrExpression(args);\n if (ParensNode.is(node)) {\n // No double wrapping.\n return new ExpressionWrapper(node);\n }\n else {\n return new ExpressionWrapper(ParensNode.create(node));\n }\n },\n cast(expr, dataType) {\n return new ExpressionWrapper(CastNode.create(parseReferenceExpression(expr), parseDataTypeExpression(dataType)));\n },\n withSchema(schema) {\n return createExpressionBuilder(executor.withPluginAtFront(new WithSchemaPlugin(schema)));\n },\n });\n eb.fn = createFunctionModule();\n eb.eb = eb;\n return eb;\n}\nexport function expressionBuilder(_) {\n return createExpressionBuilder();\n}\n","/// <reference types=\"./expression-parser.d.ts\" />\nimport { isAliasedExpression, isExpression, } from '../expression/expression.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { expressionBuilder, } from '../expression/expression-builder.js';\nimport { isFunction } from '../util/object-utils.js';\nexport function parseExpression(exp) {\n if (isOperationNodeSource(exp)) {\n return exp.toOperationNode();\n }\n else if (isFunction(exp)) {\n return exp(expressionBuilder()).toOperationNode();\n }\n throw new Error(`invalid expression: ${JSON.stringify(exp)}`);\n}\nexport function parseAliasedExpression(exp) {\n if (isOperationNodeSource(exp)) {\n return exp.toOperationNode();\n }\n else if (isFunction(exp)) {\n return exp(expressionBuilder()).toOperationNode();\n }\n throw new Error(`invalid aliased expression: ${JSON.stringify(exp)}`);\n}\nexport function isExpressionOrFactory(obj) {\n return isExpression(obj) || isAliasedExpression(obj) || isFunction(obj);\n}\n","/// <reference types=\"./dynamic-table-builder.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource, } from '../operation-node/operation-node-source.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { isObject, isString } from '../util/object-utils.js';\nexport class DynamicTableBuilder {\n #table;\n get table() {\n return this.#table;\n }\n constructor(table) {\n this.#table = table;\n }\n as(alias) {\n return new AliasedDynamicTableBuilder(this.#table, alias);\n }\n}\nexport class AliasedDynamicTableBuilder {\n #table;\n #alias;\n get table() {\n return this.#table;\n }\n get alias() {\n return this.#alias;\n }\n constructor(table, alias) {\n this.#table = table;\n this.#alias = alias;\n }\n toOperationNode() {\n return AliasNode.create(parseTable(this.#table), IdentifierNode.create(this.#alias));\n }\n}\nexport function isAliasedDynamicTableBuilder(obj) {\n return (isObject(obj) &&\n isOperationNodeSource(obj) &&\n isString(obj.table) &&\n isString(obj.alias));\n}\n","/// <reference types=\"./table-parser.d.ts\" />\nimport { isReadonlyArray, isString } from '../util/object-utils.js';\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { TableNode } from '../operation-node/table-node.js';\nimport { parseAliasedExpression, } from './expression-parser.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isAliasedDynamicTableBuilder, } from '../dynamic/dynamic-table-builder.js';\nexport function parseTableExpressionOrList(table) {\n if (isReadonlyArray(table)) {\n return table.map((it) => parseTableExpression(it));\n }\n else {\n return [parseTableExpression(table)];\n }\n}\nexport function parseTableExpression(table) {\n if (isString(table)) {\n return parseAliasedTable(table);\n }\n else if (isAliasedDynamicTableBuilder(table)) {\n return table.toOperationNode();\n }\n else {\n return parseAliasedExpression(table);\n }\n}\nexport function parseAliasedTable(from) {\n const ALIAS_SEPARATOR = ' as ';\n if (from.includes(ALIAS_SEPARATOR)) {\n const [table, alias] = from.split(ALIAS_SEPARATOR).map(trim);\n return AliasNode.create(parseTable(table), IdentifierNode.create(alias));\n }\n else {\n return parseTable(from);\n }\n}\nexport function parseTable(from) {\n const SCHEMA_SEPARATOR = '.';\n if (from.includes(SCHEMA_SEPARATOR)) {\n const [schema, table] = from.split(SCHEMA_SEPARATOR).map(trim);\n return TableNode.createWithSchema(schema, table);\n }\n else {\n return TableNode.create(from);\n }\n}\nfunction trim(str) {\n return str.trim();\n}\n","/// <reference types=\"./raw-builder.d.ts\" />\nimport { AliasNode } from '../operation-node/alias-node.js';\nimport { freeze } from '../util/object-utils.js';\nimport { NOOP_QUERY_EXECUTOR } from '../query-executor/noop-query-executor.js';\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nclass RawBuilderImpl {\n #props;\n constructor(props) {\n this.#props = freeze(props);\n }\n get expressionType() {\n return undefined;\n }\n get isRawBuilder() {\n return true;\n }\n as(alias) {\n return new AliasedRawBuilderImpl(this, alias);\n }\n $castTo() {\n return new RawBuilderImpl({ ...this.#props });\n }\n $notNull() {\n return new RawBuilderImpl(this.#props);\n }\n withPlugin(plugin) {\n return new RawBuilderImpl({\n ...this.#props,\n plugins: this.#props.plugins !== undefined\n ? freeze([...this.#props.plugins, plugin])\n : freeze([plugin]),\n });\n }\n toOperationNode() {\n return this.#toOperationNode(this.#getExecutor());\n }\n compile(executorProvider) {\n return this.#compile(this.#getExecutor(executorProvider));\n }\n async execute(executorProvider) {\n const executor = this.#getExecutor(executorProvider);\n return executor.executeQuery(this.#compile(executor));\n }\n #getExecutor(executorProvider) {\n const executor = executorProvider !== undefined\n ? executorProvider.getExecutor()\n : NOOP_QUERY_EXECUTOR;\n return this.#props.plugins !== undefined\n ? executor.withPlugins(this.#props.plugins)\n : executor;\n }\n #toOperationNode(executor) {\n return executor.transformQuery(this.#props.rawNode, this.#props.queryId);\n }\n #compile(executor) {\n return executor.compileQuery(this.#toOperationNode(executor), this.#props.queryId);\n }\n}\nexport function createRawBuilder(props) {\n return new RawBuilderImpl(props);\n}\nclass AliasedRawBuilderImpl {\n #rawBuilder;\n #alias;\n constructor(rawBuilder, alias) {\n this.#rawBuilder = rawBuilder;\n this.#alias = alias;\n }\n get expression() {\n return this.#rawBuilder;\n }\n get alias() {\n return this.#alias;\n }\n get rawBuilder() {\n return this.#rawBuilder;\n }\n toOperationNode() {\n return AliasNode.create(this.#rawBuilder.toOperationNode(), isOperationNodeSource(this.#alias)\n ? this.#alias.toOperationNode()\n : IdentifierNode.create(this.#alias));\n }\n}\n","/// <reference types=\"./sql.d.ts\" />\nimport { IdentifierNode } from '../operation-node/identifier-node.js';\nimport { isOperationNodeSource } from '../operation-node/operation-node-source.js';\nimport { RawNode } from '../operation-node/raw-node.js';\nimport { ValueNode } from '../operation-node/value-node.js';\nimport { parseStringReference } from '../parser/reference-parser.js';\nimport { parseTable } from '../parser/table-parser.js';\nimport { parseValueExpression } from '../parser/value-parser.js';\nimport { createQueryId } from '../util/query-id.js';\nimport { createRawBuilder } from './raw-builder.js';\nexport const sql = Object.assign((sqlFragments, ...parameters) => {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.create(sqlFragments, parameters?.map(parseParameter) ?? []),\n });\n}, {\n ref(columnReference) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseStringReference(columnReference)),\n });\n },\n val(value) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseValueExpression(value)),\n });\n },\n value(value) {\n return this.val(value);\n },\n table(tableReference) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(parseTable(tableReference)),\n });\n },\n id(...ids) {\n const fragments = new Array(ids.length + 1).fill('.');\n fragments[0] = '';\n fragments[fragments.length - 1] = '';\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create)),\n });\n },\n lit(value) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChild(ValueNode.createImmediate(value)),\n });\n },\n literal(value) {\n return this.lit(value);\n },\n raw(sql) {\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithSql(sql),\n });\n },\n join(array, separator = sql `, `) {\n const nodes = new Array(Math.max(2 * array.length - 1, 0));\n const sep = separator.toOperationNode();\n for (let i = 0; i < array.length; ++i) {\n nodes[2 * i] = parseParameter(array[i]);\n if (i !== array.length - 1) {\n nodes[2 * i + 1] = sep;\n }\n }\n return createRawBuilder({\n queryId: createQueryId(),\n rawNode: RawNode.createWithChildren(nodes),\n });\n },\n});\nfunction parseParameter(param) {\n if (isOperationNodeSource(param)) {\n return param.toOperationNode();\n }\n return parseValueExpression(param);\n}\n","import { AUTH_ACTION_TYPES, AUTH_DENIED_BY_GRANT_REASON, AUTH_NO_GRANT_REASON, AUTH_VERSION_UNSUPPORTED_REASON, DOCUMENT_DELETED_REASON, DOCUMENT_SCOPE_ACTION_TYPES, DowngradeNotSupportedError as DowngradeNotSupportedError$1, PEER_CAPABILITIES, PURGE_DOCUMENT, actionSignerIdentity, actionSigningTarget, appendWithoutApplying, applyAuthAction, applyDeleteDocumentAction, applyDeleteDocumentAction as applyDeleteDocumentAction$1, applyUpgradeDocumentAction, applyUpgradeDocumentAction as applyUpgradeDocumentAction$1, base58Decode, baseReducerVersion, buildOperationSignatureMessage, buildOperationSignatureParams, canonicalJson, createDocumentState, createPresignedHeader, decide, defaultBaseState, deriveDocumentId, deriveOperationId, evaluate, garbageCollect, groupDocumentType, groupMembershipActionTypes, hashActionV2, hashBrowser, hashDocumentStateForScope, isDenied, isDerivedDocumentId, isPurgeMarker, isUndoRedo, isV2ActionHash, localSupports, mentionedGroupIds, normalizeDocumentModelVersion, operationOutcome, purgeDocumentAction, purgeMarkerOperation, purgedProtocolVersions, referencedGroupIds, signaturePolicyOf, sortOperations, targetDocumentId, v2TupleProblem, withProtocolVersions } from \"@powerhousedao/shared/document-model\";\nimport { v4 } from \"uuid\";\nimport { Migrator, TableNode, sql } from \"kysely\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region src/shared/utils.ts\nfunction matchesScope(view = {}, scope) {\n\tif (view.scopes) return view.scopes.includes(scope);\n\treturn true;\n}\nfunction yieldToMain() {\n\tconst s = globalThis.scheduler;\n\tif (s?.yield) return s.yield();\n\treturn new Promise((resolve) => setTimeout(resolve, 0));\n}\nconst defaultAbortError = () => /* @__PURE__ */ new Error(\"Operation aborted\");\nfunction throwIfAborted(signal, makeError = defaultAbortError) {\n\tif (signal?.aborted) throw makeError();\n}\n/**\n* Validates PagingOptions and returns a normalized offset and limit.\n* Throws if the cursor is not empty and not a non-negative integer, or if\n* limit is less than 1. When `paging` is undefined, returns offset 0 and\n* the caller-supplied `defaultLimit`.\n*/\nfunction parsePagingOptions(paging, defaultLimit) {\n\tif (paging === void 0) return {\n\t\toffset: 0,\n\t\tlimit: defaultLimit\n\t};\n\tif (!Number.isInteger(paging.limit) || paging.limit < 1) throw new Error(`Invalid paging limit: ${String(paging.limit)} (must be an integer >= 1)`);\n\tif (paging.cursor === \"\") return {\n\t\toffset: 0,\n\t\tlimit: paging.limit\n\t};\n\tconst parsed = Number(paging.cursor);\n\tif (!Number.isInteger(parsed) || parsed < 0) throw new Error(`Invalid paging cursor: ${JSON.stringify(paging.cursor)} (must be empty or a non-negative integer)`);\n\treturn {\n\t\toffset: parsed,\n\t\tlimit: paging.limit\n\t};\n}\n//#endregion\n//#region src/events/types.ts\n/**\n* Custom error class that aggregates multiple errors from event subscribers.\n*/\nvar EventBusAggregateError = class extends Error {\n\terrors;\n\tconstructor(errors) {\n\t\tconst message = `EventBus emit failed with ${errors.length} error(s): ${errors.map((e) => {\n\t\t\tif (e && typeof e === \"object\" && \"message\" in e) return e.message;\n\t\t\treturn String(e);\n\t\t}).join(\"; \")}`;\n\t\tsuper(message);\n\t\tthis.name = \"EventBusAggregateError\";\n\t\tthis.errors = errors;\n\t}\n};\n/**\n* Event types for reactor lifecycle events.\n*/\nconst ReactorEventTypes = {\n\tJOB_PENDING: 10001,\n\tJOB_RUNNING: 10002,\n\tJOB_WRITE_READY: 10003,\n\tJOB_READ_READY: 10004,\n\tJOB_FAILED: 10005,\n\tREADMODEL_BATCH_COMPLETED: 10006,\n\tREADMODEL_INDEXED: 10007,\n\tMODEL_LOADED: 10008,\n\tSIGNATURE_REFUSED: 10009,\n\tCATCHUP_SWEPT: 10010\n};\n//#endregion\n//#region src/shared/errors.ts\n/**\n* Error thrown when attempting to access a deleted document.\n*/\nvar DocumentDeletedError = class DocumentDeletedError extends Error {\n\tdocumentId;\n\tdeletedAtUtcIso;\n\tconstructor(documentId, deletedAtUtcIso = null) {\n\t\tconst message = deletedAtUtcIso ? `Document ${documentId} was deleted at ${deletedAtUtcIso}` : `Document ${documentId} has been deleted`;\n\t\tsuper(message);\n\t\tthis.name = \"DocumentDeletedError\";\n\t\tthis.documentId = documentId;\n\t\tthis.deletedAtUtcIso = deletedAtUtcIso;\n\t\tError.captureStackTrace(this, DocumentDeletedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentDeletedError\";\n\t}\n};\n/**\n* Error thrown when the auth policy denies an action at the executor gate.\n*/\nvar AuthorizationDeniedError = class AuthorizationDeniedError extends Error {\n\tdocumentId;\n\tscope;\n\toperation;\n\tsubject;\n\tconstructor(documentId, scope, operation, subject) {\n\t\tsuper(`Authorization denied: ${subject ?? \"anonymous\"} may not execute ${operation} in scope \"${scope}\" of document ${documentId}`);\n\t\tthis.name = \"AuthorizationDeniedError\";\n\t\tthis.documentId = documentId;\n\t\tthis.scope = scope;\n\t\tthis.operation = operation;\n\t\tthis.subject = subject;\n\t\tError.captureStackTrace(this, AuthorizationDeniedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"AuthorizationDeniedError\";\n\t}\n};\n/**\n* An auth operation did not strictly exceed the newest timestamp in its stream.\n*\n* Terminal and asymmetric by design: no ordering rule can reconcile two replicas\n* that each accepted an auth operation offline, because either order hands one\n* authority the other never granted, so the replica ahead holds the arrival.\n*/\nvar AuthTimestampNotMonotonicError = class AuthTimestampNotMonotonicError extends Error {\n\tdocumentId;\n\tbranch;\n\ttimestampUtcMs;\n\tnewestTimestampUtcMs;\n\tconstructor(documentId, branch, timestampUtcMs, newestTimestampUtcMs) {\n\t\tsuper(`Auth timestamp not monotonic: ${timestampUtcMs} does not exceed ${newestTimestampUtcMs} in the auth stream of document ${documentId} on branch ${branch}`);\n\t\tthis.name = \"AuthTimestampNotMonotonicError\";\n\t\tthis.documentId = documentId;\n\t\tthis.branch = branch;\n\t\tthis.timestampUtcMs = timestampUtcMs;\n\t\tthis.newestTimestampUtcMs = newestTimestampUtcMs;\n\t\tError.captureStackTrace(this, AuthTimestampNotMonotonicError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"AuthTimestampNotMonotonicError\";\n\t}\n};\n/**\n* An operation or action carried a timestamp that is not an ISO-8601 UTC\n* instant.\n*\n* Terminal rather than retryable: the value does not change between attempts,\n* so a retry re-runs the whole job to fail identically. Quarantining, unlike a\n* held auth operation — this is malformed data rather than two replicas\n* disagreeing, and nothing further from that source should be trusted until it\n* is looked at.\n*/\nvar InvalidOperationTimestampError = class InvalidOperationTimestampError extends Error {\n\tdocumentId;\n\tscope;\n\ttimestampUtcMs;\n\tconstructor(documentId, scope, timestampUtcMs, context) {\n\t\tsuper(`Invalid timestamp \"${timestampUtcMs}\" on ${context} in scope \"${scope}\" of document ${documentId}`);\n\t\tthis.name = \"InvalidOperationTimestampError\";\n\t\tthis.documentId = documentId;\n\t\tthis.scope = scope;\n\t\tthis.timestampUtcMs = timestampUtcMs;\n\t\tError.captureStackTrace(this, InvalidOperationTimestampError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"InvalidOperationTimestampError\";\n\t}\n};\n/** A document requires a protocol version this reactor does not run. Terminal. */\nvar UnsupportedProtocolVersionError = class UnsupportedProtocolVersionError extends Error {\n\tdocumentId;\n\tprotocol;\n\tversion;\n\tconstructor(documentId, protocol, version) {\n\t\tsuper(`Document ${documentId} requires ${protocol} ${version}, which this reactor does not support`);\n\t\tthis.name = \"UnsupportedProtocolVersionError\";\n\t\tthis.documentId = documentId;\n\t\tthis.protocol = protocol;\n\t\tthis.version = version;\n\t\tError.captureStackTrace(this, UnsupportedProtocolVersionError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"UnsupportedProtocolVersionError\";\n\t}\n};\n/**\n* A load would move more operations than the bound allows, indicating a real\n* divergence between local and incoming history. Counts only first-time moves,\n* so a re-evaluation pass's re-appends do not make busy documents\n* revocation-proof. Terminal: the condition is deterministic.\n*/\nvar ExcessiveReshuffleError = class ExcessiveReshuffleError extends Error {\n\tdocumentId;\n\tscope;\n\tcount;\n\tthreshold;\n\tconstructor(documentId, scope, count, threshold) {\n\t\tsuper(`Excessive reshuffle detected: ${count} operations in scope \"${scope}\" of document ${documentId} exceeds the threshold of ${threshold}. This indicates a significant divergence between local and incoming operations.`);\n\t\tthis.name = \"ExcessiveReshuffleError\";\n\t\tthis.documentId = documentId;\n\t\tthis.scope = scope;\n\t\tthis.count = count;\n\t\tthis.threshold = threshold;\n\t\tError.captureStackTrace(this, ExcessiveReshuffleError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"ExcessiveReshuffleError\";\n\t}\n};\n/** The message carries the code: only name and message cross the queue. */\nvar InvalidSignatureError = class InvalidSignatureError extends Error {\n\tdocumentId;\n\tcode;\n\treason;\n\tconstructor(documentId, code, reason) {\n\t\tsuper(`Invalid signature in document ${documentId} [${code}]: ${reason}`);\n\t\tthis.name = \"InvalidSignatureError\";\n\t\tthis.documentId = documentId;\n\t\tthis.code = code;\n\t\tthis.reason = reason;\n\t\tError.captureStackTrace(this, InvalidSignatureError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"InvalidSignatureError\";\n\t}\n};\n/**\n* An UPGRADE_DOCUMENT action's preconditions (fromVersion and the per-scope\n* revision snapshot) did not match the document state the executor loaded.\n*\n* Terminal rather than retryable: the action carries the client's snapshot,\n* which stays stale no matter how often the job re-runs. The client is\n* expected to re-read the document and submit a fresh action instead.\n*/\nvar UpgradePreconditionFailedError = class UpgradePreconditionFailedError extends Error {\n\tdocumentId;\n\tdetail;\n\tconstructor(documentId, detail) {\n\t\tsuper(`Upgrade precondition failed for document ${documentId}: ${detail}`);\n\t\tthis.name = \"UpgradePreconditionFailedError\";\n\t\tthis.documentId = documentId;\n\t\tthis.detail = detail;\n\t\tError.captureStackTrace(this, UpgradePreconditionFailedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"UpgradePreconditionFailedError\";\n\t}\n};\n/**\n* Error thrown when a document is not found (no operations exist for the document ID).\n*/\nvar DocumentNotFoundError = class DocumentNotFoundError extends Error {\n\tdocumentId;\n\t/**\n\t* @param message Overrides the default text. A handler that knows which of\n\t* several documents an action reads - a relationship's source, say - says so\n\t* here rather than rewrapping in a bare Error, which would strip the name the\n\t* executor classifies by.\n\t*/\n\tconstructor(documentId, message) {\n\t\tsuper(message ?? `Document ${documentId} not found`);\n\t\tthis.name = \"DocumentNotFoundError\";\n\t\tthis.documentId = documentId;\n\t\tError.captureStackTrace(this, DocumentNotFoundError);\n\t}\n\t/** Also true for DocumentPurgedError: only the name crosses the queue. */\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && (error.name === \"DocumentNotFoundError\" || error.name === \"DocumentPurgedError\");\n\t}\n};\n/** The document was purged; readers treat it as absent. Terminal. */\nvar DocumentPurgedError = class DocumentPurgedError extends DocumentNotFoundError {\n\tpurged = true;\n\tconstructor(documentId, message) {\n\t\tsuper(documentId, message ?? `Document ${documentId} was purged`);\n\t\tthis.name = \"DocumentPurgedError\";\n\t\tError.captureStackTrace(this, DocumentPurgedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentPurgedError\";\n\t}\n};\n/** A purge was asked for a document that is not deleted. Terminal. */\nvar DocumentNotDeletedError = class DocumentNotDeletedError extends Error {\n\tdocumentId;\n\tconstructor(documentId, message) {\n\t\tsuper(message ?? `Document ${documentId} is not deleted`);\n\t\tthis.name = \"DocumentNotDeletedError\";\n\t\tthis.documentId = documentId;\n\t\tError.captureStackTrace(this, DocumentNotDeletedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentNotDeletedError\";\n\t}\n};\n/** A surviving document's accepted auth history names the group. Terminal. */\nvar GroupInUseError = class GroupInUseError extends Error {\n\tgroupId;\n\treferencingDocumentIds;\n\tconstructor(groupId, referencingDocumentIds) {\n\t\tsuper(`Group ${groupId} cannot be purged: the auth history of ${referencingDocumentIds.join(\", \")} names it`);\n\t\tthis.name = \"GroupInUseError\";\n\t\tthis.groupId = groupId;\n\t\tthis.referencingDocumentIds = referencingDocumentIds;\n\t\tError.captureStackTrace(this, GroupInUseError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"GroupInUseError\";\n\t}\n};\n/** A purge above maxPurgeOperations without allowLarge. Terminal. */\nvar PurgeTooLargeError = class PurgeTooLargeError extends Error {\n\tdocumentId;\n\toperationCount;\n\tmaxPurgeOperations;\n\tconstructor(documentId, operationCount, maxPurgeOperations) {\n\t\tsuper(`Document ${documentId} has ${operationCount} operations, above the purge limit of ${maxPurgeOperations}; request it with allowLarge`);\n\t\tthis.name = \"PurgeTooLargeError\";\n\t\tthis.documentId = documentId;\n\t\tthis.operationCount = operationCount;\n\t\tthis.maxPurgeOperations = maxPurgeOperations;\n\t\tError.captureStackTrace(this, PurgeTooLargeError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"PurgeTooLargeError\";\n\t}\n};\n/** A regular write carried an action type only the reactor issues. Terminal. */\nvar ReservedActionError = class ReservedActionError extends Error {\n\tdocumentId;\n\tactionType;\n\tconstructor(documentId, actionType) {\n\t\tsuper(`Action ${actionType} is reserved and cannot be submitted to document ${documentId}`);\n\t\tthis.name = \"ReservedActionError\";\n\t\tthis.documentId = documentId;\n\t\tthis.actionType = actionType;\n\t\tError.captureStackTrace(this, ReservedActionError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"ReservedActionError\";\n\t}\n};\n/**\n* An authorization preflight was asked for while the reactor's decision model\n* is off, so there is no model to answer from.\n*\n* Thrown rather than answered from the legacy host-side permission tables. The\n* two systems do not compose: the tables record which addresses a host lets\n* near a drive, the policy records what a document's own grants permit, and an\n* answer stitched from both would report an admission verdict neither system\n* would reach. A caller that cannot get a prediction disables nothing, which\n* leaves the submit path -- and its real gate -- as the only authority.\n*\n* Detection is by `name`, not `instanceof`: the SharedWorker RPC boundary\n* rebuilds a thrown error from `{ name, message, stack, cause }` alone\n* (`reactor-browser/src/rpc/error-info.ts`), so the class identity and any\n* custom field are lost in transit. This error therefore carries no fields.\n*/\nvar AuthEnforcementDisabledError = class AuthEnforcementDisabledError extends Error {\n\tconstructor() {\n\t\tsuper(\"Authorization evaluation requires the authEnforcement feature flag; this reactor holds no decision model, and the legacy host-table permission system cannot answer for one\");\n\t\tthis.name = \"AuthEnforcementDisabledError\";\n\t\tError.captureStackTrace(this, AuthEnforcementDisabledError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"AuthEnforcementDisabledError\";\n\t}\n};\n/**\n* Error thrown when a relationship edge an operation names does not exist.\n*\n* Detection is by `name`, not `instanceof`: the SharedWorker RPC boundary\n* rebuilds a thrown error from `{ name, message, stack, cause }` alone\n* (`reactor-browser/src/rpc/error-info.ts`), so the class identity is lost in\n* transit.\n*/\nvar RelationshipNotFoundError = class RelationshipNotFoundError extends Error {\n\tsourceId;\n\ttargetId;\n\trelationshipType;\n\tconstructor(sourceId, targetId, relationshipType) {\n\t\tsuper(`No ${relationshipType} relationship from ${sourceId} to ${targetId}`);\n\t\tthis.name = \"RelationshipNotFoundError\";\n\t\tthis.sourceId = sourceId;\n\t\tthis.targetId = targetId;\n\t\tthis.relationshipType = relationshipType;\n\t\tError.captureStackTrace(this, RelationshipNotFoundError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"RelationshipNotFoundError\";\n\t}\n};\n/** The store holds documents at protocol versions this reactor does not run. */\nvar UnsupportedStoredProtocolError = class UnsupportedStoredProtocolError extends Error {\n\tversions;\n\tdocuments;\n\tconstructor(versions, documents) {\n\t\tconst named = versions.map(({ protocol, version }) => `${protocol} ${version}`).join(\", \");\n\t\tsuper(`${documents} stored document(s) require ${named}, which this reactor does not run. Start a build that runs them, or accept them read-only with withUnsupportedStoredDocuments(\"read-only\")`);\n\t\tthis.name = \"UnsupportedStoredProtocolError\";\n\t\tthis.versions = versions;\n\t\tthis.documents = documents;\n\t\tError.captureStackTrace(this, UnsupportedStoredProtocolError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"UnsupportedStoredProtocolError\";\n\t}\n};\n//#endregion\n//#region src/storage/interfaces.ts\n/**\n* Thrown when an operation with the same identity already exists in the store.\n*/\nvar DuplicateOperationError = class extends Error {\n\tconstructor(description) {\n\t\tsuper(`Duplicate operation: ${description}`);\n\t\tthis.name = \"DuplicateOperationError\";\n\t}\n};\n/**\n* Thrown when a concurrent write conflict is detected during an atomic apply.\n*/\nvar OptimisticLockError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"OptimisticLockError\";\n\t}\n};\n/**\n* Thrown when the caller-provided revision does not match the current\n* stored revision, indicating a stale read.\n*/\nvar RevisionMismatchError = class extends Error {\n\tconstructor(expected, actual) {\n\t\tsuper(`Revision mismatch: expected ${expected}, got ${actual}`);\n\t\tthis.name = \"RevisionMismatchError\";\n\t}\n};\n/**\n* A create based on an empty stream that already has operations: the id is\n* taken, and no retry can resolve it. Matched by `name`, all the RPC boundary keeps.\n*/\nvar DocumentAlreadyExistsError = class extends Error {\n\tdocumentId;\n\tconstructor(documentId, scope, headRevision) {\n\t\tsuper(`Document ${documentId} already exists: create requested revision 0 but the \"${scope}\" stream is at revision ${headRevision}`);\n\t\tthis.name = \"DocumentAlreadyExistsError\";\n\t\tthis.documentId = documentId;\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentAlreadyExistsError\";\n\t}\n};\n/** Error history keeps messages, not classes, so failures match by prefix. */\nconst APPEND_CONDITION_FAILED_PREFIX = \"Append condition failed: \";\n/**\n* A read-set stream grew before the append committed. A concurrency\n* conflict, not a fault: the caller retries against the new stream heads.\n*/\nvar AppendConditionFailedError = class extends Error {\n\tcondition;\n\tconstructor(condition) {\n\t\tconst streams = condition.streams.map((s) => `${s.documentId}:${s.scope}:${s.branch}@${s.revision}`).join(\", \");\n\t\tsuper(`${APPEND_CONDITION_FAILED_PREFIX}a read-set stream advanced [${streams}]`);\n\t\tthis.condition = condition;\n\t\tthis.name = \"AppendConditionFailedError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"AppendConditionFailedError\";\n\t}\n\t/** True when a recorded error message is an append-condition failure. */\n\tstatic isFailureMessage(message) {\n\t\treturn message.startsWith(APPEND_CONDITION_FAILED_PREFIX);\n\t}\n};\n/**\n* Which sense of \"exists\" a caller of {@link IDocumentView.exists} means.\n*/\nlet DocumentExistence = /* @__PURE__ */ function(DocumentExistence) {\n\t/**\n\t* A document that is present and not deleted. This is the question a read\n\t* asks: a deleted document is not readable, so it does not exist.\n\t*/\n\tDocumentExistence[\"LiveOnly\"] = \"LiveOnly\";\n\t/**\n\t* Whether the id is taken, deleted or not. This is the question a write\n\t* asks: a deleted document keeps its operation stream, so its id can never\n\t* be reused, and answering from snapshots alone would say otherwise whenever\n\t* a snapshot row is missing while the stream is intact.\n\t*/\n\tDocumentExistence[\"IncludingDeleted\"] = \"IncludingDeleted\";\n\treturn DocumentExistence;\n}({});\n//#endregion\n//#region src/cache/operation-index-types.ts\nconst DRIVE_COLLECTION_PREFIX = \"drive.\";\n/**\n* Identifies the collection a remote synchronizes. Collections are drive-level\n* abstractions (document-drive and reactor-drive), so a collection id is the\n* drive document id plus the branch it scopes to rather than an opaque string.\n*\n* The canonical string form (`drive.${branch}.${driveId}`) is produced only by\n* `key` and parsed only by `fromKey`; that string is the wire and storage\n* representation and is byte-for-byte identical to the legacy\n* `driveCollectionId(branch, driveId)` output, so existing `document_collections`\n* rows and persisted remotes remain valid without migration.\n*/\nvar DriveCollectionId = class DriveCollectionId {\n\tdriveId;\n\tbranch;\n\tconstructor(driveId, branch) {\n\t\tthis.driveId = driveId;\n\t\tthis.branch = branch;\n\t}\n\tstatic forDrive(driveId, branch = \"main\") {\n\t\treturn new DriveCollectionId(driveId, branch);\n\t}\n\t/**\n\t* The single deserializer for the wire/storage form. `branch` may contain\n\t* dots, while `driveId` is a dot-free document id, so the drive id is the\n\t* final dot-delimited segment.\n\t*/\n\tstatic fromKey(key) {\n\t\tif (!key.startsWith(DRIVE_COLLECTION_PREFIX)) throw new Error(`Unsupported collection id: ${key}`);\n\t\tconst rest = key.slice(6);\n\t\tconst lastDot = rest.lastIndexOf(\".\");\n\t\tif (lastDot === -1 || lastDot === rest.length - 1) throw new Error(`Malformed drive collection id: ${key}`);\n\t\treturn new DriveCollectionId(rest.slice(lastDot + 1), rest.slice(0, lastDot));\n\t}\n\tget key() {\n\t\treturn `${DRIVE_COLLECTION_PREFIX}${this.branch}.${this.driveId}`;\n\t}\n\ttoString() {\n\t\treturn this.key;\n\t}\n\tequals(other) {\n\t\treturn this.driveId === other.driveId && this.branch === other.branch;\n\t}\n};\n//#endregion\n//#region src/decision/build-decision-model.ts\n/**\n* Reads each projection's stream through the supplied reader, recording the\n* revision observed. Static projections resolve first; derived projections\n* see only those and contribute a map from document id to state. Each\n* distinct stream is read once and yields one append condition entry.\n*/\nasync function buildDecisionModel(reader, definition, target, signal) {\n\tconst decisionModel = definition(target);\n\tconst projections = Object.entries(decisionModel.projections);\n\tconst reads = /* @__PURE__ */ new Map();\n\tconst model = {};\n\tfor (const [key, projection] of projections) {\n\t\tif (typeof projection.query === \"function\") continue;\n\t\tmodel[key] = (await readStream(reader, projection.query, reads, signal)).state;\n\t}\n\tconst staticModel = { ...model };\n\tconst derived = [];\n\tfor (const [key, projection] of projections) {\n\t\tif (typeof projection.query !== \"function\") continue;\n\t\tderived.push([key, projection.query(staticModel)]);\n\t}\n\tif (derived.length > 0 && reader.fence) await reader.fence(derived.flatMap(([, queries]) => queries.map((q) => q.documentId)));\n\tfor (const [key, queries] of derived) {\n\t\tconst value = {};\n\t\tfor (const query of queries) {\n\t\t\tlet read;\n\t\t\ttry {\n\t\t\t\tread = await readStream(reader, query, reads, signal);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof DocumentNotFoundError) {\n\t\t\t\t\trecordEmptyStream(query, reads);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tvalue[query.documentId] = read.state;\n\t\t}\n\t\tmodel[key] = value;\n\t}\n\treturn {\n\t\tmodel,\n\t\tappendCondition: { streams: [...reads.values()].map((read) => read.stream) }\n\t};\n}\n/** Guards a stream that holds nothing yet: any operation appearing is growth. */\nfunction recordEmptyStream(query, reads) {\n\tconst key = `${query.documentId}:${query.scope}:${query.branch}`;\n\tif (reads.has(key)) return;\n\treads.set(key, {\n\t\tstate: void 0,\n\t\tstream: {\n\t\t\tdocumentId: query.documentId,\n\t\t\tscope: query.scope,\n\t\t\tbranch: query.branch,\n\t\t\trevision: -1\n\t\t}\n\t});\n}\nasync function readStream(reader, query, reads, signal) {\n\tconst key = `${query.documentId}:${query.scope}:${query.branch}`;\n\tconst existing = reads.get(key);\n\tif (existing) return existing;\n\tconst document = await reader.getState(query.documentId, query.scope, query.branch, void 0, signal);\n\tconst read = {\n\t\tstate: document.state[query.scope],\n\t\tstream: {\n\t\t\tdocumentId: query.documentId,\n\t\t\tscope: query.scope,\n\t\t\tbranch: query.branch,\n\t\t\trevision: observedRevision(document, query.scope)\n\t\t}\n\t};\n\treads.set(key, read);\n\treturn read;\n}\n/**\n* The highest operation index the document reflects for the scope, or -1 if\n* empty. `header.revision` is authoritative, not the rebuilt operation list.\n*/\nfunction observedRevision(document, scope) {\n\tif (scope in document.header.revision) return document.header.revision[scope] - 1;\n\tif (scope in document.operations) {\n\t\tconst operations = document.operations[scope];\n\t\tif (operations.length > 0) return operations[operations.length - 1].index;\n\t}\n\tif (!(scope in document.header.revision)) return -1;\n\treturn document.header.revision[scope] - 1;\n}\n/**\n* The projections whose queries depend on folded state. A positional walk\n* resolves their streams through `queryOverHistory`; a projection without one\n* contributes no streams to a walk.\n*/\nfunction derivedReadSet(definition) {\n\tconst projections = [];\n\tfor (const [name, projection] of Object.entries(definition.projections)) {\n\t\tif (typeof projection.query !== \"function\") continue;\n\t\tprojections.push({\n\t\t\tname,\n\t\t\tdecidingActions: projection.decidingActions,\n\t\t\tapply: projection.apply,\n\t\t\tqueryOverHistory: projection.queryOverHistory\n\t\t});\n\t}\n\treturn projections;\n}\n/**\n* The streams a model reads whose queries are known before it is built. A\n* derived query needs the statically-queried projections first, so it is not\n* included here.\n*/\nfunction staticReadSet(definition) {\n\tconst streams = [];\n\tfor (const [name, projection] of Object.entries(definition.projections)) {\n\t\tif (typeof projection.query === \"function\") continue;\n\t\tstreams.push({\n\t\t\tname,\n\t\t\tquery: projection.query,\n\t\t\tdecidingActions: projection.decidingActions,\n\t\t\tapply: projection.apply\n\t\t});\n\t}\n\treturn streams;\n}\n//#endregion\n//#region src/decision/auth-decision-model.ts\nfunction refusalReason(refusal) {\n\tswitch (refusal) {\n\t\tcase \"version-unsupported\": return AUTH_VERSION_UNSUPPORTED_REASON;\n\t\tcase \"denied-by-grant\": return AUTH_DENIED_BY_GRANT_REASON;\n\t\tcase \"no-applicable-grant\": return AUTH_NO_GRANT_REASON;\n\t}\n}\nfunction decideAuthModel(model, subject, request, groups, conditions) {\n\tif (request.verb === \"execute\" && model.document.isDeleted) return {\n\t\tdecision: \"deny\",\n\t\treason: DOCUMENT_DELETED_REASON\n\t};\n\tconst evaluation = evaluate(model.auth, subject, request, groups, conditions);\n\tif (evaluation.decision === \"allow\") return { decision: \"allow\" };\n\treturn {\n\t\tdecision: \"deny\",\n\t\treason: refusalReason(evaluation.refusal)\n\t};\n}\nfunction documentProjection(target) {\n\treturn {\n\t\tdecidingActions: [\"DELETE_DOCUMENT\"],\n\t\tapply: (document, operation) => operation.action.type === \"DELETE_DOCUMENT\" ? applyDeleteDocumentAction({\n\t\t\t...document,\n\t\t\tstate: { ...document.state }\n\t\t}, operation.action) : document,\n\t\tquery: {\n\t\t\tdocumentId: target.documentId,\n\t\t\tbranch: target.branch,\n\t\t\tscope: \"document\"\n\t\t}\n\t};\n}\nfunction authProjection(target) {\n\treturn {\n\t\tdecidingActions: [...AUTH_ACTION_TYPES],\n\t\tapply: (document, operation) => applyAuthAction(document, operation.action),\n\t\tquery: {\n\t\t\tdocumentId: target.documentId,\n\t\t\tbranch: target.branch,\n\t\t\tscope: \"auth\"\n\t\t}\n\t};\n}\n/** This decision model uses both the document and the auth streams. */\nfunction authDecisionModel(target) {\n\treturn {\n\t\tprojections: {\n\t\t\tdocument: documentProjection(target),\n\t\t\tauth: authProjection(target)\n\t\t},\n\t\tevaluatesScope() {\n\t\t\treturn true;\n\t\t},\n\t\tdecide(model, subject, request) {\n\t\t\treturn decideAuthModel(model, subject, request);\n\t\t}\n\t};\n}\n/**\n* Folds one group-stream operation with the registered group model's reducer.\n* A reactor without the module registered folds nothing, so the member list\n* stays as read and a missing reducer never widens access.\n*/\nfunction applyGroupOperation(registry, document, operation) {\n\tlet reducer;\n\ttry {\n\t\treducer = registry.getModule(groupDocumentType).reducer;\n\t} catch {\n\t\treturn document;\n\t}\n\treturn reducer(document, operation.action);\n}\n/**\n* Folds one evaluated-scope operation with the reducer registered for the\n* document's own type, at the document's stamped version. A reactor without\n* that module folds nothing, so conditions read the base state and an\n* unresolvable reducer never widens access.\n*/\nfunction applyModelOperation(registry, document, operation) {\n\tlet reducer;\n\ttry {\n\t\tconst version = normalizeDocumentModelVersion(document.state.document?.version);\n\t\treducer = registry.getModule(document.header.documentType, version).reducer;\n\t} catch {\n\t\treturn document;\n\t}\n\treturn reducer(document, operation.action);\n}\n/**\n* The auth model extended with a derived groups projection: the streams it\n* reads are the group documents the folded grant list names, so adding a\n* grant that names a new group pulls that group's stream into the read-set.\n* Group queries pin the main branch, because a group's member list lives on\n* its main branch no matter which branch the referencing document is on.\n*/\nfunction groupsProjection(registry) {\n\treturn {\n\t\tdecidingActions: [...groupMembershipActionTypes],\n\t\tapply: (document, operation) => applyGroupOperation(registry, document, operation),\n\t\tquery: (model) => referencedGroupIds(model.auth?.grants ?? []).map((id) => ({\n\t\t\tdocumentId: id,\n\t\t\tbranch: \"main\",\n\t\t\tscope: \"global\"\n\t\t})),\n\t\tqueryOverHistory: (reads) => {\n\t\t\tconst ids = [];\n\t\t\tfor (const read of reads) {\n\t\t\t\tif (read.name !== \"auth\") continue;\n\t\t\t\tfor (const operation of read.operations) for (const id of mentionedGroupIds(operation.action)) if (!ids.includes(id)) ids.push(id);\n\t\t\t}\n\t\t\treturn ids.map((id) => ({\n\t\t\t\tdocumentId: id,\n\t\t\t\tbranch: \"main\",\n\t\t\t\tscope: \"global\"\n\t\t\t}));\n\t\t}\n\t};\n}\nfunction authGroupsDecisionModel(registry) {\n\treturn (target) => ({\n\t\tprojections: {\n\t\t\tdocument: documentProjection(target),\n\t\t\tauth: authProjection(target),\n\t\t\tgroups: groupsProjection(registry)\n\t\t},\n\t\tevaluatesScope() {\n\t\t\treturn true;\n\t\t},\n\t\tdecide(model, subject, request) {\n\t\t\treturn decideAuthModel(model, subject, request, model.groups);\n\t\t}\n\t});\n}\n/**\n* The groups model with conditions live: decide hands the executing scope's\n* state and the action input through to the evaluator, so `where` clauses\n* and { match } principals apply. The model folds the evaluated scope during\n* a positional walk, so a condition reads the state as it stood at each\n* operation's position.\n*/\nfunction authConditionsDecisionModel(registry) {\n\treturn (target) => ({\n\t\tprojections: {\n\t\t\tdocument: documentProjection(target),\n\t\t\tauth: authProjection(target),\n\t\t\tgroups: groupsProjection(registry)\n\t\t},\n\t\tfoldEvaluatedScope: (document, operation) => applyModelOperation(registry, document, operation),\n\t\tevaluatesScope() {\n\t\t\treturn true;\n\t\t},\n\t\tdecide(model, subject, request, ctx) {\n\t\t\treturn decideAuthModel(model, subject, request, model.groups, {\n\t\t\t\tscopeState: ctx.scopeState,\n\t\t\t\tactionInput: ctx.actionInput\n\t\t\t});\n\t\t}\n\t});\n}\n//#endregion\n//#region src/decision/document-decision-model.ts\n/**\n* The simplest decision model: one projection over the document scope, which\n* rejects on a deleted document.\n*/\nfunction documentDecisionModel(target) {\n\treturn {\n\t\tprojections: { document: {\n\t\t\tdecidingActions: [\"DELETE_DOCUMENT\"],\n\t\t\tapply: (document, operation) => operation.action.type === \"DELETE_DOCUMENT\" ? applyDeleteDocumentAction({\n\t\t\t\t...document,\n\t\t\t\tstate: { ...document.state }\n\t\t\t}, operation.action) : document,\n\t\t\tquery: {\n\t\t\t\tdocumentId: target.documentId,\n\t\t\t\tbranch: target.branch,\n\t\t\t\tscope: \"document\"\n\t\t\t}\n\t\t} },\n\t\tevaluatesScope() {\n\t\t\treturn true;\n\t\t},\n\t\tdecide(model, subject, request) {\n\t\t\treturn request.verb === \"execute\" && model.document.isDeleted ? {\n\t\t\t\tdecision: \"deny\",\n\t\t\t\treason: DOCUMENT_DELETED_REASON\n\t\t\t} : { decision: \"allow\" };\n\t\t}\n\t};\n}\n//#endregion\n//#region src/decision/registered-model.ts\n/**\n* Builds the model at the stream heads and decides one request against it. The\n* append condition it returns is the read-set the store enforces at write time.\n*\n* With `conditions` supplied, the executing scope's state is read at the head\n* for `doc.<scope>.*` paths, or taken from the run's carried document when the\n* caller has already reduced earlier writes into it. That read carries no\n* append-condition entry of its own: the written stream's expected-revision\n* check already refuses a write whose scope grew between the read and the\n* append.\n*/\nasync function decideAtHead(model, cache, target, subject, request, signal, conditions) {\n\tconst built = await buildDecisionModel(cache, model, target, signal);\n\tlet scopeState;\n\tif (conditions !== void 0) scopeState = (conditions.carriedDocument ?? await cache.getState(target.documentId, request.scope, target.branch, void 0, signal)).state[request.scope];\n\treturn {\n\t\tevaluation: model(target).decide(built.model, subject, request, {\n\t\t\tscopeState,\n\t\t\tactionInput: conditions?.actionInput\n\t\t}),\n\t\tappendCondition: built.appendCondition,\n\t\tdocumentVersion: built.model.document.version,\n\t\tdeletedAtUtcIso: built.model.document.deletedAtUtcIso ?? null\n\t};\n}\n/**\n* The model this reactor enforces. With `authEnforcement` off the auth scope is\n* absent from every append condition and no load walks it; with `authGroups`\n* on, the group documents the grant list names join the read-set and the\n* registry supplies the reducer that folds them.\n*/\nfunction selectDecisionModel(flags, registry) {\n\tif (flags.authConditions) return authConditionsDecisionModel(registry);\n\tif (flags.authGroups) return authGroupsDecisionModel(registry);\n\treturn flags.authEnforcement ? authDecisionModel : documentDecisionModel;\n}\n//#endregion\n//#region src/executor/util.ts\n/** Actions the reactor reduces itself, onto the document scope. */\nconst DOCUMENT_SCOPE_ACTIONS = DOCUMENT_SCOPE_ACTION_TYPES;\n/**\n* `CREATE_DOCUMENT` is exempt by necessity: it runs before the document exists,\n* so building a decision model would throw and defer the job forever.\n*/\nconst GATED_DOCUMENT_ACTIONS = new Set([...DOCUMENT_SCOPE_ACTIONS].filter((type) => type !== \"CREATE_DOCUMENT\"));\n/**\n* Creates a PHDocument from a CREATE_DOCUMENT action input.\n* Reconstructs the document header and initializes the base state.\n*\n* @param action - The CREATE_DOCUMENT action containing the document parameters\n* @returns A newly constructed PHDocument with initialized header and base state\n*/\nfunction createDocumentFromAction(action) {\n\tconst input = action.input;\n\tconst header = createPresignedHeader();\n\theader.id = input.documentId;\n\theader.documentType = input.model;\n\tif (input.signing) {\n\t\theader.createdAtUtcIso = input.signing.createdAtUtcIso;\n\t\theader.lastModifiedAtUtcIso = input.signing.createdAtUtcIso;\n\t\theader.sig = {\n\t\t\tpublicKey: input.signing.publicKey,\n\t\t\tnonce: input.signing.nonce\n\t\t};\n\t}\n\tif (input.slug !== void 0) header.slug = input.slug;\n\tif (!header.slug) header.slug = input.documentId;\n\tif (input.name !== void 0) header.name = input.name;\n\tif (input.branch !== void 0) header.branch = input.branch;\n\tif (input.meta !== void 0) header.meta = input.meta;\n\tif (input.protocolVersions !== void 0) header.protocolVersions = input.protocolVersions;\n\tconst baseState = defaultBaseState();\n\treturn {\n\t\theader,\n\t\toperations: {},\n\t\tstate: baseState,\n\t\tinitialState: baseState,\n\t\tclipboard: []\n\t};\n}\n/**\n* Calculate the next operation index for a specific scope.\n* Each scope maintains its own independent index sequence.\n*\n* Per-scope indexing means:\n* - Each scope (document, global, local, etc.) has independent indexes\n* - Indexes start at 0 for each scope\n* - Different scopes can have operations with the same index value\n*\n* This function uses header.revision which is populated by the cache/storage layer\n* and contains the next available index for each scope. This design avoids requiring\n* the full operation history to be loaded, which is crucial for snapshot-based caching.\n*\n* @param document - The document whose header.revision to inspect\n* @param scope - The scope to calculate the next index for\n* @returns The next available index in the specified scope\n*/\nconst getNextIndexForScope = (document, scope) => {\n\treturn document.header.revision[scope] || 0;\n};\n/**\n* Creates an empty consistency token with no coordinates.\n* Used when a job is registered or fails without writing operations.\n*\n* @returns A consistency token with an empty coordinates array\n*/\nfunction createEmptyConsistencyToken() {\n\treturn {\n\t\tversion: 1,\n\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tcoordinates: []\n\t};\n}\n/**\n* Creates a consistency token from operations written during job execution.\n* Maps each operation to a consistency coordinate tracking (documentId, scope, branch, operationIndex).\n* If no operations are provided, returns an empty token.\n*\n* @param operationsWithContext - Array of operations with their execution context\n* @returns A consistency token representing all operations written\n*/\nfunction createConsistencyToken(operationsWithContext) {\n\tif (operationsWithContext.length === 0) return createEmptyConsistencyToken();\n\tconst coordinates = [];\n\tfor (let i = 0; i < operationsWithContext.length; i++) {\n\t\tconst opWithContext = operationsWithContext[i];\n\t\tcoordinates.push({\n\t\t\tdocumentId: opWithContext.context.documentId,\n\t\t\tscope: opWithContext.context.scope,\n\t\t\tbranch: opWithContext.context.branch,\n\t\t\toperationIndex: opWithContext.operation.index\n\t\t});\n\t}\n\treturn {\n\t\tversion: 1,\n\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tcoordinates\n\t};\n}\nfunction createOperation(action, index, skip, context) {\n\treturn {\n\t\tid: deriveOperationId(context.documentId, context.scope, context.branch, action.id),\n\t\tindex,\n\t\ttimestampUtcMs: action.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString(),\n\t\thash: \"\",\n\t\tskip,\n\t\taction\n\t};\n}\nfunction updateDocumentRevision(document, scope, operationIndex) {\n\tdocument.header.revision = {\n\t\t...document.header.revision,\n\t\t[scope]: operationIndex + 1\n\t};\n}\nfunction buildSuccessResult(job, operation, documentId, documentType, resultingState, startTime) {\n\treturn {\n\t\tjob,\n\t\tsuccess: true,\n\t\toperations: [operation],\n\t\toperationsWithContext: [{\n\t\t\toperation,\n\t\t\tcontext: {\n\t\t\t\tdocumentId,\n\t\t\t\tscope: job.scope,\n\t\t\t\tbranch: job.branch,\n\t\t\t\tdocumentType,\n\t\t\t\tresultingState,\n\t\t\t\tordinal: 0\n\t\t\t}\n\t\t}],\n\t\tduration: Date.now() - startTime\n\t};\n}\nfunction buildErrorResult(job, error, startTime) {\n\treturn {\n\t\tjob,\n\t\tsuccess: false,\n\t\terror,\n\t\tduration: Date.now() - startTime\n\t};\n}\n/**\n* The error a refusal surfaces as. Both classes are already terminal in the job\n* result handler, so a refusal never burns a retry.\n*/\nfunction refusalError(reason, documentId, deletedAtUtcIso, action) {\n\tif (reason === DOCUMENT_DELETED_REASON) return new DocumentDeletedError(documentId, deletedAtUtcIso);\n\treturn new AuthorizationDeniedError(documentId, action.scope, action.type, action.context?.signer?.user.address);\n}\n/**\n* Whether this operation is part of the document's creation. The create and the\n* upgrade from version zero hold the first two indexes for the life of the\n* document, so a reshuffle has to leave them where they are.\n*/\nfunction isGenesisOperation(operation) {\n\tif (operation.action.type === \"CREATE_DOCUMENT\") return true;\n\tif (operation.action.type !== \"UPGRADE_DOCUMENT\") return false;\n\treturn operation.action.input.fromVersion === 0;\n}\n/**\n* The distinct streams a job wrote, collected so a rollback knows what to evict.\n*\n* A write records its stream on every apply, and a long run applies the same\n* stream hundreds of times, so this keeps one entry per stream rather than one\n* per write: the eviction only cares which streams were touched, and the\n* successful jobs that never read this back pay for a lookup instead of an\n* allocation.\n*/\nvar TouchedStreams = class {\n\tstreams = /* @__PURE__ */ new Map();\n\tadd(documentId, scope, branch) {\n\t\tconst key = `${documentId}\\u0000${scope}\\u0000${branch}`;\n\t\tif (this.streams.has(key)) return;\n\t\tthis.streams.set(key, {\n\t\t\tdocumentId,\n\t\t\tscope,\n\t\t\tbranch\n\t\t});\n\t}\n\t[Symbol.iterator]() {\n\t\treturn this.streams.values();\n\t}\n};\n/**\n* The ids of the actions the caller handed to a job. Load and reevaluation\n* jobs write operations nobody submitted, so they report none.\n*/\nfunction submittedActionIds(job) {\n\treturn job.kind === \"mutation\" ? job.actions.map((action) => action.id) : [];\n}\n/**\n* Reports what became of each submitted action.\n*\n* A job's operations can include ones it only moved to a new index, so only\n* those carrying a submitted action are reported. Returns undefined when the\n* job submitted nothing, which keeps `JobInfo.result` null for the jobs that\n* have no caller to answer to.\n*/\nfunction summarizeSubmittedActions(operations, submitted) {\n\tif (!submitted || submitted.length === 0) return;\n\tconst ids = new Set(submitted);\n\tconst actions = [];\n\tfor (const { operation, context } of operations) {\n\t\tif (!ids.has(operation.action.id)) continue;\n\t\tactions.push({\n\t\t\tactionId: operation.action.id,\n\t\t\tscope: context.scope,\n\t\t\tindex: operation.index,\n\t\t\t...operationOutcome(operation)\n\t\t});\n\t}\n\tif (actions.length === 0) return;\n\treturn {\n\t\tactions,\n\t\tallApplied: actions.every((action) => action.kind === \"applied\")\n\t};\n}\n/** Tombstones a job has read, each under the shared lock it took first. */\nvar PurgeFence = class {\n\tlocks;\n\tchecked;\n\tpurged;\n\tconstructor(locks, checked, purged) {\n\t\tthis.locks = locks;\n\t\tthis.checked = checked;\n\t\tthis.purged = purged;\n\t}\n\t/** Locks and reads an id the job start did not resolve. */\n\tasync isPurged(documentId) {\n\t\tawait this.isPurgedMany([documentId]);\n\t\treturn this.purged.has(documentId);\n\t}\n\t/** Locks and reads the unresolved ids in one lock and one lookup. */\n\tasync isPurgedMany(documentIds) {\n\t\tconst unchecked = [...new Set(documentIds)].filter((id) => !this.checked.has(id));\n\t\tif (unchecked.length > 0) {\n\t\t\tawait this.locks.shared(unchecked);\n\t\t\tconst found = await this.locks.purged(unchecked);\n\t\t\tfor (const id of unchecked) this.checked.add(id);\n\t\t\tfor (const id of found) this.purged.add(id);\n\t\t}\n\t\treturn new Set(documentIds.filter((id) => this.purged.has(id)));\n\t}\n};\n/** Locks and checks an id on its first read; a purged id reads as purged. */\nvar FencedWriteCache = class {\n\tinner;\n\tpurgeFence;\n\tevict;\n\tevicted = /* @__PURE__ */ new Set();\n\tconstructor(inner, purgeFence, evict) {\n\t\tthis.inner = inner;\n\t\tthis.purgeFence = purgeFence;\n\t\tthis.evict = evict;\n\t}\n\t/** Fences ids known before their reads in one round trip. */\n\tasync fence(documentIds) {\n\t\tawait this.purgeFence.isPurgedMany(documentIds);\n\t}\n\tasync getState(documentId, scope, branch, targetRevision, signal) {\n\t\tif (await this.purgeFence.isPurged(documentId)) {\n\t\t\tif (!this.evicted.has(documentId)) {\n\t\t\t\tthis.evicted.add(documentId);\n\t\t\t\tthis.evict(documentId);\n\t\t\t}\n\t\t\tthrow new DocumentPurgedError(documentId);\n\t\t}\n\t\treturn this.inner.getState(documentId, scope, branch, targetRevision, signal);\n\t}\n\tputState(documentId, scope, branch, revision, document, position) {\n\t\tthis.inner.putState(documentId, scope, branch, revision, document, position);\n\t}\n\tputRun(documentId, scope, branch, run) {\n\t\tthis.inner.putRun(documentId, scope, branch, run);\n\t}\n\tinvalidate(documentId, scope, branch) {\n\t\treturn this.inner.invalidate(documentId, scope, branch);\n\t}\n\tclear() {\n\t\tthis.inner.clear();\n\t}\n\tstartup() {\n\t\treturn this.inner.startup();\n\t}\n\tshutdown() {\n\t\treturn this.inner.shutdown();\n\t}\n};\n/** The target whose membership an ADD or REMOVE_RELATIONSHIP writes. */\nfunction relationshipTarget(action) {\n\tif (action.type !== \"ADD_RELATIONSHIP\" && action.type !== \"REMOVE_RELATIONSHIP\") return;\n\tconst target = action.input?.targetId;\n\treturn typeof target === \"string\" && target.length > 0 ? target : void 0;\n}\n/** The ids a job's locks cover, sorted: its write ids and groups it names. */\nfunction jobWriteIds(job) {\n\tconst ids = /* @__PURE__ */ new Set([job.documentId]);\n\tconst actions = [...job.actions, ...job.operations.map((operation) => operation.action)];\n\tfor (const action of actions) {\n\t\tif (DOCUMENT_SCOPE_ACTIONS.has(action.type)) ids.add(targetDocumentId(action, job.documentId));\n\t\tconst target = relationshipTarget(action);\n\t\tif (target !== void 0) ids.add(target);\n\t\tif (action.scope === \"auth\") for (const groupId of mentionedGroupIds(action)) ids.add(groupId);\n\t}\n\treturn [...ids].sort();\n}\n//#endregion\n//#region src/registry/errors.ts\n/**\n* Error thrown when a document model module is not found in the registry.\n*/\nvar ModuleNotFoundError = class extends Error {\n\tdocumentType;\n\trequestedVersion;\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` version ${version}` : \"\";\n\t\tsuper(`Document model module not found for type: ${documentType}${versionSuffix}`);\n\t\tthis.name = \"ModuleNotFoundError\";\n\t\tthis.documentType = documentType;\n\t\tthis.requestedVersion = version;\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"ModuleNotFoundError\";\n\t}\n};\n/** The host has the model only as a live module, which workers cannot import. */\nvar ModelNotWorkerImportableError = class extends Error {\n\tdocumentType;\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` version ${version}` : \"\";\n\t\tsuper(`Document model ${documentType}${versionSuffix} is registered on the host only as a live module, so executor workers cannot load it. Register it from a { filePath } or { packageName } source.`);\n\t\tthis.name = \"ModelNotWorkerImportableError\";\n\t\tthis.documentType = documentType;\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"ModelNotWorkerImportableError\";\n\t}\n};\n/**\n* Error thrown when attempting to register a module that already exists.\n*/\nvar DuplicateModuleError = class extends Error {\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` (version ${version})` : \"\";\n\t\tsuper(`Document model module already registered for type: ${documentType}${versionSuffix}`);\n\t\tthis.name = \"DuplicateModuleError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DuplicateModuleError\";\n\t}\n};\n/**\n* Error thrown when a module is invalid or malformed.\n*/\nvar InvalidModuleError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(`Invalid document model module: ${message}`);\n\t\tthis.name = \"InvalidModuleError\";\n\t}\n};\n/**\n* Error thrown when attempting to register an upgrade manifest that already exists.\n*/\nvar DuplicateManifestError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Upgrade manifest already registered for type: ${documentType}`);\n\t\tthis.name = \"DuplicateManifestError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DuplicateManifestError\";\n\t}\n};\n/**\n* Error thrown when an upgrade manifest is not found.\n*/\nvar ManifestNotFoundError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Upgrade manifest not found for type: ${documentType}`);\n\t\tthis.name = \"ManifestNotFoundError\";\n\t}\n};\n/**\n* Error thrown when a required upgrade transition is missing from the manifest.\n*/\nvar MissingUpgradeTransitionError = class extends Error {\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Missing upgrade transition for ${documentType}: v${fromVersion} to v${toVersion}`);\n\t\tthis.name = \"MissingUpgradeTransitionError\";\n\t}\n};\n/**\n* Error thrown when getUpgradeReducer is called with a non-single-step version increment.\n*/\nvar InvalidUpgradeStepError = class extends Error {\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Invalid upgrade step for ${documentType}: must be single version increment, got v${fromVersion} to v${toVersion}`);\n\t\tthis.name = \"InvalidUpgradeStepError\";\n\t}\n};\n//#endregion\n//#region src/executor/types.ts\n/** 200k operations purge in 1.6 s on local Postgres; jobs time out at 30 s. */\nconst DEFAULT_MAX_PURGE_OPERATIONS = 2e5;\n/** How long a deferred job waits for its document before it fails. */\nconst DEFAULT_DEFERRED_JOB_TTL_MS = 3e4;\n/**\n* Event types for the job executor\n*/\nconst JobExecutorEventTypes = {\n\tJOB_STARTED: 2e4,\n\tJOB_COMPLETED: 20001,\n\tJOB_FAILED: 20002,\n\tEXECUTOR_STARTED: 20003,\n\tEXECUTOR_STOPPED: 20004\n};\n//#endregion\n//#region src/cache/collection-membership-cache.ts\nvar CollectionMembershipCache = class CollectionMembershipCache {\n\toperationIndex;\n\tcache = /* @__PURE__ */ new Map();\n\tconstructor(operationIndex) {\n\t\tthis.operationIndex = operationIndex;\n\t}\n\twithScopedIndex(operationIndex) {\n\t\tconst scoped = new CollectionMembershipCache(operationIndex);\n\t\tscoped.cache = this.cache;\n\t\treturn scoped;\n\t}\n\tasync getCollectionsForDocuments(documentIds) {\n\t\tconst result = {};\n\t\tconst missing = [];\n\t\tfor (const docId of documentIds) {\n\t\t\tconst cached = this.cache.get(docId);\n\t\t\tif (cached !== void 0) result[docId] = cached;\n\t\t\telse missing.push(docId);\n\t\t}\n\t\tif (missing.length > 0) {\n\t\t\tconst fromDb = await this.operationIndex.getCollectionsForDocuments(missing);\n\t\t\tfor (const docId of missing) {\n\t\t\t\tconst collections = fromDb[docId] ?? [];\n\t\t\t\tresult[docId] = collections;\n\t\t\t\tthis.cache.set(docId, collections);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tinvalidate(documentId) {\n\t\tthis.cache.delete(documentId);\n\t}\n};\n//#endregion\n//#region src/cache/lru/lru-tracker.ts\nvar LRUNode = class {\n\tkey;\n\tprev;\n\tnext;\n\tconstructor(key) {\n\t\tthis.key = key;\n\t\tthis.prev = void 0;\n\t\tthis.next = void 0;\n\t}\n};\nvar LRUTracker = class {\n\tmap;\n\thead;\n\ttail;\n\tconstructor() {\n\t\tthis.map = /* @__PURE__ */ new Map();\n\t\tthis.head = void 0;\n\t\tthis.tail = void 0;\n\t}\n\tget size() {\n\t\treturn this.map.size;\n\t}\n\ttouch(key) {\n\t\tconst node = this.map.get(key);\n\t\tif (node) this.moveToFront(node);\n\t\telse this.addToFront(key);\n\t}\n\tevict() {\n\t\tif (!this.tail) return;\n\t\tconst key = this.tail.key;\n\t\tthis.remove(key);\n\t\treturn key;\n\t}\n\tremove(key) {\n\t\tconst node = this.map.get(key);\n\t\tif (!node) return;\n\t\tthis.removeNode(node);\n\t\tthis.map.delete(key);\n\t}\n\tclear() {\n\t\tthis.map.clear();\n\t\tthis.head = void 0;\n\t\tthis.tail = void 0;\n\t}\n\taddToFront(key) {\n\t\tconst node = new LRUNode(key);\n\t\tthis.map.set(key, node);\n\t\tif (!this.head) {\n\t\t\tthis.head = node;\n\t\t\tthis.tail = node;\n\t\t} else {\n\t\t\tnode.next = this.head;\n\t\t\tthis.head.prev = node;\n\t\t\tthis.head = node;\n\t\t}\n\t}\n\tmoveToFront(node) {\n\t\tif (node === this.head) return;\n\t\tthis.removeNode(node);\n\t\tnode.prev = void 0;\n\t\tnode.next = this.head;\n\t\tif (this.head) this.head.prev = node;\n\t\tthis.head = node;\n\t\tif (!this.tail) this.tail = node;\n\t}\n\tremoveNode(node) {\n\t\tif (node.prev) node.prev.next = node.next;\n\t\telse this.head = node.next;\n\t\tif (node.next) node.next.prev = node.prev;\n\t\telse this.tail = node.prev;\n\t}\n};\n//#endregion\n//#region src/cache/document-meta-cache.ts\n/**\n* In-memory document metadata cache with LRU eviction.\n*\n* Caches PHDocumentState per (documentId, branch) key. On cache miss,\n* rebuilds from document scope operations. Provides an explicit cross-scope\n* contract for accessing document scope metadata.\n*\n* **Thread Safety:**\n* Not thread-safe. Designed for single-threaded job executor environment.\n*/\nvar DocumentMetaCache = class DocumentMetaCache {\n\tcache;\n\tlruTracker;\n\toperationStore;\n\tconfig;\n\tconstructor(operationStore, config) {\n\t\tthis.operationStore = operationStore;\n\t\tthis.config = { maxDocuments: config.maxDocuments };\n\t\tthis.cache = /* @__PURE__ */ new Map();\n\t\tthis.lruTracker = new LRUTracker();\n\t}\n\twithScopedStore(operationStore) {\n\t\tconst scoped = new DocumentMetaCache(operationStore, this.config);\n\t\tscoped.cache = this.cache;\n\t\tscoped.lruTracker = this.lruTracker;\n\t\treturn scoped;\n\t}\n\tasync startup() {\n\t\treturn Promise.resolve();\n\t}\n\tasync shutdown() {\n\t\treturn Promise.resolve();\n\t}\n\tasync getDocumentMeta(documentId, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst key = this.makeKey(documentId, branch);\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) {\n\t\t\tthis.lruTracker.touch(key);\n\t\t\treturn cached;\n\t\t}\n\t\tconst meta = await this.rebuildLatest(documentId, branch, signal);\n\t\tthis.putDocumentMeta(documentId, branch, meta);\n\t\treturn meta;\n\t}\n\tasync rebuildAtRevision(documentId, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn this.rebuildFromOperations(documentId, branch, targetRevision, signal);\n\t}\n\tputDocumentMeta(documentId, branch, meta) {\n\t\tconst key = this.makeKey(documentId, branch);\n\t\tif (!this.cache.has(key) && this.cache.size >= this.config.maxDocuments) {\n\t\t\tconst evictKey = this.lruTracker.evict();\n\t\t\tif (evictKey) this.cache.delete(evictKey);\n\t\t}\n\t\tthis.cache.set(key, structuredClone(meta));\n\t\tthis.lruTracker.touch(key);\n\t}\n\tinvalidate(documentId, branch) {\n\t\tlet evicted = 0;\n\t\tif (branch === void 0) {\n\t\t\tfor (const key of this.cache.keys()) if (key.startsWith(`${documentId}:`)) {\n\t\t\t\tthis.cache.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else {\n\t\t\tconst key = this.makeKey(documentId, branch);\n\t\t\tif (this.cache.has(key)) {\n\t\t\t\tthis.cache.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted = 1;\n\t\t\t}\n\t\t}\n\t\treturn evicted;\n\t}\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.lruTracker.clear();\n\t}\n\tmakeKey(documentId, branch) {\n\t\treturn `${documentId}:${branch}`;\n\t}\n\tasync rebuildLatest(documentId, branch, signal) {\n\t\treturn this.rebuildFromOperations(documentId, branch, void 0, signal);\n\t}\n\tasync rebuildFromOperations(documentId, branch, targetRevision, signal) {\n\t\tconst docScopeOps = await this.operationStore.getSince(documentId, \"document\", branch, -1, void 0, void 0, signal);\n\t\tif (docScopeOps.results.length === 0) throw new DocumentNotFoundError(documentId);\n\t\tconst createOp = docScopeOps.results[0];\n\t\tif (isPurgeMarker(createOp)) return purgedMeta(createOp.action);\n\t\tif (createOp.action.type !== \"CREATE_DOCUMENT\") throw new Error(`Invalid document: first operation must be CREATE_DOCUMENT, found ${createOp.action.type}`);\n\t\tconst createAction = createOp.action;\n\t\tconst documentType = createAction.input.model;\n\t\tlet document = createDocumentFromAction(createAction);\n\t\tlet documentScopeRevision = 0;\n\t\tlet purged = false;\n\t\tfor (const op of docScopeOps.results) {\n\t\t\tif (targetRevision !== void 0 && op.index > targetRevision) break;\n\t\t\tdocumentScopeRevision = op.index;\n\t\t\tif (op.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\tconst upgradeAction = op.action;\n\t\t\t\tdocument = applyUpgradeDocumentAction$1(document, upgradeAction);\n\t\t\t} else if (op.action.type === \"DELETE_DOCUMENT\" || op.action.type === PURGE_DOCUMENT) {\n\t\t\t\tdocument = applyDeleteDocumentAction$1(document, op.action);\n\t\t\t\tpurged ||= op.action.type === PURGE_DOCUMENT;\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType,\n\t\t\tprotocolVersions: purged ? purgedProtocolVersions() : createAction.input.protocolVersions,\n\t\t\tdocumentScopeRevision: documentScopeRevision + 1\n\t\t};\n\t}\n};\n/** A lone marker has no CREATE_DOCUMENT; the marker describes the stream. */\nfunction purgedMeta(action) {\n\treturn {\n\t\tstate: createDocumentState({\n\t\t\tisDeleted: true,\n\t\t\tdeletedAtUtcIso: action.input.purgedAtUtcIso\n\t\t}),\n\t\tdocumentType: action.input.documentType,\n\t\tprotocolVersions: purgedProtocolVersions(),\n\t\tdocumentScopeRevision: 1\n\t};\n}\n//#endregion\n//#region src/catch-up/settled-watermark.ts\nconst MAX_PENDING_PROBES = 64;\n/** pg_sequence_last_value needs 10; pg_current_* replaced txid_* in 13. */\nfunction snapshotFunctionsFor(serverVersionNum) {\n\tif (serverVersionNum >= 13e4) return {\n\t\tsnapshot: \"pg_current_snapshot\",\n\t\tcurrentXid: \"pg_current_xact_id\",\n\t\txidIfAssigned: \"pg_current_xact_id_if_assigned\"\n\t};\n\tif (serverVersionNum >= 1e5) return {\n\t\tsnapshot: \"txid_current_snapshot\",\n\t\tcurrentXid: \"txid_current\",\n\t\txidIfAssigned: \"txid_current_if_assigned\"\n\t};\n\tthrow new Error(`PostgreSQL server_version_num ${serverVersionNum} is not supported: read-side catch-up needs 10 or later`);\n}\n/** Parses the `xmin:xmax:xip,...` text form of a snapshot. */\nfunction parseSnapshot(text) {\n\tconst parts = text.split(\":\");\n\tif (parts.length !== 3) throw new Error(`Malformed snapshot: ${text}`);\n\tconst [xmin, xmax, xip] = parts;\n\treturn {\n\t\txmin: BigInt(xmin),\n\t\txmax: BigInt(xmax),\n\t\txip: xip === \"\" ? [] : xip.split(\",\").map((xid) => BigInt(xid))\n\t};\n}\nasync function readSnapshotFunctions(db) {\n\tconst result = await sql`select current_setting('server_version_num') as version`.execute(db);\n\treturn snapshotFunctionsFor(Number(result.rows[0].version));\n}\n/** A probe settles once an xmin passes the xid it took after its head. */\nvar ProbeSettler = class {\n\tsettled = 0;\n\tlastHead = 0;\n\tcovered = 0;\n\tlastXip = [];\n\tpending = [];\n\tget settledThrough() {\n\t\treturn this.settled;\n\t}\n\tget head() {\n\t\treturn this.lastHead;\n\t}\n\t/** The highest head a settled or pending probe covers. */\n\tget probedHead() {\n\t\treturn this.covered;\n\t}\n\tobserve(head, xid, snapshot, nowUtcMs) {\n\t\tthis.lastHead = Math.max(this.lastHead, head);\n\t\tthis.lastXip = snapshot.xip;\n\t\tif (xid !== null && head > this.covered) {\n\t\t\tthis.covered = head;\n\t\t\tthis.pending.push({\n\t\t\t\thead,\n\t\t\t\txid,\n\t\t\t\ttakenAtUtcMs: nowUtcMs\n\t\t\t});\n\t\t\tif (this.pending.length > MAX_PENDING_PROBES) this.pending.shift();\n\t\t}\n\t\tconst stillPending = [];\n\t\tfor (const probe of this.pending) if (snapshot.xmin > probe.xid) this.settled = Math.max(this.settled, probe.head);\n\t\telse stillPending.push(probe);\n\t\tthis.pending = stillPending.filter((probe) => probe.head > this.settled);\n\t\treturn this.settled;\n\t}\n\t/** Xids an unsettled probe still waits on. */\n\twaitingOn() {\n\t\tif (this.pending.length === 0) return [];\n\t\tconst xid = this.pending[0].xid;\n\t\treturn this.lastXip.filter((open) => open < xid).map((open) => open.toString());\n\t}\n\tstalledSinceUtcMs() {\n\t\treturn this.pending[0]?.takenAtUtcMs;\n\t}\n};\nfunction operationIndexTableName(db) {\n\tconst from = db.selectFrom(\"operation_index_operations\").selectAll().toOperationNode().from?.froms[0];\n\tconst schema = from !== void 0 && TableNode.is(from) ? from.table.schema?.name : void 0;\n\tconst quote = (identifier) => `\"${identifier.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\treturn schema === void 0 ? quote(\"operation_index_operations\") : `${quote(schema)}.${quote(\"operation_index_operations\")}`;\n}\n/** Reads the head, takes and commits an xid, then reads a snapshot, in order. */\nfunction createKyselyWatermarkProbe(db) {\n\tlet resolved = null;\n\tconst resolve = async () => {\n\t\tconst fns = await readSnapshotFunctions(db);\n\t\tconst table = operationIndexTableName(db);\n\t\tconst sequence = (await sql`select pg_get_serial_sequence(${table}, 'ordinal') as sequence`.execute(db)).rows[0]?.sequence;\n\t\tif (!sequence) throw new Error(`No ordinal sequence found for ${table}`);\n\t\treturn {\n\t\t\tfns,\n\t\t\tsequence\n\t\t};\n\t};\n\treturn async (probedHead) => {\n\t\tresolved ??= resolve().catch((error) => {\n\t\t\tresolved = null;\n\t\t\tthrow error;\n\t\t});\n\t\tconst { fns, sequence } = await resolved;\n\t\tconst headRow = (await sql`select coalesce(pg_sequence_last_value(${sequence}::regclass), 0) as head, ${sql.raw(fns.xidIfAssigned)}() is null as outside_write`.execute(db)).rows[0];\n\t\tconst head = Number(headRow.head);\n\t\tlet xid = null;\n\t\tif (headRow.outside_write && head > probedHead) {\n\t\t\tconst xidResult = await sql`select ${sql.raw(fns.currentXid)}()::text as xid`.execute(db);\n\t\t\txid = BigInt(xidResult.rows[0].xid);\n\t\t}\n\t\tconst row = (await sql`select ${sql.raw(fns.snapshot)}()::text as snapshot, ${sql.raw(fns.xidIfAssigned)}() is null as outside_write`.execute(db)).rows[0];\n\t\treturn {\n\t\t\thead,\n\t\t\txid,\n\t\t\tsnapshot: parseSnapshot(row.snapshot),\n\t\t\toutsideWrite: headRow.outside_write && row.outside_write\n\t\t};\n\t};\n}\n/** Knows when an ordinal gap is final by asking which transactions are open. */\nvar SettledWatermark = class {\n\tprobe;\n\tlogger;\n\tnow;\n\tsettler = new ProbeSettler();\n\tlisteners = /* @__PURE__ */ new Set();\n\tcurrent;\n\tnext;\n\twarnedInsideWrite = false;\n\tconstructor(probe, logger, now = Date.now) {\n\t\tthis.probe = probe;\n\t\tthis.logger = logger;\n\t\tthis.now = now;\n\t}\n\tget settledThrough() {\n\t\treturn this.settler.settledThrough;\n\t}\n\trefresh(signal) {\n\t\tsignal?.throwIfAborted();\n\t\tif (this.next !== void 0) return this.next;\n\t\tif (this.current === void 0) return this.start();\n\t\tconst next = this.current.catch(() => this.settledThrough).then(() => {\n\t\t\tthis.next = void 0;\n\t\t\treturn this.start();\n\t\t});\n\t\tthis.next = next;\n\t\treturn next;\n\t}\n\tonAdvance(listener) {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\tstatus() {\n\t\tconst stalledSinceUtcMs = this.settler.head > this.settledThrough ? this.settler.stalledSinceUtcMs() : void 0;\n\t\treturn {\n\t\t\thead: this.settler.head,\n\t\t\tsettledThrough: this.settledThrough,\n\t\t\twaitingOn: this.settler.waitingOn(),\n\t\t\t...stalledSinceUtcMs !== void 0 ? { stalledSinceUtcMs } : {}\n\t\t};\n\t}\n\tstart() {\n\t\tconst run = this.probeOnce().finally(() => {\n\t\t\tif (this.current === run) this.current = void 0;\n\t\t});\n\t\tthis.current = run;\n\t\treturn run;\n\t}\n\tasync probeOnce() {\n\t\tconst reading = await this.probe(this.settler.probedHead);\n\t\tif (!reading.outsideWrite) {\n\t\t\tif (!this.warnedInsideWrite) {\n\t\t\t\tthis.warnedInsideWrite = true;\n\t\t\t\tthis.logger.warn(\"settled watermark probe ran inside another session's write transaction; discarded\");\n\t\t\t}\n\t\t\treturn this.settledThrough;\n\t\t}\n\t\tconst before = this.settledThrough;\n\t\tconst after = this.settler.observe(reading.head, reading.xid, reading.snapshot, this.now());\n\t\tif (after > before) for (const listener of this.listeners) try {\n\t\t\tlistener(after);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"settled watermark listener failed: @error\", error);\n\t\t}\n\t\treturn after;\n\t}\n};\n/** Sessions holding these xids open; empty without pg_stat_activity. */\nasync function describeWaitingSessions(db, xids) {\n\tif (xids.length === 0) return [];\n\tconst epochless = xids.map((xid) => (BigInt(xid) % 2n ** 32n).toString());\n\ttry {\n\t\treturn (await sql`select pid, application_name, state, xact_start, backend_xid::text as xid\n from pg_stat_activity\n where backend_xid::text in (${sql.join(epochless)})`.execute(db)).rows.map((row) => ({\n\t\t\tpid: Number(row.pid),\n\t\t\tapplicationName: row.application_name ?? \"\",\n\t\t\tstate: row.state ?? \"\",\n\t\t\txactStart: row.xact_start === null ? null : new Date(row.xact_start).toISOString(),\n\t\t\txid: row.xid\n\t\t}));\n\t} catch {\n\t\treturn [];\n\t}\n}\n//#endregion\n//#region src/storage/kysely/document-purges.ts\n/** Class key of every purge lock; the stream locks use the single-key space. */\nconst PURGE_NS = 1347571013;\n/** Ids share this many lock keys, so a job's lock count stays bounded. */\nconst PURGE_LOCK_BUCKETS = 1024;\nasync function acquirePurgeLocks(trx, ids, mode) {\n\tconst unique = [...new Set(ids)];\n\tif (unique.length === 0) return;\n\tconst lock = sql.raw(mode === \"shared\" ? \"pg_advisory_xact_lock_shared\" : \"pg_advisory_xact_lock\");\n\tawait sql`\n with keys as materialized (\n select distinct hashtext(id) & ${sql.lit(1023)} as key\n from unnest(${unique}::text[]) as t(id)\n order by key\n )\n select ${lock}(${sql.lit(PURGE_NS)}, key) from keys order by key\n `.execute(trx);\n}\n/** The ids among `ids` that have a tombstone, read in the handle's schema. */\nasync function findPurged(db, ids) {\n\tconst unique = [...new Set(ids)];\n\tif (unique.length === 0) return /* @__PURE__ */ new Set();\n\tconst rows = await db.selectFrom(\"document_purges\").select(\"documentId\").where(sql`\"documentId\" = any(${unique}::text[])`).execute();\n\treturn new Set(rows.map((row) => row.documentId));\n}\n/** Every tombstoned id, read in the handle's schema. */\nasync function listPurged(db) {\n\treturn (await db.selectFrom(\"document_purges\").select(\"documentId\").orderBy(\"documentId\").execute()).map((row) => row.documentId);\n}\n/** Bind slots per statement: 16-bit on the wire, read signed in-process. */\nconst MAX_BIND_PARAMETERS = 32767;\n/** Splits rows into runs that each bind at most MAX_BIND_PARAMETERS. */\nfunction chunkRows(rows) {\n\tif (rows.length === 0) return [];\n\tconst columnsPerRow = Math.max(1, Object.keys(rows[0]).length);\n\tconst perChunk = Math.max(1, Math.floor(MAX_BIND_PARAMETERS / columnsPerRow));\n\tif (rows.length <= perChunk) return [rows];\n\tconst chunks = [];\n\tfor (let i = 0; i < rows.length; i += perChunk) chunks.push(rows.slice(i, i + perChunk));\n\treturn chunks;\n}\n/** Per database: the function that assigns the transaction's xid. */\nconst xidFunctions = /* @__PURE__ */ new WeakMap();\nvar KyselyOperationIndexTxn = class {\n\tcollections = [];\n\tcollectionMemberships = [];\n\tcollectionRemovals = [];\n\tgroupReferences = [];\n\toperations = [];\n\tmembershipInvalidations = /* @__PURE__ */ new Set();\n\t/** Called by the commit as it writes each document_collections row. */\n\trecordMembershipInvalidation(documentId) {\n\t\tthis.membershipInvalidations.add(documentId);\n\t}\n\tgetMembershipInvalidations() {\n\t\treturn [...this.membershipInvalidations];\n\t}\n\tcreateCollection(collectionId) {\n\t\tthis.collections.push(collectionId);\n\t}\n\taddToCollection(collectionId, documentId) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"addToCollection must be called after write() - no operations in transaction\");\n\t\tthis.collectionMemberships.push({\n\t\t\tcollectionId,\n\t\t\tdocumentId,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\tremoveFromCollection(collectionId, documentId) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"removeFromCollection must be called after write() - no operations in transaction\");\n\t\tthis.collectionRemovals.push({\n\t\t\tcollectionId,\n\t\t\tdocumentId,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\trecordGroupReferences(documentId, groupIds) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"recordGroupReferences must be called after write() - no operations in transaction\");\n\t\tif (groupIds.length === 0) return;\n\t\tthis.groupReferences.push({\n\t\t\tdocumentId,\n\t\t\tgroupIds,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\twrite(operations) {\n\t\tthis.operations.push(...operations);\n\t}\n\tgetCollections() {\n\t\treturn this.collections;\n\t}\n\tgetGroupReferenceRecords() {\n\t\treturn this.groupReferences;\n\t}\n\tgetCollectionMembershipRecords() {\n\t\treturn this.collectionMemberships;\n\t}\n\tgetCollectionRemovals() {\n\t\treturn this.collectionRemovals;\n\t}\n\tgetOperations() {\n\t\treturn this.operations;\n\t}\n};\nvar KyselyOperationIndex = class KyselyOperationIndex {\n\tdb;\n\ttrx;\n\tliveIds;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\t/** `liveIds`: ids the transaction read untombstoned under its shared lock. */\n\twithTransaction(trx, liveIds) {\n\t\tconst instance = new KyselyOperationIndex(this.db);\n\t\tinstance.trx = trx;\n\t\tinstance.liveIds = liveIds;\n\t\treturn instance;\n\t}\n\tstart() {\n\t\treturn new KyselyOperationIndexTxn();\n\t}\n\tasync commit(txn, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst kyselyTxn = txn;\n\t\tif (this.trx) return this.executeCommit(this.trx, kyselyTxn);\n\t\tlet resultOrdinals = [];\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tresultOrdinals = await this.executeCommit(trx, kyselyTxn);\n\t\t});\n\t\treturn resultOrdinals;\n\t}\n\t/**\n\t* A policy-driven join: keeps the earliest join so a rediscovered reference\n\t* never shrinks a backfill window remotes already rely on, and reopens a\n\t* closed membership because a policy reference is not a removable one.\n\t*/\n\tasync joinKeepingEarliest(trx, kyselyTxn, documentId, collectionId, ordinal) {\n\t\tkyselyTxn.recordMembershipInvalidation(documentId);\n\t\tawait trx.insertInto(\"document_collections\").values({\n\t\t\tdocumentId,\n\t\t\tcollectionId,\n\t\t\tjoinedOrdinal: ordinal,\n\t\t\tleftOrdinal: null\n\t\t}).onConflict((oc) => oc.columns([\"documentId\", \"collectionId\"]).doUpdateSet({\n\t\t\tjoinedOrdinal: sql`LEAST(\"document_collections\".\"joinedOrdinal\", EXCLUDED.\"joinedOrdinal\")`,\n\t\t\tleftOrdinal: null\n\t\t})).execute();\n\t}\n\tasync executeCommit(trx, kyselyTxn) {\n\t\tconst collections = kyselyTxn.getCollections();\n\t\tconst memberships = kyselyTxn.getCollectionMembershipRecords();\n\t\tconst removals = kyselyTxn.getCollectionRemovals();\n\t\tconst groupReferences = kyselyTxn.getGroupReferenceRecords();\n\t\tconst operations = kyselyTxn.getOperations();\n\t\tif (collections.length > 0) {\n\t\t\tconst collectionRows = collections.map((collectionId) => ({\n\t\t\t\tdocumentId: collectionId,\n\t\t\t\tcollectionId,\n\t\t\t\tjoinedOrdinal: BigInt(0),\n\t\t\t\tleftOrdinal: null\n\t\t\t}));\n\t\t\tfor (const collectionId of collections) kyselyTxn.recordMembershipInvalidation(collectionId);\n\t\t\tfor (const chunk of chunkRows(collectionRows)) await trx.insertInto(\"document_collections\").values(chunk).onConflict((oc) => oc.doNothing()).execute();\n\t\t}\n\t\tlet operationOrdinals = [];\n\t\tif (operations.length > 0) {\n\t\t\tawait this.refusePurgedOperations(trx, operations);\n\t\t\tawait this.assignXid(trx);\n\t\t\tconst operationRows = operations.map((op) => ({\n\t\t\t\topId: op.id || \"\",\n\t\t\t\tdocumentId: op.documentId,\n\t\t\t\tdocumentType: op.documentType,\n\t\t\t\tscope: op.scope,\n\t\t\t\tbranch: op.branch,\n\t\t\t\ttimestampUtcMs: op.timestampUtcMs,\n\t\t\t\tindex: op.index,\n\t\t\t\tskip: op.skip,\n\t\t\t\thash: op.hash,\n\t\t\t\taction: op.action,\n\t\t\t\tdeniedReason: op.deniedReason ?? null,\n\t\t\t\tsourceRemote: op.sourceRemote\n\t\t\t}));\n\t\t\tfor (const chunk of chunkRows(operationRows)) {\n\t\t\t\tconst insertedOps = await trx.insertInto(\"operation_index_operations\").values(chunk).returning(\"ordinal\").execute();\n\t\t\t\toperationOrdinals = operationOrdinals.concat(insertedOps.map((row) => row.ordinal));\n\t\t\t}\n\t\t}\n\t\tif (memberships.length > 0) for (const m of memberships) {\n\t\t\tconst ordinal = operationOrdinals[m.operationIndex];\n\t\t\tkyselyTxn.recordMembershipInvalidation(m.documentId);\n\t\t\tawait trx.insertInto(\"document_collections\").values({\n\t\t\t\tdocumentId: m.documentId,\n\t\t\t\tcollectionId: m.collectionId,\n\t\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\t\tleftOrdinal: null\n\t\t\t}).onConflict((oc) => oc.columns([\"documentId\", \"collectionId\"]).doUpdateSet({\n\t\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\t\tleftOrdinal: null\n\t\t\t})).execute();\n\t\t\tconst references = await trx.selectFrom(\"group_references\").select(\"groupId\").where(\"documentId\", \"=\", m.documentId).execute();\n\t\t\tfor (const { groupId } of references) await this.joinKeepingEarliest(trx, kyselyTxn, groupId, m.collectionId, BigInt(ordinal));\n\t\t}\n\t\tif (removals.length > 0) for (const r of removals) {\n\t\t\tconst ordinal = operationOrdinals[r.operationIndex];\n\t\t\tkyselyTxn.recordMembershipInvalidation(r.documentId);\n\t\t\tawait trx.updateTable(\"document_collections\").set({ leftOrdinal: BigInt(ordinal) }).where(\"collectionId\", \"=\", r.collectionId).where(\"documentId\", \"=\", r.documentId).where(\"leftOrdinal\", \"is\", null).execute();\n\t\t}\n\t\tif (groupReferences.length > 0) for (const record of groupReferences) {\n\t\t\tconst ordinal = operationOrdinals[record.operationIndex];\n\t\t\tawait trx.insertInto(\"group_references\").values(record.groupIds.map((groupId) => ({\n\t\t\t\tdocumentId: record.documentId,\n\t\t\t\tgroupId\n\t\t\t}))).onConflict((oc) => oc.doNothing()).execute();\n\t\t\tconst rows = await trx.selectFrom(\"document_collections\").select(\"collectionId\").where(\"documentId\", \"=\", record.documentId).execute();\n\t\t\tfor (const groupId of record.groupIds) for (const { collectionId } of rows) await this.joinKeepingEarliest(trx, kyselyTxn, groupId, collectionId, BigInt(ordinal));\n\t\t}\n\t\treturn operationOrdinals;\n\t}\n\tasync getCollectionsInRange(after, through, among, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tif (through <= after || among?.length === 0) return [];\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").select(\"dc.collectionId\").distinct().where(\"oi.ordinal\", \">\", after).where(\"oi.ordinal\", \"<=\", through);\n\t\tif (among !== void 0) query = query.where(\"dc.collectionId\", \"in\", [...among]);\n\t\treturn (await query.execute()).map((row) => row.collectionId);\n\t}\n\tasync getOrdinalsInRange(after, through, limit, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tif (through <= after || limit <= 0) return [];\n\t\treturn (await this.queryExecutor.selectFrom(\"operation_index_operations\").select(\"ordinal\").where(\"ordinal\", \">\", after).where(\"ordinal\", \"<=\", through).orderBy(\"ordinal\", \"asc\").limit(limit).execute()).map((row) => Number(row.ordinal));\n\t}\n\tasync getByOrdinals(ordinals, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tif (ordinals.length === 0) return [];\n\t\tconst results = [];\n\t\tfor (let i = 0; i < ordinals.length; i += MAX_BIND_PARAMETERS) {\n\t\t\tconst chunk = ordinals.slice(i, i + MAX_BIND_PARAMETERS);\n\t\t\tconst rows = await this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"ordinal\", \"in\", chunk).orderBy(\"ordinal\", \"asc\").execute();\n\t\t\tfor (const row of rows) results.push(this.rowToOperationWithContext(row));\n\t\t}\n\t\tresults.sort((a, b) => a.context.ordinal - b.context.ordinal);\n\t\treturn results;\n\t}\n\tasync getStreamAfter(stream, after, signal, limit) {\n\t\tsignal?.throwIfAborted();\n\t\treturn (await this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"documentId\", \"=\", stream.documentId).where(\"branch\", \"=\", stream.branch).where(\"scope\", \"=\", stream.scope).where(\"ordinal\", \">\", after).orderBy(\"ordinal\", \"asc\").$if(limit !== void 0, (qb) => qb.limit(limit)).execute()).map((row) => this.rowToOperationWithContext(row));\n\t}\n\tasync getGroupReferencers(groupId, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn (await this.queryExecutor.selectFrom(\"group_references\").select(\"documentId\").where(\"groupId\", \"=\", groupId).orderBy(\"documentId\").execute()).map((row) => row.documentId);\n\t}\n\tasync getOrdinalsByOpIds(documentId, scope, branch, opIds, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tif (opIds.length === 0) return /* @__PURE__ */ new Map();\n\t\tconst rows = await this.queryExecutor.selectFrom(\"operation_index_operations\").select(\"opId\").select((eb) => eb.fn.max(\"ordinal\").as(\"ordinal\")).where(\"documentId\", \"=\", documentId).where(\"branch\", \"=\", branch).where(\"scope\", \"=\", scope).where(\"opId\", \"in\", opIds).groupBy(\"opId\").execute();\n\t\treturn new Map(rows.map((row) => [row.opId, Number(row.ordinal)]));\n\t}\n\tasync find(collectionId, cursor, view, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst outerCursor = cursor ?? -1;\n\t\tconst limit = paging?.limit ?? 500;\n\t\tconst pagingCursorOrdinal = paging?.cursor !== void 0 ? Number.parseInt(paging.cursor, 10) : -1;\n\t\tconst buildBranch = (kind) => {\n\t\t\tlet qb = this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").selectAll(\"oi\").select([\"dc.documentId\", \"dc.collectionId\"]).where(\"dc.collectionId\", \"=\", collectionId).where(sql`(dc.\"leftOrdinal\" IS NULL OR oi.ordinal < dc.\"leftOrdinal\")`);\n\t\t\tif (kind === \"joiner\") qb = qb.where(\"dc.joinedOrdinal\", \">\", BigInt(outerCursor)).where(\"oi.ordinal\", \"<=\", outerCursor);\n\t\t\telse qb = qb.where(\"oi.ordinal\", \">\", outerCursor);\n\t\t\tqb = qb.where(\"oi.ordinal\", \">\", pagingCursorOrdinal);\n\t\t\tif (view?.branch) qb = qb.where(\"oi.branch\", \"=\", view.branch);\n\t\t\tif (view?.scopes && view.scopes.length > 0) qb = qb.where(\"oi.scope\", \"in\", view.scopes);\n\t\t\tif (view?.excludeSourceRemote) qb = qb.where(\"oi.sourceRemote\", \"!=\", view.excludeSourceRemote);\n\t\t\tif (view?.throughOrdinal !== void 0) qb = qb.where(\"oi.ordinal\", \"<=\", view.throughOrdinal).where(\"dc.joinedOrdinal\", \"<=\", BigInt(view.throughOrdinal));\n\t\t\treturn qb;\n\t\t};\n\t\tconst rows = await buildBranch(\"joiner\").unionAll(buildBranch(\"newOps\")).orderBy(\"ordinal\", \"asc\").limit(limit + 1).execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (rows.length > limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationIndexEntry(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.find(collectionId, cursor, view, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\tasync get(documentId, view, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst limit = paging?.limit ?? 500;\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"documentId\", \"=\", documentId).orderBy(\"ordinal\", \"asc\");\n\t\tif (view?.branch) query = query.where(\"branch\", \"=\", view.branch);\n\t\tif (view?.scopes && view.scopes.length > 0) query = query.where(\"scope\", \"in\", view.scopes);\n\t\tif (paging?.cursor) {\n\t\t\tconst cursorOrdinal = Number.parseInt(paging.cursor, 10);\n\t\t\tquery = query.where(\"ordinal\", \">\", cursorOrdinal);\n\t\t}\n\t\tquery = query.limit(limit + 1);\n\t\tconst rows = await query.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (rows.length > limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationIndexEntry(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.get(documentId, view, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\tasync getSinceOrdinal(ordinal, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst limit = paging?.limit ?? 500;\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"ordinal\", \">\", ordinal).orderBy(\"ordinal\", \"asc\");\n\t\tif (paging?.cursor) {\n\t\t\tconst cursorOrdinal = Number.parseInt(paging.cursor, 10);\n\t\t\tquery = query.where(\"ordinal\", \">\", cursorOrdinal);\n\t\t}\n\t\tquery = query.limit(limit + 1);\n\t\tconst rows = await query.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (rows.length > limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationWithContext(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.getSinceOrdinal(ordinal, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\t/** Backstop to the store's refusal: only a marker indexes a purged id. */\n\tasync refusePurgedOperations(trx, operations) {\n\t\tconst ids = new Set(operations.filter((operation) => !isPurgeMarker(operation)).map((operation) => operation.documentId).filter((id) => !this.liveIds?.has(id)));\n\t\tconst purged = await findPurged(trx, ids);\n\t\tfor (const id of ids) if (purged.has(id)) throw new DocumentPurgedError(id);\n\t}\n\t/** Takes the xid before the first ordinal, as the settled watermark needs. */\n\tasync assignXid(trx) {\n\t\tlet fn = xidFunctions.get(this.db);\n\t\tif (fn === void 0) {\n\t\t\tfn = readSnapshotFunctions(trx).then((fns) => fns.currentXid);\n\t\t\txidFunctions.set(this.db, fn);\n\t\t\tfn.catch(() => xidFunctions.delete(this.db));\n\t\t}\n\t\tconst name = await fn;\n\t\tawait sql`select ${sql.raw(name)}()`.execute(trx);\n\t}\n\trowToOperationWithContext(row) {\n\t\treturn {\n\t\t\toperation: {\n\t\t\t\tindex: row.index,\n\t\t\t\ttimestampUtcMs: row.timestampUtcMs,\n\t\t\t\thash: row.hash,\n\t\t\t\tskip: row.skip,\n\t\t\t\taction: row.action,\n\t\t\t\tdeniedReason: row.deniedReason ?? void 0,\n\t\t\t\tid: row.opId\n\t\t\t},\n\t\t\tcontext: {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tscope: row.scope,\n\t\t\t\tbranch: row.branch,\n\t\t\t\tordinal: row.ordinal\n\t\t\t}\n\t\t};\n\t}\n\trowToOperationIndexEntry(row) {\n\t\treturn {\n\t\t\tordinal: row.ordinal,\n\t\t\tdocumentId: row.documentId,\n\t\t\tdocumentType: row.documentType,\n\t\t\tbranch: row.branch,\n\t\t\tscope: row.scope,\n\t\t\tindex: row.index,\n\t\t\ttimestampUtcMs: row.timestampUtcMs,\n\t\t\thash: row.hash,\n\t\t\tskip: row.skip,\n\t\t\taction: row.action,\n\t\t\tdeniedReason: row.deniedReason ?? void 0,\n\t\t\tid: row.opId,\n\t\t\tsourceRemote: row.sourceRemote\n\t\t};\n\t}\n\tasync getLatestTimestampForCollection(collectionId, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn (await this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").select(\"oi.timestampUtcMs\").where(\"dc.collectionId\", \"=\", collectionId).where(sql`(dc.\"leftOrdinal\" IS NULL OR oi.ordinal < dc.\"leftOrdinal\")`).orderBy(\"oi.ordinal\", \"desc\").limit(1).executeTakeFirst())?.timestampUtcMs ?? null;\n\t}\n\tasync getCollectionsForDocuments(documentIds) {\n\t\tif (documentIds.length === 0) return {};\n\t\tconst rows = await this.queryExecutor.selectFrom(\"document_collections\").select([\"documentId\", \"collectionId\"]).where(\"documentId\", \"in\", documentIds).where(\"leftOrdinal\", \"is\", null).execute();\n\t\tconst result = {};\n\t\tfor (const row of rows) {\n\t\t\tif (!(row.documentId in result)) result[row.documentId] = [];\n\t\t\tresult[row.documentId].push(row.collectionId);\n\t\t}\n\t\treturn result;\n\t}\n};\n//#endregion\n//#region src/cache/buffer/ring-buffer.ts\n/**\n* RingBuffer is a generic circular buffer implementation that stores a fixed number\n* of items. When the buffer is full, new items overwrite the oldest items.\n*\n* This implementation maintains O(1) time complexity for push operations and provides\n* items in chronological order (oldest to newest) via getAll().\n*\n* @template T - The type of items stored in the buffer\n*/\nvar RingBuffer = class {\n\tbuffer;\n\thead = 0;\n\tsize = 0;\n\tcapacity;\n\tconstructor(capacity) {\n\t\tif (capacity <= 0) throw new Error(\"Ring buffer capacity must be greater than 0\");\n\t\tthis.capacity = capacity;\n\t\tthis.buffer = new Array(capacity);\n\t}\n\t/**\n\t* Adds an item to the buffer. If the buffer is full, overwrites the oldest item.\n\t*\n\t* @param item - The item to add\n\t*/\n\tpush(item) {\n\t\tconst index = (this.head + this.size) % this.capacity;\n\t\tif (this.size < this.capacity) {\n\t\t\tthis.buffer[index] = item;\n\t\t\tthis.size++;\n\t\t} else {\n\t\t\tthis.buffer[this.head] = item;\n\t\t\tthis.head = (this.head + 1) % this.capacity;\n\t\t}\n\t}\n\t/**\n\t* Returns all items in the buffer in chronological order (oldest to newest).\n\t*\n\t* @returns Array of items in insertion order\n\t*/\n\tgetAll() {\n\t\tif (this.size === 0) return [];\n\t\tconst result = [];\n\t\tfor (let i = 0; i < this.size; i++) {\n\t\t\tconst index = (this.head + i) % this.capacity;\n\t\t\tresult.push(this.buffer[index]);\n\t\t}\n\t\treturn result;\n\t}\n\t/**\n\t* Clears all items from the buffer.\n\t*/\n\tclear() {\n\t\tthis.buffer = new Array(this.capacity);\n\t\tthis.head = 0;\n\t\tthis.size = 0;\n\t}\n\t/**\n\t* Gets the current number of items in the buffer.\n\t*/\n\tget length() {\n\t\treturn this.size;\n\t}\n};\n//#endregion\n//#region src/cache/kysely-write-cache.ts\n/**\n* The last operation index a keyframe's document reflects for the scope. A\n* keyframe only exists for a scope that has operations, so a missing entry\n* means the stored row is corrupt.\n*/\nfunction keyframeRevision(keyframe, documentId, scope) {\n\tconst nextIndex = keyframe.document.header.revision[scope];\n\tif (typeof nextIndex !== \"number\") throw new Error(`Corrupt keyframe for document ${documentId} at revision ${keyframe.revision}: header carries no ${scope} revision`);\n\treturn nextIndex - 1;\n}\nfunction extractModuleVersion(doc) {\n\tconst v = doc.state.document.version;\n\treturn normalizeDocumentModelVersion(v);\n}\n/** The highest revision held, latest push winning a tie. */\nfunction highestRevision(snapshots) {\n\tlet newest = void 0;\n\tfor (const snapshot of snapshots) if (!newest || snapshot.revision >= newest.revision) newest = snapshot;\n\treturn newest;\n}\n/**\n* Copies a document far enough that the caller cannot write through it. Inside\n* this class, callers only ever replace whole fields on these four, so one\n* level each is enough.\n*/\nfunction copyDocument(document) {\n\treturn {\n\t\t...document,\n\t\theader: { ...document.header },\n\t\tstate: { ...document.state },\n\t\toperations: { ...document.operations }\n\t};\n}\nvar KyselyWriteCache = class KyselyWriteCache {\n\tstreams;\n\tlruTracker;\n\tkeyframeStore;\n\toperationStore;\n\tregistry;\n\tconfig;\n\treads = /* @__PURE__ */ new Map();\n\tconstructor(keyframeStore, operationStore, registry, config) {\n\t\tthis.keyframeStore = keyframeStore;\n\t\tthis.operationStore = operationStore;\n\t\tthis.registry = registry;\n\t\tthis.config = {\n\t\t\tmaxDocuments: config.maxDocuments,\n\t\t\tringBufferSize: config.ringBufferSize,\n\t\t\tkeyframeInterval: config.keyframeInterval\n\t\t};\n\t\tthis.streams = /* @__PURE__ */ new Map();\n\t\tthis.lruTracker = new LRUTracker();\n\t}\n\twithScopedStores(operationStore, keyframeStore) {\n\t\tconst scoped = new KyselyWriteCache(keyframeStore, operationStore, this.registry, this.config);\n\t\tscoped.streams = this.streams;\n\t\tscoped.lruTracker = this.lruTracker;\n\t\tscoped.reads = this.reads;\n\t\treturn scoped;\n\t}\n\t/**\n\t* Initializes the write cache.\n\t* Currently a no-op as keyframe store lifecycle is managed externally.\n\t*/\n\tasync startup() {\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Shuts down the write cache.\n\t* Currently a no-op as keyframe store lifecycle is managed externally.\n\t*/\n\tasync shutdown() {\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Retrieves document state at a specific revision from cache or rebuilds it.\n\t*\n\t* Note: this returns a _shallow_ copy of the document.\n\t*\n\t* Cache hit path: Returns cached snapshot if available (O(1))\n\t* Warm miss path: Rebuilds from cached base revision + incremental ops\n\t* Cold miss path: Rebuilds from keyframe or from scratch using all operations\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - The operation scope\n\t* @param branch - The operation branch\n\t* @param targetRevision - The target revision, or undefined for newest\n\t* @param signal - Optional abort signal to cancel the operation\n\t* @returns The document at the target revision\n\t* @throws {Error} \"Operation aborted\" if signal is aborted\n\t* @throws {ModuleNotFoundError} If document type not registered in registry\n\t* @throws {DocumentPurgedError} If the stream's only row is a purge marker\n\t* @throws {Error} \"Failed to rebuild document\" if operation store fails\n\t* @throws {Error} If reducer throws during operation application\n\t* @throws {Error} If document serialization fails\n\t*/\n\tasync getState(documentId, scope, branch, targetRevision, signal) {\n\t\tconst read = { evicted: false };\n\t\tlet pending = this.reads.get(documentId);\n\t\tif (!pending) {\n\t\t\tpending = /* @__PURE__ */ new Set();\n\t\t\tthis.reads.set(documentId, pending);\n\t\t}\n\t\tpending.add(read);\n\t\ttry {\n\t\t\treturn await this.readState(documentId, scope, branch, targetRevision, signal, read);\n\t\t} finally {\n\t\t\tpending.delete(read);\n\t\t\tif (pending.size === 0) this.reads.delete(documentId);\n\t\t}\n\t}\n\tasync readState(documentId, scope, branch, targetRevision, signal, read) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst streamKey = this.makeStreamKey(documentId, scope, branch);\n\t\tconst stream = this.streams.get(streamKey);\n\t\tif (stream) {\n\t\t\tconst snapshots = stream.ringBuffer.getAll();\n\t\t\tif (targetRevision === void 0) {\n\t\t\t\tconst newest = highestRevision(snapshots);\n\t\t\t\tif (newest?.position === \"head\") {\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn copyDocument(newest.document);\n\t\t\t\t}\n\t\t\t\tif (newest) {\n\t\t\t\t\tconst document = await this.warmMissRebuild(newest.document, newest.revision, documentId, scope, branch, void 0, signal);\n\t\t\t\t\tthis.storeUnlessEvicted(read, documentId, scope, branch, (document.header.revision[scope] ?? 0) - 1, document, \"head\");\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn document;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst exactMatch = snapshots.findLast((s) => s.revision === targetRevision);\n\t\t\t\tif (exactMatch) {\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn copyDocument(exactMatch.document);\n\t\t\t\t}\n\t\t\t\tconst newestOlder = this.findNearestOlderSnapshot(snapshots, targetRevision);\n\t\t\t\tif (newestOlder) {\n\t\t\t\t\tconst document = await this.warmMissRebuild(newestOlder.document, newestOlder.revision, documentId, scope, branch, targetRevision, signal);\n\t\t\t\t\tthis.storeUnlessEvicted(read, documentId, scope, branch, targetRevision, document, \"historical\");\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn document;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst document = await this.coldMissRebuild(documentId, scope, branch, targetRevision, signal);\n\t\tconst revision = targetRevision ?? (document.header.revision[scope] ?? 0) - 1;\n\t\tthis.storeUnlessEvicted(read, documentId, scope, branch, revision, document, targetRevision === void 0 ? \"head\" : \"historical\");\n\t\treturn document;\n\t}\n\t/**\n\t* Stores a document snapshot in the cache at a specific revision.\n\t*\n\t* The cached document is a shallow copy of the input with its operation history\n\t* truncated to the last operation per scope and its clipboard cleared. This keeps\n\t* memory use and copy costs constant regardless of operation count. Consumers of\n\t* getState() must not rely on the full operation history being present; the only\n\t* guaranteed invariant is that operations[scope].at(-1) reflects the latest\n\t* operation index for each scope.\n\t*\n\t* Updates LRU tracker and may evict least recently used stream if at capacity.\n\t* Asynchronously persists keyframes at configured intervals (fire-and-forget).\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - The operation scope\n\t* @param branch - The operation branch\n\t* @param revision - The revision number\n\t* @param document - The document to cache\n\t* @throws {Error} If document serialization fails\n\t*/\n\tputState(documentId, scope, branch, revision, document, position) {\n\t\tthis.store(documentId, scope, branch, revision, document, position);\n\t}\n\t/**\n\t* Stores the run's head and mints a keyframe for every interval the run\n\t* crossed on its way there. Only the head enters the ring buffer; the\n\t* earlier revisions are keyframe candidates and nothing more.\n\t*/\n\tputRun(documentId, scope, branch, run) {\n\t\tif (run.length === 0) return;\n\t\tfor (const entry of run.slice(0, -1)) this.persistKeyframe(documentId, scope, branch, entry.revision, entry.document);\n\t\tconst head = run[run.length - 1];\n\t\tthis.store(documentId, scope, branch, head.revision, head.document, \"head\");\n\t}\n\tstoreUnlessEvicted(read, documentId, scope, branch, revision, document, position) {\n\t\tif (!read.evicted) this.store(documentId, scope, branch, revision, document, position);\n\t}\n\tstore(documentId, scope, branch, revision, document, position) {\n\t\tconst streamKey = this.makeStreamKey(documentId, scope, branch);\n\t\tconst stream = this.getOrCreateStream(streamKey);\n\t\tconst snapshot = {\n\t\t\trevision,\n\t\t\tdocument: {\n\t\t\t\t...copyDocument(document),\n\t\t\t\toperations: Object.fromEntries(Object.entries(document.operations).map(([k, ops]) => [k, ops.length ? [ops.at(-1)] : []])),\n\t\t\t\tclipboard: []\n\t\t\t},\n\t\t\tposition\n\t\t};\n\t\tstream.ringBuffer.push(snapshot);\n\t\tthis.persistKeyframe(documentId, scope, branch, revision, document);\n\t}\n\t/** Persists the snapshot if this revision is one the interval falls on. */\n\tpersistKeyframe(documentId, scope, branch, revision, document) {\n\t\tif (!this.isKeyframeRevision(revision)) return;\n\t\tthis.keyframeStore.putKeyframe(documentId, scope, branch, revision, {\n\t\t\t...document,\n\t\t\toperations: {},\n\t\t\tclipboard: []\n\t\t}).catch((err) => {\n\t\t\tconsole.error(`Failed to persist keyframe ${documentId}@${revision}:`, err);\n\t\t});\n\t}\n\t/**\n\t* Invalidates cached document streams.\n\t*\n\t* Supports three invalidation scopes:\n\t* - Document-level: invalidate(documentId) - removes all streams for document\n\t* - Scope-level: invalidate(documentId, scope) - removes all branches for scope\n\t* - Stream-level: invalidate(documentId, scope, branch) - removes specific stream\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - Optional scope to narrow invalidation\n\t* @param branch - Optional branch to narrow invalidation (requires scope)\n\t* @returns The number of streams evicted\n\t*/\n\tinvalidate(documentId, scope, branch) {\n\t\tfor (const read of this.reads.get(documentId) ?? []) read.evicted = true;\n\t\tlet evicted = 0;\n\t\tif (scope === void 0 && branch === void 0) {\n\t\t\tfor (const [key] of this.streams.entries()) if (key.startsWith(`${documentId}:`)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else if (scope !== void 0 && branch === void 0) {\n\t\t\tfor (const [key] of this.streams.entries()) if (key.startsWith(`${documentId}:${scope}:`)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else if (scope !== void 0 && branch !== void 0) {\n\t\t\tconst key = this.makeStreamKey(documentId, scope, branch);\n\t\t\tif (this.streams.has(key)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted = 1;\n\t\t\t}\n\t\t}\n\t\treturn evicted;\n\t}\n\t/**\n\t* Clears the entire cache, removing all cached document streams.\n\t* Resets LRU tracking state. This operation always succeeds.\n\t*/\n\tclear() {\n\t\tfor (const pending of this.reads.values()) for (const read of pending) read.evicted = true;\n\t\tthis.streams.clear();\n\t\tthis.lruTracker.clear();\n\t}\n\t/**\n\t* Retrieves a specific stream for a document. Exposed on the implementation\n\t* for testing, but not on the interface.\n\t*\n\t* @internal\n\t*/\n\tgetStream(documentId, scope, branch) {\n\t\tconst key = this.makeStreamKey(documentId, scope, branch);\n\t\treturn this.streams.get(key);\n\t}\n\tasync findNearestKeyframe(documentId, scope, branch, targetRevision, signal) {\n\t\tif (targetRevision === Number.MAX_SAFE_INTEGER || targetRevision <= 0) return;\n\t\tconst keyframe = await this.keyframeStore.findNearestKeyframe(documentId, scope, branch, targetRevision, signal);\n\t\tif (!keyframe) return;\n\t\treturn {\n\t\t\trevision: Math.min(keyframeRevision(keyframe, documentId, scope), keyframe.revision),\n\t\t\tdocument: keyframe.document\n\t\t};\n\t}\n\t/**\n\t* Rebuilds a scope from a keyframe or from the whole operation history.\n\t*\n\t* The document scope is always rebuilt first, because it carries the type,\n\t* the upgrades and the deletion marker. Its version-changing upgrades are not\n\t* applied there though: an upgrade reducer must see the state the requested\n\t* scope has reached at that upgrade's boundary, so each one is held back and\n\t* applied when the replay below crosses the boundary that\n\t* resolveModuleVersionForOp derives from it. Upgrades whose boundary lies past\n\t* the last replayed operation are applied at the end. Creation-time 0->N seed\n\t* upgrades carry the initial state, so they still apply immediately.\n\t*/\n\tasync coldMissRebuild(documentId, scope, branch, targetRevision, signal, fromKeyframe = true) {\n\t\tconst effectiveTargetRevision = targetRevision || Number.MAX_SAFE_INTEGER;\n\t\tconst keyframe = fromKeyframe ? await this.findNearestKeyframe(documentId, scope, branch, effectiveTargetRevision, signal) : void 0;\n\t\tconst documentScopeBound = scope === \"document\" ? targetRevision : void 0;\n\t\tlet document;\n\t\tlet startRevision;\n\t\tlet documentType;\n\t\tconst validatedUpgrades = [];\n\t\tconst pendingUpgrades = [];\n\t\tlet lastDocumentScopeOperation;\n\t\tif (keyframe) {\n\t\t\tdocument = keyframe.document;\n\t\t\tstartRevision = keyframe.revision;\n\t\t\tdocumentType = keyframe.document.header.documentType;\n\t\t\tconst documentScopeResume = scope === \"document\" ? keyframe.revision : keyframeRevision(keyframe, documentId, \"document\");\n\t\t\tconst docScopeOpsAfterKeyframe = await this.operationStore.getSince(documentId, \"document\", branch, documentScopeResume, void 0, void 0, signal);\n\t\t\tfor (const operation of docScopeOpsAfterKeyframe.results) {\n\t\t\t\tif (documentScopeBound !== void 0 && operation.index > documentScopeBound) break;\n\t\t\t\tlastDocumentScopeOperation = operation;\n\t\t\t\tif (operation.error || isDenied(operation)) continue;\n\t\t\t\tif (operation.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\t\tconst upgradeAction = operation.action;\n\t\t\t\t\tconst fromVersion = upgradeAction.input.fromVersion;\n\t\t\t\t\tconst toVersion = upgradeAction.input.toVersion;\n\t\t\t\t\tif (fromVersion > 0 && fromVersion < toVersion) {\n\t\t\t\t\t\tlet upgradePath;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tupgradePath = this.registry.computeUpgradePath(documentType, fromVersion, toVersion);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tif (upgradeAction.input.initialState !== void 0) upgradePath = void 0;\n\t\t\t\t\t\t\telse throw new Error(`Failed to rebuild document ${documentId}: no upgrade manifest for ${documentType} v${fromVersion}→v${toVersion} and no initialState snapshot. ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalidatedUpgrades.push({\n\t\t\t\t\t\t\tfromVersion,\n\t\t\t\t\t\t\ttoVersion,\n\t\t\t\t\t\t\trevision: upgradeAction.input.revision,\n\t\t\t\t\t\t\ttimestampUtcMs: operation.timestampUtcMs\n\t\t\t\t\t\t});\n\t\t\t\t\t\tpendingUpgrades.push({\n\t\t\t\t\t\t\taction: upgradeAction,\n\t\t\t\t\t\t\tupgradePath,\n\t\t\t\t\t\t\tindex: operation.index,\n\t\t\t\t\t\t\tsubsequentDeletes: []\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (operation.action.type === \"DELETE_DOCUMENT\" || operation.action.type === PURGE_DOCUMENT) {\n\t\t\t\t\tapplyDeleteDocumentAction(document, operation.action);\n\t\t\t\t\tfor (const pending of pendingUpgrades) pending.subsequentDeletes.push(operation.action);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tstartRevision = -1;\n\t\t\tconst createOpResult = await this.operationStore.getSince(documentId, \"document\", branch, -1, void 0, {\n\t\t\t\tcursor: \"0\",\n\t\t\t\tlimit: 1\n\t\t\t}, signal);\n\t\t\tif (createOpResult.results.length === 0) throw new DocumentNotFoundError(documentId);\n\t\t\tconst createOp = createOpResult.results[0];\n\t\t\tif (isPurgeMarker(createOp)) throw new DocumentPurgedError(documentId);\n\t\t\tif (createOp.action.type !== \"CREATE_DOCUMENT\") throw new Error(`Failed to rebuild document ${documentId}: first operation in document scope must be CREATE_DOCUMENT, found ${createOp.action.type}`);\n\t\t\tconst documentCreateAction = createOp.action;\n\t\t\tdocumentType = documentCreateAction.input.model;\n\t\t\tif (!documentType) throw new Error(`Failed to rebuild document ${documentId}: CREATE_DOCUMENT action missing model in input`);\n\t\t\tdocument = createDocumentFromAction(documentCreateAction);\n\t\t\tlastDocumentScopeOperation = createOp;\n\t\t\tlet docModule = this.registry.getModule(documentType, extractModuleVersion(document));\n\t\t\tconst docScopeOps = await this.operationStore.getSince(documentId, \"document\", branch, 0, void 0, void 0, signal);\n\t\t\tfor (const operation of docScopeOps.results) {\n\t\t\t\tif (documentScopeBound !== void 0 && operation.index > documentScopeBound) break;\n\t\t\t\tlastDocumentScopeOperation = operation;\n\t\t\t\tif (operation.index === 0) continue;\n\t\t\t\tif (operation.error || isDenied(operation)) continue;\n\t\t\t\tif (operation.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\t\tconst upgradeAction = operation.action;\n\t\t\t\t\tconst fromVersion = upgradeAction.input.fromVersion;\n\t\t\t\t\tconst toVersion = upgradeAction.input.toVersion;\n\t\t\t\t\tif (fromVersion > 0 && fromVersion < toVersion) {\n\t\t\t\t\t\tlet upgradePath;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tupgradePath = this.registry.computeUpgradePath(documentType, fromVersion, toVersion);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tif (upgradeAction.input.initialState !== void 0) upgradePath = void 0;\n\t\t\t\t\t\t\telse throw new Error(`Failed to rebuild document ${documentId}: no upgrade manifest for ${documentType} v${fromVersion}→v${toVersion} and no initialState snapshot. ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalidatedUpgrades.push({\n\t\t\t\t\t\t\tfromVersion,\n\t\t\t\t\t\t\ttoVersion,\n\t\t\t\t\t\t\trevision: upgradeAction.input.revision,\n\t\t\t\t\t\t\ttimestampUtcMs: operation.timestampUtcMs\n\t\t\t\t\t\t});\n\t\t\t\t\t\tpendingUpgrades.push({\n\t\t\t\t\t\t\taction: upgradeAction,\n\t\t\t\t\t\t\tupgradePath,\n\t\t\t\t\t\t\tindex: operation.index,\n\t\t\t\t\t\t\tsubsequentDeletes: []\n\t\t\t\t\t\t});\n\t\t\t\t\t} else document = applyUpgradeDocumentAction(document, upgradeAction, void 0);\n\t\t\t\t\tdocModule = this.registry.getModule(documentType, normalizeDocumentModelVersion(toVersion));\n\t\t\t\t} else if (operation.action.type === \"DELETE_DOCUMENT\" || operation.action.type === PURGE_DOCUMENT) {\n\t\t\t\t\tapplyDeleteDocumentAction(document, operation.action);\n\t\t\t\t\tfor (const pending of pendingUpgrades) pending.subsequentDeletes.push(operation.action);\n\t\t\t\t} else {\n\t\t\t\t\tconst protocolVersion = baseReducerVersion(document.header);\n\t\t\t\t\tdocument = withProtocolVersions(docModule.reducer(document, operation.action, void 0, {\n\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\tprotocolVersion\n\t\t\t\t\t}), document.header.protocolVersions);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (scope === \"document\") {\n\t\t\tdocument = this.applyPendingUpgrades(document, pendingUpgrades, Number.MAX_SAFE_INTEGER);\n\t\t\tconst last = lastDocumentScopeOperation ?? await this.operationAt(documentId, \"document\", branch, startRevision, signal);\n\t\t\tdocument.operations = {\n\t\t\t\t...document.operations,\n\t\t\t\tdocument: last ? [last] : []\n\t\t\t};\n\t\t\treturn this.stampRevisions(document, documentId, scope, branch, targetRevision, signal);\n\t\t}\n\t\tif (keyframe) {\n\t\t\tconst resumeOperation = await this.operationAt(documentId, scope, branch, startRevision, signal);\n\t\t\tif (resumeOperation) document.operations = {\n\t\t\t\t...document.operations,\n\t\t\t\t[scope]: [resumeOperation]\n\t\t\t};\n\t\t}\n\t\tconst moduleCache = /* @__PURE__ */ new Map();\n\t\tconst getModuleCached = (version) => {\n\t\t\tconst key = version ?? 0;\n\t\t\tlet mod = moduleCache.get(key);\n\t\t\tif (!mod) {\n\t\t\t\tmod = this.registry.getModule(documentType, version);\n\t\t\t\tmoduleCache.set(key, mod);\n\t\t\t}\n\t\t\treturn mod;\n\t\t};\n\t\tconst finalVersion = validatedUpgrades.at(-1)?.toVersion ?? extractModuleVersion(document);\n\t\tlet cursor = void 0;\n\t\tconst pageSize = 100;\n\t\tlet hasMorePages;\n\t\tlet needsFullReplay = false;\n\t\tdo {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tconst paging = {\n\t\t\t\tcursor: cursor || \"0\",\n\t\t\t\tlimit: pageSize\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tconst result = await this.operationStore.getSince(documentId, scope, branch, startRevision, void 0, paging, signal);\n\t\t\t\tfor (const operation of result.results) {\n\t\t\t\t\tif (targetRevision !== void 0 && operation.index > targetRevision) break;\n\t\t\t\t\tif (keyframe && operation.skip > 0) {\n\t\t\t\t\t\tneedsFullReplay = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst moduleVersion = this.resolveModuleVersionForOp(operation.index, operation.timestampUtcMs, scope, validatedUpgrades, finalVersion);\n\t\t\t\t\tdocument = this.applyPendingUpgrades(document, pendingUpgrades, moduleVersion ?? Number.MAX_SAFE_INTEGER);\n\t\t\t\t\tif (isDenied(operation)) document = appendWithoutApplying(document, operation, scope);\n\t\t\t\t\telse {\n\t\t\t\t\t\tconst protocolVersion = baseReducerVersion(document.header);\n\t\t\t\t\t\tdocument = withProtocolVersions(getModuleCached(moduleVersion).reducer(document, operation.action, void 0, {\n\t\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\t\tprotocolVersion,\n\t\t\t\t\t\t\treplayOptions: { operation },\n\t\t\t\t\t\t\tskipIndexValidation: true\n\t\t\t\t\t\t}), document.header.protocolVersions);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst reachedTarget = targetRevision !== void 0 && result.results.some((op) => op.index >= targetRevision);\n\t\t\t\thasMorePages = Boolean(result.nextCursor) && !reachedTarget && !needsFullReplay;\n\t\t\t\tif (hasMorePages) cursor = result.nextCursor;\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(`Failed to rebuild document ${documentId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t}\n\t\t} while (hasMorePages);\n\t\tif (needsFullReplay) return this.coldMissRebuild(documentId, scope, branch, targetRevision, signal, false);\n\t\tdocument = this.applyTailPendingUpgrades(document, pendingUpgrades, scope, targetRevision);\n\t\tdocument = await this.stampRevisions(document, documentId, scope, branch, targetRevision, signal);\n\t\tif (pendingUpgrades.length > 0) {\n\t\t\tconst firstHeldBack = pendingUpgrades[0];\n\t\t\tconst stamped = document.header.revision[\"document\"] ?? 0;\n\t\t\tdocument.header.revision = {\n\t\t\t\t...document.header.revision,\n\t\t\t\tdocument: Math.min(stamped, firstHeldBack.index)\n\t\t\t};\n\t\t}\n\t\treturn document;\n\t}\n\t/**\n\t* Applies and removes every held-back upgrade whose target version is at or\n\t* below `throughVersion`, in the order the document scope recorded them.\n\t*/\n\tapplyPendingUpgrades(document, pendingUpgrades, throughVersion) {\n\t\twhile (pendingUpgrades.length > 0) {\n\t\t\tconst pending = pendingUpgrades[0];\n\t\t\tif (throughVersion < pending.action.input.toVersion) break;\n\t\t\tpendingUpgrades.shift();\n\t\t\tdocument = this.applyPendingUpgrade(document, pending);\n\t\t}\n\t\treturn document;\n\t}\n\t/**\n\t* Applies the remaining held-back upgrades after the requested scope's\n\t* replay has finished. A head read applies them all. A positional read\n\t* applies only those whose boundary for this scope lies at or before the\n\t* target position: applying a later one would label migrated state with a\n\t* pre-upgrade revision, and a keyframe stored from that poisons every\n\t* rebuild that resumes from it. Boundaries come from the upgrade's revision\n\t* snapshot; an upgrade without one records no position for this scope, and\n\t* the replay loop not having crossed it already places it past the target.\n\t*/\n\tapplyTailPendingUpgrades(document, pendingUpgrades, scope, targetRevision) {\n\t\twhile (pendingUpgrades.length > 0) {\n\t\t\tconst pending = pendingUpgrades[0];\n\t\t\tif (targetRevision !== void 0) {\n\t\t\t\tconst snapshot = pending.action.input.revision;\n\t\t\t\tif (snapshot === void 0) break;\n\t\t\t\tif ((snapshot[scope] ?? 0) > targetRevision) break;\n\t\t\t}\n\t\t\tpendingUpgrades.shift();\n\t\t\tdocument = this.applyPendingUpgrade(document, pending);\n\t\t}\n\t\treturn document;\n\t}\n\t/**\n\t* Applies one held-back upgrade, then re-applies the deletes the document\n\t* scope recorded after it so the hold-back cannot invert their order.\n\t*/\n\tapplyPendingUpgrade(document, pending) {\n\t\tdocument = applyUpgradeDocumentAction(document, pending.action, pending.upgradePath);\n\t\tfor (const deleteAction of pending.subsequentDeletes) document = applyDeleteDocumentAction(document, deleteAction);\n\t\treturn document;\n\t}\n\t/**\n\t* Copies the current document revisions onto the document. Overwrites the\n\t* requested scope revision with the target revision, if provided.\n\t*/\n\tasync stampRevisions(document, documentId, scope, branch, targetRevision, signal) {\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tdocument.header.revision = revisions.revision;\n\t\tif (targetRevision !== void 0) document.header.revision = {\n\t\t\t...document.header.revision,\n\t\t\t[scope]: targetRevision + 1\n\t\t};\n\t\tdocument.header.lastModifiedAtUtcIso = revisions.latestTimestamp;\n\t\treturn document;\n\t}\n\t/** The stored operation at `index`, or undefined if it is no longer there. */\n\tasync operationAt(documentId, scope, branch, index, signal) {\n\t\tif (index < 0) return;\n\t\tconst operation = (await this.operationStore.getSince(documentId, scope, branch, index - 1, void 0, {\n\t\t\tcursor: \"0\",\n\t\t\tlimit: 1\n\t\t}, signal)).results[0];\n\t\treturn operation && operation.index === index ? operation : void 0;\n\t}\n\t/**\n\t* Resolves which module version to use for a given operation in phase 2.\n\t*\n\t* Uses the validated-upgrade boundary rules from D7:\n\t* - If `input.revision` is present: op.index < revision[scope] → before the upgrade boundary\n\t* - Otherwise: timestamp fallback\n\t* - Falls back to final module version when neither is decidable\n\t*/\n\tresolveModuleVersionForOp(opIndex, opTimestamp, scope, validatedUpgrades, finalVersion) {\n\t\tif (validatedUpgrades.length === 0) return finalVersion;\n\t\tlet currentVersion = validatedUpgrades[0]?.fromVersion;\n\t\tfor (const upgrade of validatedUpgrades) {\n\t\t\tlet beforeUpgrade;\n\t\t\tif (upgrade.revision !== void 0) beforeUpgrade = opIndex < (upgrade.revision[scope] ?? 0);\n\t\t\telse beforeUpgrade = opTimestamp < upgrade.timestampUtcMs;\n\t\t\tif (beforeUpgrade) return currentVersion;\n\t\t\tcurrentVersion = upgrade.toVersion;\n\t\t}\n\t\treturn currentVersion;\n\t}\n\tasync warmMissRebuild(baseDocument, baseRevision, documentId, scope, branch, targetRevision, signal) {\n\t\tconst documentType = baseDocument.header.documentType;\n\t\tconst docScopeNextIndex = baseDocument.header.revision[\"document\"] ?? 0;\n\t\tif ((await this.operationStore.getSince(documentId, \"document\", branch, docScopeNextIndex - 1, void 0, void 0, signal)).results.length > 0) return this.coldMissRebuild(documentId, scope, branch, targetRevision, signal);\n\t\tconst module = this.registry.getModule(documentType, extractModuleVersion(baseDocument));\n\t\tlet document = copyDocument(baseDocument);\n\t\tlet needsFullReplay = false;\n\t\ttry {\n\t\t\tconst pagedResults = await this.operationStore.getSince(documentId, scope, branch, baseRevision, void 0, void 0, signal);\n\t\t\tfor (const operation of pagedResults.results) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\tif (targetRevision !== void 0 && operation.index > targetRevision) break;\n\t\t\t\tif (operation.skip > 0) {\n\t\t\t\t\tneedsFullReplay = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (isDenied(operation)) document = appendWithoutApplying(document, operation, scope);\n\t\t\t\telse {\n\t\t\t\t\tconst protocolVersion = baseReducerVersion(document.header);\n\t\t\t\t\tdocument = withProtocolVersions(module.reducer(document, operation.action, void 0, {\n\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\tprotocolVersion,\n\t\t\t\t\t\treplayOptions: { operation },\n\t\t\t\t\t\tskipIndexValidation: true\n\t\t\t\t\t}), document.header.protocolVersions);\n\t\t\t\t}\n\t\t\t\tif (targetRevision !== void 0 && operation.index === targetRevision) break;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthrow new Error(`Failed to rebuild document ${documentId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t}\n\t\tif (needsFullReplay) return this.coldMissRebuild(documentId, scope, branch, targetRevision, signal, false);\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tdocument.header.revision = revisions.revision;\n\t\tif (targetRevision !== void 0) document.header.revision = {\n\t\t\t...document.header.revision,\n\t\t\t[scope]: targetRevision + 1\n\t\t};\n\t\tdocument.header.lastModifiedAtUtcIso = revisions.latestTimestamp;\n\t\treturn document;\n\t}\n\tfindNearestOlderSnapshot(snapshots, targetRevision) {\n\t\tlet nearest = void 0;\n\t\tfor (const snapshot of snapshots) if (snapshot.revision < targetRevision) {\n\t\t\tif (!nearest || snapshot.revision > nearest.revision) nearest = snapshot;\n\t\t}\n\t\treturn nearest;\n\t}\n\tmakeStreamKey(documentId, scope, branch) {\n\t\treturn `${documentId}:${scope}:${branch}`;\n\t}\n\tgetOrCreateStream(key) {\n\t\tlet stream = this.streams.get(key);\n\t\tif (!stream) {\n\t\t\tif (this.streams.size >= this.config.maxDocuments) {\n\t\t\t\tconst evictKey = this.lruTracker.evict();\n\t\t\t\tif (evictKey) this.streams.delete(evictKey);\n\t\t\t}\n\t\t\tstream = {\n\t\t\t\tkey,\n\t\t\t\tringBuffer: new RingBuffer(this.config.ringBufferSize)\n\t\t\t};\n\t\t\tthis.streams.set(key, stream);\n\t\t}\n\t\tthis.lruTracker.touch(key);\n\t\treturn stream;\n\t}\n\tisKeyframeRevision(revision) {\n\t\treturn revision > 0 && revision % this.config.keyframeInterval === 0;\n\t}\n};\n//#endregion\n//#region src/events/event-bus.ts\nvar EventBus = class {\n\teventTypeToSubscribers = /* @__PURE__ */ new Map();\n\tsubscribe(type, subscriber) {\n\t\tlet list = this.eventTypeToSubscribers.get(type);\n\t\tif (!list) {\n\t\t\tlist = [];\n\t\t\tthis.eventTypeToSubscribers.set(type, list);\n\t\t}\n\t\tlist.push(subscriber);\n\t\tlet done = false;\n\t\treturn () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tconst arr = this.eventTypeToSubscribers.get(type);\n\t\t\tif (!arr) return;\n\t\t\tconst idx = arr.indexOf(subscriber);\n\t\t\tif (idx !== -1) arr.splice(idx, 1);\n\t\t\tif (arr.length === 0) this.eventTypeToSubscribers.delete(type);\n\t\t};\n\t}\n\tasync emit(type, data) {\n\t\tconst list = this.eventTypeToSubscribers.get(type);\n\t\tif (!list || list.length === 0) return;\n\t\tconst snapshot = list.slice();\n\t\tconst errors = [];\n\t\tfor (const fn of snapshot) try {\n\t\t\tawait Promise.resolve(fn(type, data));\n\t\t} catch (err) {\n\t\t\terrors.push(err);\n\t\t}\n\t\tif (errors.length > 0) throw new EventBusAggregateError(errors);\n\t}\n};\n//#endregion\n//#region src/core/feature-flags.ts\n/**\n* Every flag this reactor knows, with the flags it requires. A stage adds its\n* flag here when it ships, so asking an older reactor for a later stage's flag\n* is an unrecognized name rather than a flag that quietly does nothing.\n*/\nconst FLAG_PREREQUISITES = {\n\tdocumentDecisions: [],\n\tauthEnforcement: [\"documentDecisions\"],\n\tauthGroups: [\"authEnforcement\"],\n\tauthConditions: [\"authGroups\"]\n};\n/**\n* The flags as plain booleans, with anything unset off, validated. Callers hold\n* a partial set, because that is what crosses to a pooled worker, and every\n* consumer needs the same resolution of it.\n*/\nfunction resolveFeatureFlags(flags = {}) {\n\tconst resolved = {\n\t\tdocumentDecisions: flags.documentDecisions ?? false,\n\t\tauthEnforcement: flags.authEnforcement ?? false,\n\t\tauthGroups: flags.authGroups ?? false,\n\t\tauthConditions: flags.authConditions ?? false\n\t};\n\tvalidateFeatureFlags(flags, FLAG_PREREQUISITES);\n\treturn resolved;\n}\n/**\n* Throws when the flags ask for enforcement the reactor cannot deliver. Either\n* failure would otherwise read as enforcement being on while the reactor\n* applies less than the caller asked for.\n*/\nfunction validateFeatureFlags(flags, prerequisites) {\n\tconst known = Object.keys(prerequisites);\n\tconst unrecognized = Object.keys(flags).filter((name) => !known.includes(name));\n\tif (unrecognized.length > 0) throw new Error(`Unrecognized reactor feature flag: ${unrecognized.join(\", \")}. This reactor knows: ${known.join(\", \")}.`);\n\tfor (const name of known) {\n\t\tif (flags[name] !== true) continue;\n\t\tconst missing = prerequisites[name].filter((required) => flags[required] !== true);\n\t\tif (missing.length > 0) throw new Error(`Reactor feature flag ${name} requires ${missing.join(\", \")}.`);\n\t}\n}\n//#endregion\n//#region src/storage/kysely/document-purger.ts\n/** An `Operation` row whose DELETE_DOCUMENT applied: not errored, not denied. */\nconst appliedDelete = sql`action->>'type' = 'DELETE_DOCUMENT' and coalesce(error, '') = '' and coalesce(\"deniedReason\", '') = ''`;\n/** Rows removed per statement from the tables a document can fill. */\nconst DEFAULT_PURGE_DELETE_BATCH = 5e3;\n/** A purge transaction's statements; bound to the job's transaction. */\nvar KyselyDocumentPurger = class {\n\tbatchSize;\n\tdb;\n\tconstructor(db, batchSize = DEFAULT_PURGE_DELETE_BATCH) {\n\t\tthis.batchSize = batchSize;\n\t\tthis.db = db;\n\t}\n\t/** Every stream the document holds operations in. */\n\tasync streams(documentId) {\n\t\treturn this.db.selectFrom(\"Operation\").select([\"scope\", \"branch\"]).distinct().where(\"documentId\", \"=\", documentId).orderBy(\"scope\").orderBy(\"branch\").execute();\n\t}\n\tasync operationCount(documentId) {\n\t\tconst row = await this.db.selectFrom(\"operation_index_operations\").select((eb) => eb.fn.countAll().as(\"count\")).where(\"documentId\", \"=\", documentId).executeTakeFirst();\n\t\treturn Number(row?.count ?? 0);\n\t}\n\t/** Untombstoned documents group_references records as naming the group. */\n\tasync groupReferencers(groupId) {\n\t\tconst ids = (await this.db.selectFrom(\"group_references\").select(\"documentId\").where(\"groupId\", \"=\", groupId).where(\"documentId\", \"<>\", groupId).orderBy(\"documentId\").execute()).map((row) => row.documentId);\n\t\tconst purged = await findPurged(this.db, ids);\n\t\treturn ids.filter((id) => !purged.has(id));\n\t}\n\t/** Survivors whose accepted auth history names the group; refusals do not. */\n\tasync groupReferencersInHistory(groupId) {\n\t\tconst referencing = [];\n\t\tfor (const documentId of await this.groupReferencers(groupId)) if ([...(await this.authOperations(documentId)).values()].some((operations) => garbageCollect(sortOperations(operations)).some((operation) => operation.deniedReason === void 0 && operation.error === void 0 && mentionedGroupIds(operation.action).includes(groupId)))) referencing.push(documentId);\n\t\treturn referencing;\n\t}\n\t/** The document's auth-scope operations, per branch, in index order. */\n\tasync authOperations(documentId) {\n\t\tconst rows = await this.db.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", \"auth\").orderBy(\"branch\").orderBy(\"index\").execute();\n\t\tconst byBranch = /* @__PURE__ */ new Map();\n\t\tfor (const row of rows) {\n\t\t\tconst operations = byBranch.get(row.branch) ?? [];\n\t\t\toperations.push({\n\t\t\t\tindex: row.index,\n\t\t\t\ttimestampUtcMs: row.timestampUtcMs.toISOString(),\n\t\t\t\thash: row.hash,\n\t\t\t\tskip: row.skip,\n\t\t\t\terror: row.error || void 0,\n\t\t\t\tdeniedReason: row.deniedReason || void 0,\n\t\t\t\tid: row.opId,\n\t\t\t\taction: row.action\n\t\t\t});\n\t\t\tbyBranch.set(row.branch, operations);\n\t\t}\n\t\treturn byBranch;\n\t}\n\t/** Every document ever in the collection, but its owner and its own row. */\n\tasync collectionMembers(collectionId, ownerId, branch) {\n\t\treturn (await this.db.selectFrom(\"document_collections as dc\").select(\"dc.documentId\").select(sql`dc.\"leftOrdinal\" is null`.as(\"openHere\")).select((eb) => eb.exists(eb.selectFrom(\"Operation as op\").select(\"op.opId\").whereRef(\"op.documentId\", \"=\", \"dc.documentId\").where(\"op.branch\", \"=\", branch).where(\"op.scope\", \"=\", \"document\").where(appliedDelete)).as(\"deleted\")).select((eb) => eb.exists(eb.selectFrom(\"document_collections as other\").select(\"other.documentId\").whereRef(\"other.documentId\", \"=\", \"dc.documentId\").where(\"other.collectionId\", \"<>\", collectionId).where(\"other.leftOrdinal\", \"is\", null)).as(\"openElsewhere\")).where(\"dc.collectionId\", \"=\", collectionId).where(\"dc.documentId\", \"not in\", [ownerId, collectionId]).orderBy(\"dc.documentId\").execute()).map((row) => {\n\t\t\tconst openElsewhere = Boolean(row.openElsewhere);\n\t\t\treturn {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\topenElsewhere,\n\t\t\t\trequired: !openElsewhere && (Boolean(row.openHere) || Boolean(row.deleted))\n\t\t\t};\n\t\t});\n\t}\n\tasync remoteCollection(remoteName) {\n\t\treturn (await this.db.selectFrom(\"sync_remotes\").select(\"collection_id\").where(\"name\", \"=\", remoteName).executeTakeFirst())?.collection_id;\n\t}\n\t/** Deletes every row about the document; the counts are per table. */\n\tasync deleteRows(documentId) {\n\t\tconst removed = {};\n\t\tremoved.Operation = await this.deleteBatched(async () => {\n\t\t\tconst result = await this.db.deleteFrom(\"Operation\").where(\"id\", \"in\", (eb) => eb.selectFrom(\"Operation\").select(\"id\").where(\"documentId\", \"=\", documentId).limit(this.batchSize)).executeTakeFirst();\n\t\t\treturn Number(result.numDeletedRows);\n\t\t});\n\t\tremoved.operation_index_operations = await this.deleteBatched(async () => {\n\t\t\tconst result = await this.db.deleteFrom(\"operation_index_operations\").where(\"ordinal\", \"in\", (eb) => eb.selectFrom(\"operation_index_operations\").select(\"ordinal\").where(\"documentId\", \"=\", documentId).limit(this.batchSize)).executeTakeFirst();\n\t\t\treturn Number(result.numDeletedRows);\n\t\t});\n\t\tremoved.Keyframe = await this.deleteBatched(async () => {\n\t\t\tconst result = await this.db.deleteFrom(\"Keyframe\").where(\"id\", \"in\", (eb) => eb.selectFrom(\"Keyframe\").select(\"id\").where(\"documentId\", \"=\", documentId).limit(this.batchSize)).executeTakeFirst();\n\t\t\treturn Number(result.numDeletedRows);\n\t\t});\n\t\tremoved.DocumentSnapshot = await this.deleteBatched(async () => {\n\t\t\tconst result = await this.db.deleteFrom(\"DocumentSnapshot\").where(\"id\", \"in\", (eb) => eb.selectFrom(\"DocumentSnapshot\").select(\"id\").where(\"documentId\", \"=\", documentId).limit(this.batchSize)).executeTakeFirst();\n\t\t\treturn Number(result.numDeletedRows);\n\t\t});\n\t\tremoved.SlugMapping = await this.deleteWhere(\"SlugMapping\", \"documentId\", documentId);\n\t\tconst relationships = await this.db.selectFrom(\"DocumentRelationship\").select((eb) => eb.fn.countAll().as(\"count\")).where((eb) => eb.or([eb(\"sourceId\", \"=\", documentId), eb(\"targetId\", \"=\", documentId)])).executeTakeFirst();\n\t\tremoved.DocumentRelationship = Number(relationships?.count ?? 0);\n\t\tremoved.Document = await this.deleteWhere(\"Document\", \"id\", documentId);\n\t\tremoved.group_references = await this.deleteWhere(\"group_references\", \"documentId\", documentId);\n\t\tremoved.sync_dead_letters = await this.deleteWhere(\"sync_dead_letters\", \"document_id\", documentId);\n\t\tremoved.sync_holds = await this.deleteWhere(\"sync_holds\", \"document_id\", documentId);\n\t\treturn removed;\n\t}\n\tasync writeTombstone(tombstone) {\n\t\tconst values = {\n\t\t\tdocumentId: tombstone.documentId,\n\t\t\tordinal: tombstone.ordinal,\n\t\t\tremovedRows: JSON.stringify(tombstone.removedRows),\n\t\t\tpurgedAtUtc: tombstone.purgedAtUtc,\n\t\t\trequestId: tombstone.requestId\n\t\t};\n\t\tawait this.db.insertInto(\"document_purges\").values(values).onConflict((oc) => oc.column(\"documentId\").doUpdateSet({\n\t\t\tordinal: values.ordinal,\n\t\t\tremovedRows: values.removedRows,\n\t\t\tpurgedAtUtc: values.purgedAtUtc,\n\t\t\trequestId: values.requestId\n\t\t})).execute();\n\t}\n\t/** Reopens every membership at the marker ordinal, plus `collectionIds`. */\n\tasync reopenMemberships(documentId, ordinal, collectionIds = []) {\n\t\tawait this.db.updateTable(\"document_collections\").set({\n\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\tleftOrdinal: null\n\t\t}).where(\"documentId\", \"=\", documentId).execute();\n\t\tfor (const collectionId of new Set(collectionIds)) await this.db.insertInto(\"document_collections\").values({\n\t\t\tdocumentId,\n\t\t\tcollectionId,\n\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\tleftOrdinal: null\n\t\t}).onConflict((oc) => oc.columns([\"documentId\", \"collectionId\"]).doUpdateSet({\n\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\tleftOrdinal: null\n\t\t})).execute();\n\t\treturn (await this.db.selectFrom(\"document_collections\").select(\"collectionId\").where(\"documentId\", \"=\", documentId).orderBy(\"collectionId\").execute()).map((row) => row.collectionId);\n\t}\n\tasync deleteBatched(step) {\n\t\tlet total = 0;\n\t\tfor (;;) {\n\t\t\tconst deleted = await step();\n\t\t\ttotal += deleted;\n\t\t\tif (deleted < this.batchSize) return total;\n\t\t}\n\t}\n\tasync deleteWhere(table, column, documentId) {\n\t\tconst result = await this.db.deleteFrom(table).where(column, \"=\", documentId).executeTakeFirst();\n\t\treturn Number(result.numDeletedRows);\n\t}\n};\n//#endregion\n//#region src/executor/execution-scope.ts\n/** For scopes without a transaction to hold a lock in. */\nconst NOOP_DOCUMENT_LOCKS = {\n\tshared: () => Promise.resolve(),\n\texclusive: () => Promise.resolve(),\n\tpurged: () => Promise.resolve(/* @__PURE__ */ new Set())\n};\nvar DefaultExecutionScope = class {\n\toperationStore;\n\toperationIndex;\n\twriteCache;\n\tdocumentMetaCache;\n\tcollectionMembershipCache;\n\tconstructor(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache) {\n\t\tthis.operationStore = operationStore;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.writeCache = writeCache;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t}\n\tasync run(fn, signal) {\n\t\tsignal?.throwIfAborted();\n\t\treturn fn({\n\t\t\toperationStore: this.operationStore,\n\t\t\toperationIndex: this.operationIndex,\n\t\t\twriteCache: this.writeCache,\n\t\t\tdocumentMetaCache: this.documentMetaCache,\n\t\t\tcollectionMembershipCache: this.collectionMembershipCache,\n\t\t\tdocumentLocks: NOOP_DOCUMENT_LOCKS\n\t\t});\n\t}\n};\nvar KyselyExecutionScope = class {\n\tdb;\n\toperationStore;\n\toperationIndex;\n\tkeyframeStore;\n\twriteCache;\n\tdocumentMetaCache;\n\tcollectionMembershipCache;\n\tconstructor(db, operationStore, operationIndex, keyframeStore, writeCache, documentMetaCache, collectionMembershipCache) {\n\t\tthis.db = db;\n\t\tthis.operationStore = operationStore;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.keyframeStore = keyframeStore;\n\t\tthis.writeCache = writeCache;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t}\n\tasync run(fn, signal) {\n\t\tsignal?.throwIfAborted();\n\t\treturn this.db.transaction().execute(async (trx) => {\n\t\t\tconst sharedLocked = /* @__PURE__ */ new Set();\n\t\t\tconst liveIds = /* @__PURE__ */ new Set();\n\t\t\tconst scopedOperationStore = this.operationStore.withTransaction(trx, liveIds);\n\t\t\tconst scopedOperationIndex = this.operationIndex.withTransaction(trx, liveIds);\n\t\t\tconst scopedKeyframeStore = this.keyframeStore.withTransaction(trx);\n\t\t\treturn fn({\n\t\t\t\toperationStore: scopedOperationStore,\n\t\t\t\toperationIndex: scopedOperationIndex,\n\t\t\t\twriteCache: this.writeCache.withScopedStores(scopedOperationStore, scopedKeyframeStore),\n\t\t\t\tdocumentMetaCache: this.documentMetaCache.withScopedStore(scopedOperationStore),\n\t\t\t\tcollectionMembershipCache: this.collectionMembershipCache.withScopedIndex(scopedOperationIndex),\n\t\t\t\tdocumentLocks: {\n\t\t\t\t\tshared: async (ids) => {\n\t\t\t\t\t\tconst list = [...ids];\n\t\t\t\t\t\tawait acquirePurgeLocks(trx, list, \"shared\");\n\t\t\t\t\t\tfor (const id of list) sharedLocked.add(id);\n\t\t\t\t\t},\n\t\t\t\t\texclusive: (id) => acquirePurgeLocks(trx, [id], \"exclusive\"),\n\t\t\t\t\tpurged: async (ids) => {\n\t\t\t\t\t\tconst list = [...ids];\n\t\t\t\t\t\tconst found = await findPurged(trx, list);\n\t\t\t\t\t\tfor (const id of list) if (sharedLocked.has(id) && !found.has(id)) liveIds.add(id);\n\t\t\t\t\t\treturn found;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tpurger: new KyselyDocumentPurger(trx)\n\t\t\t});\n\t\t});\n\t}\n};\n//#endregion\n//#region src/utils/reshuffle.ts\nconst STRICT_ORDER_ACTION_TYPES = /* @__PURE__ */ new Set([\n\t\"CREATE_DOCUMENT\",\n\t\"DELETE_DOCUMENT\",\n\t\"UPGRADE_DOCUMENT\",\n\t\"ADD_RELATIONSHIP\",\n\t\"REMOVE_RELATIONSHIP\",\n\t\"UPDATE_RELATIONSHIP\",\n\t\"PURGE_DOCUMENT\",\n\t\"ADD_FOLDER\",\n\t\"UPDATE_FOLDER\",\n\t\"REMOVE_FOLDER\"\n]);\n/**\n* Reshuffles operations by timestamp, then applies deterministic tie-breaking.\n* Used for merging concurrent operations from different branches.\n*\n* For strict document-structure actions (e.g., CREATE_DOCUMENT/UPGRADE_DOCUMENT),\n* logical index (index - skip) is prioritized to preserve causal replay order.\n*\n* For other actions, action ID is prioritized to ensure a canonical cross-reactor order\n* for concurrent operations that may have diverged local indices due to prior reshuffles.\n* Logical index and operation ID are then used as deterministic tie-breakers.\n*\n* Example:\n* [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, 2:0, B3:0, B4:2, B5:0]\n* GC => [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, B4:2, B5:0]\n* Split => [0:0, 1:0] + [2:0, A3:0, A4:0, A5:0] + [B4:2, B5:0]\n* Reshuffle(6:4) => [6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n* merge => [0:0, 1:0, 6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n*/\nfunction reshuffleByTimestamp(startIndex, opsA, opsB) {\n\treturn [...opsA, ...opsB].sort((a, b) => {\n\t\tconst timestampDiff = new Date(a.timestampUtcMs).getTime() - new Date(b.timestampUtcMs).getTime();\n\t\tif (timestampDiff !== 0) return timestampDiff;\n\t\tconst rank = (op) => STRICT_ORDER_ACTION_TYPES.has(op.action?.type ?? \"\") ? 0 : 1;\n\t\tconst rankDiff = rank(a) - rank(b);\n\t\tif (rankDiff !== 0) return rankDiff;\n\t\tif (rank(a) === 0) {\n\t\t\tconst logicalIndexDiff = a.index - a.skip - (b.index - b.skip);\n\t\t\tif (logicalIndexDiff !== 0) return logicalIndexDiff;\n\t\t}\n\t\tconst actionIdDiff = (a.action?.id ?? \"\").localeCompare(b.action?.id ?? \"\");\n\t\tif (actionIdDiff !== 0) return actionIdDiff;\n\t\treturn a.id.localeCompare(b.id);\n\t}).map((op, i) => ({\n\t\t...op,\n\t\tindex: startIndex.index + i,\n\t\tskip: i === 0 ? startIndex.skip : 0\n\t}));\n}\n//#endregion\n//#region src/decision/merged-order.ts\n/** Identifies a stream within a walk. */\nfunction streamKey(query) {\n\treturn `${query.documentId}:${query.scope}:${query.branch}`;\n}\n/**\n* Orders two operations from different streams by position. Timestamp decides;\n* an equal timestamp puts an auth operation first, and otherwise falls to the\n* action id and then the operation id, so that two replicas holding the same\n* operations agree on the order whatever order they happen to store them in.\n*/\nfunction comparePositions(a, b) {\n\tconst aTime = Date.parse(a.operation.timestampUtcMs);\n\tconst bTime = Date.parse(b.operation.timestampUtcMs);\n\tif (aTime !== bTime) return aTime - bTime;\n\tif (a.streamKey === b.streamKey) return a.operation.index - b.operation.index;\n\tconst aAuth = a.scope === \"auth\";\n\tif (aAuth !== (b.scope === \"auth\")) return aAuth ? -1 : 1;\n\tconst actionIds = (a.operation.action.id ?? \"\").localeCompare(b.operation.action.id ?? \"\");\n\tif (actionIds !== 0) return actionIds;\n\treturn (a.operation.id ?? \"\").localeCompare(b.operation.id ?? \"\");\n}\n/**\n* Merges the read-set streams into one sequence by position. An operation's\n* place in the result is the bound a decision at that operation reads to: every\n* operation before it has been applied, and it has not.\n*/\nfunction mergeByPosition(streams) {\n\tconst merged = [];\n\tfor (const stream of streams) for (const operation of stream.operations) merged.push({\n\t\tstreamKey: stream.streamKey,\n\t\tscope: stream.scope,\n\t\toperation\n\t});\n\treturn merged.sort(comparePositions);\n}\n/**\n* The skip that retracts everything from `firstRetractedIndex` up to where the\n* re-appended operation lands. It spans the indexes rather than counting the\n* operations, because a stream with a gap in it makes those differ.\n*/\nfunction retractionSkip(nextIndex, firstRetractedIndex) {\n\treturn nextIndex - firstRetractedIndex;\n}\n//#endregion\n//#region src/decision/walk.ts\n/**\n* A single forward pass is only correct while a stream's effective operations\n* are ordered.\n*/\nfunction assertPositionOrder(streamKey, scope, operations) {\n\tfor (let i = 1; i < operations.length; i++) {\n\t\tconst previous = operations[i - 1];\n\t\tconst current = operations[i];\n\t\tif (comparePositions({\n\t\t\tstreamKey,\n\t\t\tscope,\n\t\t\toperation: previous\n\t\t}, {\n\t\t\tstreamKey,\n\t\t\tscope,\n\t\t\toperation: current\n\t\t}) > 0) throw new Error(`Stream ${streamKey} is out of position order: index ${previous.index} at ${previous.timestampUtcMs} precedes index ${current.index} at ${current.timestampUtcMs}`);\n\t}\n}\n/**\n* Visits every operation in the read-set once, in the order their positions\n* fall, and hands back the state each stream held just before it. That state is\n* what a decision at that operation reads.\n*\n* Skips are resolved first (i.e. this is performed on a garbage collected\n* stream), which means we can do a single forward pass.\n*\n* An operation that contributes no state, whether denied or holding a reducer\n* error, is visited but not applied (this matches the write cache's rebuild).\n*\n* The consumer sends back whether it refused the operation it was handed: a\n* refusal this pass produced must suppress it the same way a stored one does.\n*/\nfunction* walkByPosition(streams) {\n\tconst merged = mergeByPosition(streams.map((stream) => {\n\t\tconst operations = garbageCollect(sortOperations([...stream.operations]));\n\t\tassertPositionOrder(stream.streamKey, stream.scope, operations);\n\t\treturn {\n\t\t\tstreamKey: stream.streamKey,\n\t\t\tscope: stream.scope,\n\t\t\toperations\n\t\t};\n\t}));\n\tconst byKey = new Map(streams.map((stream) => [stream.streamKey, stream]));\n\tconst states = new Map(streams.map((stream) => [stream.streamKey, stream.document]));\n\tfor (const { streamKey, operation } of merged) {\n\t\tif ((yield {\n\t\t\tstreamKey,\n\t\t\toperation,\n\t\t\tstates: new Map(states)\n\t\t}) || operation.error !== void 0 || isDenied(operation)) continue;\n\t\tconst stream = byKey.get(streamKey);\n\t\tconst before = states.get(streamKey);\n\t\tif (before === void 0 || stream === void 0) throw new Error(`No state for stream ${streamKey}`);\n\t\tstates.set(streamKey, stream.apply(before, operation));\n\t}\n}\n//#endregion\n//#region src/decision/evaluation.ts\n/** The stream key for evaluated operations whose scope no projection reads. */\nconst EVALUATED_ONLY = \"evaluated\";\n/**\n* Whether any stream the model reads declares this operation's action type as\n* one that can change an evaluation.\n*/\nfunction isDecidingAction(operation, readSet) {\n\treturn readSet.some((stream) => stream.decidingActions.includes(operation.action.type));\n}\n/**\n* Who an operation acts as. A replayed operation is evaluated as its own signer,\n* so an address-scoped policy does not deny its own author's history.\n*/\nfunction subjectOf(operation) {\n\tconst signer = operation.action.context?.signer;\n\treturn {\n\t\taddress: signer?.user.address,\n\t\tkey: signer?.app.key\n\t};\n}\n/**\n* The model as the walk reached this operation: each static projection's value\n* is its own scope's state, and each derived projection's value maps document\n* id to that document's state, holding only the streams this replica walked. A\n* derived stream it does not hold stays out of the map, which fails closed.\n*/\nfunction modelAt(readSet, derivedNames, derived, states) {\n\tconst model = {};\n\tfor (const stream of readSet) {\n\t\tconst document = states.get(streamKey(stream.query));\n\t\tif (document === void 0) throw new Error(`No state walked for projection ${stream.name}`);\n\t\tmodel[stream.name] = document.state[stream.query.scope];\n\t}\n\tfor (const name of derivedNames) model[name] = {};\n\tfor (const entry of derived) {\n\t\tconst map = model[entry.name];\n\t\tconst document = states.get(streamKey(entry.query));\n\t\tif (document !== void 0) map[entry.query.documentId] = document.state[entry.query.scope];\n\t}\n\treturn model;\n}\n/**\n* Evaluates each operation at its own position and returns the refusals in an\n* array parallel to the operations, where undefined means allowed.\n*\n* A position is a timestamp, so an operation refused by a delete is one that\n* sorts after it, and the operations before it are left alone. That holds\n* whether the delete is already stored or is among the operations passed in.\n*/\nasync function evaluateByPosition(model, target, subject, stores, signal) {\n\tconst { scope, operations } = subject;\n\tconst { writeCache, operationStore } = stores;\n\tconst definition = model(target);\n\tconst readSet = staticReadSet(definition);\n\tconst derivedSet = derivedReadSet(definition);\n\tif (!definition.evaluatesScope(scope)) return operations.map(() => void 0);\n\tconst evaluating = new Set(operations.map((operation) => operation.id));\n\tconst creation = operations.find((operation) => operation.action.type === \"CREATE_DOCUMENT\" && operation.action.input.documentId === target.documentId);\n\tasync function stateBefore(query) {\n\t\ttry {\n\t\t\treturn await writeCache.getState(query.documentId, query.scope, query.branch, -1, signal);\n\t\t} catch (error) {\n\t\t\tif (creation !== void 0 && query.documentId === target.documentId && error instanceof DocumentNotFoundError && !(error instanceof DocumentPurgedError)) return createDocumentFromAction(creation.action);\n\t\t\tthrow error;\n\t\t}\n\t}\n\tconst readStreams = await Promise.all(readSet.map(async (stream) => ({\n\t\tstream,\n\t\toperations: (await operationStore.getSince(stream.query.documentId, stream.query.scope, stream.query.branch, -1, { actionTypes: stream.decidingActions }, void 0, signal)).results.filter((operation) => !evaluating.has(operation.id))\n\t})));\n\tconst decidingOperations = operations.filter((operation) => isDecidingAction(operation, readSet));\n\tif (readStreams.every((read) => read.operations.length === 0) && decidingOperations.length === 0) return operations.map(() => void 0);\n\tif (readStreams.length === 0) throw new Error(`Decision model for ${target.documentId} reads no stream whose query is known before it is built`);\n\tconst writtenProjection = readSet.find((stream) => stream.query.scope === scope);\n\tconst walked = [];\n\tconst histories = [];\n\tfor (const read of readStreams) {\n\t\tconst streamOperations = read.stream === writtenProjection ? [...read.operations, ...operations] : read.operations;\n\t\tconst before = await stateBefore(read.stream.query);\n\t\twalked.push({\n\t\t\tstreamKey: streamKey(read.stream.query),\n\t\t\tscope: read.stream.query.scope,\n\t\t\tdocument: before,\n\t\t\toperations: streamOperations,\n\t\t\tapply: read.stream.apply\n\t\t});\n\t\thistories.push({\n\t\t\tname: read.stream.name,\n\t\t\toperations: streamOperations\n\t\t});\n\t}\n\tlet evaluatedStateKey;\n\tif (writtenProjection !== void 0) evaluatedStateKey = streamKey(writtenProjection.query);\n\telse if (definition.foldEvaluatedScope !== void 0) {\n\t\tconst query = {\n\t\t\tdocumentId: target.documentId,\n\t\t\tscope,\n\t\t\tbranch: target.branch\n\t\t};\n\t\tconst storedOperations = (await operationStore.getSince(query.documentId, query.scope, query.branch, -1, void 0, void 0, signal)).results.filter((operation) => !evaluating.has(operation.id));\n\t\tconst before = await stateBefore(query);\n\t\tevaluatedStateKey = streamKey(query);\n\t\twalked.push({\n\t\t\tstreamKey: evaluatedStateKey,\n\t\t\tscope,\n\t\t\tdocument: before,\n\t\t\toperations: [...storedOperations, ...operations],\n\t\t\tapply: definition.foldEvaluatedScope\n\t\t});\n\t} else walked.push({\n\t\tstreamKey: EVALUATED_ONLY,\n\t\tscope,\n\t\tdocument: walked[0].document,\n\t\toperations,\n\t\tapply: (document) => document\n\t});\n\tconst derivedEntries = [];\n\tconst walkedKeys = new Set(walked.map((stream) => stream.streamKey));\n\tfor (const projection of derivedSet) {\n\t\tconst queries = projection.queryOverHistory?.(histories) ?? [];\n\t\tfor (const query of queries) {\n\t\t\tconst key = streamKey(query);\n\t\t\tif (walkedKeys.has(key)) continue;\n\t\t\tlet before;\n\t\t\ttry {\n\t\t\t\tbefore = await writeCache.getState(query.documentId, query.scope, query.branch, -1, signal);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof DocumentNotFoundError) continue;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst streamOperations = (await operationStore.getSince(query.documentId, query.scope, query.branch, -1, { actionTypes: projection.decidingActions }, void 0, signal)).results.filter((operation) => !evaluating.has(operation.id));\n\t\t\twalkedKeys.add(key);\n\t\t\twalked.push({\n\t\t\t\tstreamKey: key,\n\t\t\t\tscope: query.scope,\n\t\t\t\tdocument: before,\n\t\t\t\toperations: streamOperations,\n\t\t\t\tapply: projection.apply\n\t\t\t});\n\t\t\tderivedEntries.push({\n\t\t\t\tname: projection.name,\n\t\t\t\tquery\n\t\t\t});\n\t\t}\n\t}\n\tconst reasons = /* @__PURE__ */ new Map();\n\tconst walk = walkByPosition(walked);\n\tlet step = walk.next(false);\n\twhile (!step.done) {\n\t\tconst position = step.value;\n\t\tif (!evaluating.has(position.operation.id)) {\n\t\t\tstep = walk.next(false);\n\t\t\tcontinue;\n\t\t}\n\t\tconst evaluatedDocument = evaluatedStateKey === void 0 ? void 0 : position.states.get(evaluatedStateKey);\n\t\tconst scopeState = evaluatedDocument === void 0 ? void 0 : evaluatedDocument.state[scope];\n\t\tconst evaluation = definition.decide(modelAt(readSet, derivedSet.map((projection) => projection.name), derivedEntries, position.states), subjectOf(position.operation), {\n\t\t\tverb: \"execute\",\n\t\t\tscope: position.operation.action.scope,\n\t\t\toperation: position.operation.action.type\n\t\t}, {\n\t\t\tscopeState,\n\t\t\tactionInput: position.operation.action.input\n\t\t});\n\t\tconst denied = evaluation.decision === \"deny\";\n\t\treasons.set(position.operation.id, denied ? evaluation.reason : void 0);\n\t\tstep = walk.next(denied);\n\t}\n\treturn operations.map((operation) => reasons.get(operation.id));\n}\n//#endregion\n//#region src/executor/document-action-handler.ts\nvar DocumentActionHandler = class {\n\tregistry;\n\tlogger;\n\tdriveContainerTypes;\n\tfeatureFlags;\n\tdecisionModel;\n\tprotocolSupport;\n\tloggedUnregisteredProtocols = /* @__PURE__ */ new Set();\n\tconstructor(registry, logger, driveContainerTypes, featureFlags, decisionModel, protocolSupport) {\n\t\tthis.registry = registry;\n\t\tthis.logger = logger;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t\tthis.featureFlags = featureFlags;\n\t\tthis.decisionModel = decisionModel;\n\t\tthis.protocolSupport = protocolSupport;\n\t}\n\t/** Keys this reactor does not register are admitted: it cannot judge them. */\n\tunsupportedProtocol(documentId, protocolVersions) {\n\t\tfor (const [protocol, version] of Object.entries(protocolVersions ?? {})) {\n\t\t\tconst supported = this.protocolSupport[protocol];\n\t\t\tif (supported === void 0) {\n\t\t\t\tif (!this.loggedUnregisteredProtocols.has(protocol)) {\n\t\t\t\t\tthis.loggedUnregisteredProtocols.add(protocol);\n\t\t\t\t\tthis.logger.info(\"Admitting document @documentId with unregistered protocol @protocol @version\", documentId, protocol, version);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!supported.includes(version)) return new UnsupportedProtocolVersionError(documentId, protocol, version);\n\t\t}\n\t}\n\t/** Whether the write arrives with its evaluation already decided. */\n\talreadyEvaluated(executing) {\n\t\treturn this.featureFlags.documentDecisions && (executing.replayingAcceptedHistory || executing.evaluatedByPosition);\n\t}\n\tasync execute(write, executing) {\n\t\tconst { action } = write;\n\t\tif (write.deniedReason !== void 0) return this.writeDenied(write, executing);\n\t\tconst refusal = await this.refuseIfPolicyDenies(write, executing);\n\t\tif (refusal) return refusal;\n\t\tswitch (action.type) {\n\t\t\tcase \"CREATE_DOCUMENT\": return this.executeCreate(write, executing);\n\t\t\tcase \"DELETE_DOCUMENT\": return this.executeDelete(write, executing);\n\t\t\tcase \"UPGRADE_DOCUMENT\": return this.executeUpgrade(write, executing);\n\t\t\tcase \"ADD_RELATIONSHIP\": return this.executeAddRelationship(write, executing);\n\t\t\tcase \"REMOVE_RELATIONSHIP\": return this.executeRemoveRelationship(write, executing);\n\t\t\tcase \"UPDATE_RELATIONSHIP\": return this.executeUpdateRelationship(write, executing);\n\t\t\tcase \"PURGE_DOCUMENT\": return buildErrorResult(executing.job, new ReservedActionError(executing.job.documentId, action.type), executing.startTime);\n\t\t\tdefault: return buildErrorResult(executing.job, /* @__PURE__ */ new Error(`Unknown document action type: ${action.type}`), executing.startTime);\n\t\t}\n\t}\n\t/**\n\t* Refuses a document-scope write the policy denies, or undefined to proceed.\n\t* Without this an `execute`-on-`document` grant is unenforceable.\n\t*/\n\tasync refuseIfPolicyDenies(write, executing) {\n\t\tconst { action } = write;\n\t\tconst { job, startTime, stores, signal } = executing;\n\t\tif (!this.featureFlags.documentDecisions || !this.featureFlags.authEnforcement || this.alreadyEvaluated(executing) || !GATED_DOCUMENT_ACTIONS.has(action.type)) return;\n\t\tconst documentId = targetDocumentId(action, job.documentId);\n\t\tlet admission;\n\t\ttry {\n\t\t\tadmission = await decideAtHead(this.decisionModel, stores.writeCache, {\n\t\t\t\tdocumentId,\n\t\t\t\tbranch: job.branch\n\t\t\t}, {\n\t\t\t\taddress: action.context?.signer?.user.address,\n\t\t\t\tkey: action.context?.signer?.app.key\n\t\t\t}, {\n\t\t\t\tverb: \"execute\",\n\t\t\t\tscope: action.scope,\n\t\t\t\toperation: action.type\n\t\t\t}, signal, this.featureFlags.authConditions ? { actionInput: action.input } : void 0);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tif (admission.evaluation.decision === \"allow\") return;\n\t\treturn buildErrorResult(job, refusalError(admission.evaluation.reason, documentId, admission.deletedAtUtcIso, action), startTime);\n\t}\n\t/** A refused operation holds a position in the stream but changes nothing. */\n\tasync writeDenied(write, executing) {\n\t\tconst { action, skip, sourceRemote, deniedReason } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(job.documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tconst index = getNextIndexForScope(document, job.scope);\n\t\tlet standing = document;\n\t\tif (skip > 0) try {\n\t\t\tstanding = await stores.writeCache.getState(job.documentId, job.scope, job.branch, index - skip - 1, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet operation = createOperation(action, index, skip, {\n\t\t\tdocumentId: job.documentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\toperation.deniedReason = deniedReason;\n\t\toperation.hash = hashDocumentStateForScope(standing, job.scope);\n\t\tconst writeResult = await this.writeOperationToStore({\n\t\t\tdocumentId: job.documentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t}, operation, executing);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(standing, job.scope, operation.index);\n\t\tstanding.operations = {\n\t\t\t...standing.operations,\n\t\t\t[job.scope]: [...standing.operations[job.scope] ?? [], operation]\n\t\t};\n\t\texecuting.touchedStreams.add(job.documentId, job.scope, job.branch);\n\t\tstores.writeCache.putState(job.documentId, job.scope, job.branch, operation.index, standing, \"head\");\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: job.documentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(job.documentId, job.branch, {\n\t\t\tstate: standing.state.document,\n\t\t\tdocumentType: standing.header.documentType,\n\t\t\tprotocolVersions: standing.header.protocolVersions,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, job.documentId, standing.header.documentType, JSON.stringify({\n\t\t\theader: standing.header,\n\t\t\tdocument: standing.state.document\n\t\t}), startTime);\n\t}\n\tasync executeCreate(write, executing) {\n\t\tconst { action, skip, sourceRemote } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tif (job.scope !== \"document\") return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: /* @__PURE__ */ new Error(`CREATE_DOCUMENT must be in \"document\" scope, got \"${job.scope}\"`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst input = action.input;\n\t\tconst unsupported = this.unsupportedProtocol(input.documentId, input.protocolVersions);\n\t\tif (unsupported) return buildErrorResult(job, unsupported, startTime);\n\t\tconst document = createDocumentFromAction(action);\n\t\tlet operation = createOperation(action, 0, skip, {\n\t\t\tdocumentId: document.header.id,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst resultingStateObj = {\n\t\t\t...document.state,\n\t\t\theader: document.header\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore({\n\t\t\tdocumentId: document.header.id,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t}, operation, executing);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\texecuting.touchedStreams.add(document.header.id, job.scope, job.branch);\n\t\tstores.writeCache.putState(document.header.id, job.scope, job.branch, operation.index, document, \"head\");\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: document.header.id,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tif (this.driveContainerTypes.has(document.header.documentType)) {\n\t\t\tconst collectionId = DriveCollectionId.forDrive(document.header.id, job.branch).key;\n\t\t\tindexTxn.createCollection(collectionId);\n\t\t\tindexTxn.addToCollection(collectionId, document.header.id);\n\t\t}\n\t\tstores.documentMetaCache.putDocumentMeta(document.header.id, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tprotocolVersions: document.header.protocolVersions,\n\t\t\tdocumentScopeRevision: 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, document.header.id, document.header.documentType, resultingState, startTime);\n\t}\n\tasync executeDelete(write, executing) {\n\t\tconst { action, skip, sourceRemote } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tconst input = action.input;\n\t\tif (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error(\"DELETE_DOCUMENT action requires a documentId in input\"), startTime);\n\t\tconst documentId = input.documentId;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document before deletion: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tconst documentState = document.state.document;\n\t\tif (documentState.isDeleted && !this.alreadyEvaluated(executing)) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);\n\t\tlet operation = createOperation(action, getNextIndexForScope(document, job.scope), skip, {\n\t\t\tdocumentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tapplyDeleteDocumentAction$1(document, action);\n\t\tconst resultingStateObj = {\n\t\t\theader: document.header,\n\t\t\tdocument: document.state.document\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore({\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t}, operation, executing);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\texecuting.touchedStreams.add(documentId, job.scope, job.branch);\n\t\tstores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document, \"head\");\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(documentId, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tprotocolVersions: document.header.protocolVersions,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);\n\t}\n\tasync executeUpgrade(write, executing) {\n\t\tconst { action, skip, sourceRemote } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tconst input = action.input;\n\t\tif (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error(\"UPGRADE_DOCUMENT action requires a documentId in input\"), startTime);\n\t\tconst documentId = input.documentId;\n\t\tconst fromVersion = input.fromVersion;\n\t\tconst toVersion = input.toVersion;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tconst documentState = document.state.document;\n\t\tif (documentState.isDeleted && !this.alreadyEvaluated(executing)) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);\n\t\tif (fromVersion === toVersion && fromVersion > 0) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst arrivesDecided = executing.replayingAcceptedHistory || executing.evaluatedByPosition;\n\t\tif (fromVersion > 0 && !arrivesDecided) {\n\t\t\tconst stampedVersion = normalizeDocumentModelVersion(documentState.version);\n\t\t\tif (fromVersion !== stampedVersion) return buildErrorResult(job, new UpgradePreconditionFailedError(documentId, `fromVersion ${fromVersion} does not match the document's version ${stampedVersion}`), startTime);\n\t\t\tif (input.revision !== void 0) {\n\t\t\t\tlet actualRevisions;\n\t\t\t\ttry {\n\t\t\t\t\tactualRevisions = (await stores.operationStore.getRevisions(documentId, job.branch, signal)).revision;\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch revisions for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t\t\t}\n\t\t\t\tconst revisionScopes = /* @__PURE__ */ new Set([...Object.keys(input.revision), ...Object.keys(actualRevisions)]);\n\t\t\t\tfor (const revisionScope of revisionScopes) {\n\t\t\t\t\tconst snapshot = input.revision[revisionScope] ?? 0;\n\t\t\t\t\tconst actual = actualRevisions[revisionScope] ?? 0;\n\t\t\t\t\tif (snapshot !== actual) return buildErrorResult(job, new UpgradePreconditionFailedError(documentId, `revision snapshot for scope \"${revisionScope}\" is ${snapshot} but the document is at ${actual}`), startTime);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlet upgradePath;\n\t\tif (fromVersion > 0 && fromVersion < toVersion) try {\n\t\t\tupgradePath = this.registry.computeUpgradePath(document.header.documentType, fromVersion, toVersion);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tconst otherScopes = Object.keys(document.state).filter((scope) => scope !== job.scope);\n\t\tif (fromVersion > 0) for (const scope of otherScopes) {\n\t\t\tlet scopedDocument;\n\t\t\ttry {\n\t\t\t\tscopedDocument = await stores.writeCache.getState(documentId, scope, job.branch, void 0, signal);\n\t\t\t} catch (error) {\n\t\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch ${scope} scope for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t\t}\n\t\t\tdocument = {\n\t\t\t\t...document,\n\t\t\t\tstate: {\n\t\t\t\t\t...document.state,\n\t\t\t\t\t[scope]: scopedDocument.state[scope]\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t\tconst nextIndex = getNextIndexForScope(document, job.scope);\n\t\ttry {\n\t\t\tdocument = applyUpgradeDocumentAction$1(document, action, upgradePath);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet operation = createOperation(action, nextIndex, skip, {\n\t\t\tdocumentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst resultingStateObj = {\n\t\t\t...document.state,\n\t\t\theader: document.header\n\t\t};\n\t\tif (fromVersion > 0) resultingStateObj.__migrated = true;\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore({\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t}, operation, executing);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\texecuting.touchedStreams.add(documentId, job.scope, job.branch);\n\t\tstores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document, \"head\");\n\t\tfor (const scope of otherScopes) executing.postCommitInvalidations.push({\n\t\t\tdocumentId,\n\t\t\tscope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(documentId, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tprotocolVersions: document.header.protocolVersions,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);\n\t}\n\t/** A submitted write naming a purged target was refused at job start. */\n\tasync isTargetPurged(write, executing) {\n\t\tconst target = relationshipTarget(write.action);\n\t\tif (target === void 0 || !executing.purgeFence) return false;\n\t\treturn executing.purgeFence.isPurged(target);\n\t}\n\tasync executeAddRelationship(write, executing) {\n\t\tlet targetPurged;\n\t\ttry {\n\t\t\ttargetPurged = await this.isTargetPurged(write, executing);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(executing.job, error instanceof Error ? error : new Error(String(error)), executing.startTime);\n\t\t}\n\t\treturn this.withRelationshipAction(\"ADD_RELATIONSHIP\", write, executing, (input) => input.sourceId === input.targetId ? /* @__PURE__ */ new Error(\"ADD_RELATIONSHIP: sourceId and targetId cannot be the same (self-relationships not allowed)\") : null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {\n\t\t\tif (!targetPurged && this.driveContainerTypes.has(sourceDoc.header.documentType)) {\n\t\t\t\tconst collectionId = DriveCollectionId.forDrive(input.sourceId, j.branch).key;\n\t\t\t\ttxn.addToCollection(collectionId, input.targetId);\n\t\t\t\ts.collectionMembershipCache.invalidate(input.targetId);\n\t\t\t}\n\t\t});\n\t}\n\tasync executeRemoveRelationship(write, executing) {\n\t\tlet targetPurged;\n\t\ttry {\n\t\t\ttargetPurged = await this.isTargetPurged(write, executing);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(executing.job, error instanceof Error ? error : new Error(String(error)), executing.startTime);\n\t\t}\n\t\treturn this.withRelationshipAction(\"REMOVE_RELATIONSHIP\", write, executing, null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {\n\t\t\tif (!targetPurged && this.driveContainerTypes.has(sourceDoc.header.documentType)) {\n\t\t\t\tconst collectionId = DriveCollectionId.forDrive(input.sourceId, j.branch).key;\n\t\t\t\ttxn.removeFromCollection(collectionId, input.targetId);\n\t\t\t\ts.collectionMembershipCache.invalidate(input.targetId);\n\t\t\t}\n\t\t});\n\t}\n\texecuteUpdateRelationship(write, executing) {\n\t\treturn this.withRelationshipAction(\"UPDATE_RELATIONSHIP\", write, executing, null, null);\n\t}\n\tasync withRelationshipAction(actionTypeName, write, executing, preValidate, postWrite) {\n\t\tconst { action, skip, sourceRemote } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tif (job.scope !== \"document\") return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} must be in \"document\" scope, got \"${job.scope}\"`), startTime);\n\t\tconst input = action.input;\n\t\tif (!input.sourceId || !input.targetId || !input.relationshipType) return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} action requires sourceId, targetId, and relationshipType in input`), startTime);\n\t\tif (preValidate !== null) {\n\t\t\tconst validationError = preValidate(input);\n\t\t\tif (validationError !== null) return buildErrorResult(job, validationError, startTime);\n\t\t}\n\t\tlet sourceDoc;\n\t\ttry {\n\t\t\tsourceDoc = await stores.writeCache.getState(input.sourceId, \"document\", job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\tif (DocumentPurgedError.isError(error)) return buildErrorResult(job, error, startTime);\n\t\t\tif (DocumentNotFoundError.isError(error)) return buildErrorResult(job, new DocumentNotFoundError(input.sourceId, `${actionTypeName}: source document ${input.sourceId} not found`), startTime);\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName}: source document ${input.sourceId} not found: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tlet operation = createOperation(action, getNextIndexForScope(sourceDoc, job.scope), skip, {\n\t\t\tdocumentId: input.sourceId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst writeResult = await this.writeOperationToStore({\n\t\t\tdocumentId: input.sourceId,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t}, operation, executing);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tsourceDoc.header.lastModifiedAtUtcIso = operation.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString();\n\t\tupdateDocumentRevision(sourceDoc, job.scope, operation.index);\n\t\tsourceDoc.operations = {\n\t\t\t...sourceDoc.operations,\n\t\t\t[job.scope]: [...sourceDoc.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tconst scopeState = sourceDoc.state[job.scope];\n\t\tconst resultingStateObj = {\n\t\t\theader: structuredClone(sourceDoc.header),\n\t\t\t[job.scope]: scopeState === void 0 ? {} : structuredClone(scopeState)\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\texecuting.touchedStreams.add(input.sourceId, job.scope, job.branch);\n\t\texecuting.touchedStreams.add(input.targetId, job.scope, job.branch);\n\t\tstores.writeCache.putState(input.sourceId, job.scope, job.branch, operation.index, sourceDoc, \"head\");\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: input.sourceId,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tif (postWrite !== null) postWrite({\n\t\t\tindexTxn,\n\t\t\tstores,\n\t\t\tsourceDoc,\n\t\t\tinput,\n\t\t\tjob\n\t\t});\n\t\tstores.documentMetaCache.putDocumentMeta(input.sourceId, job.branch, {\n\t\t\tstate: sourceDoc.state.document,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tprotocolVersions: sourceDoc.header.protocolVersions,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, input.sourceId, sourceDoc.header.documentType, resultingState, startTime);\n\t}\n\tasync writeOperationToStore(target, operation, executing) {\n\t\tconst { documentId, documentType, scope, branch } = target;\n\t\tconst { job, startTime, stores, signal } = executing;\n\t\texecuting.touchedStreams.add(documentId, scope, branch);\n\t\tlet storedOperations;\n\t\ttry {\n\t\t\tstoredOperations = await stores.operationStore.apply(documentId, documentType, scope, branch, operation.index, (txn) => {\n\t\t\t\ttxn.addOperations(operation);\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Failed to write operation to IOperationStore (@documentId @scope @branch): @Operation @Error\", documentId, scope, branch, operation, error);\n\t\t\tstores.writeCache.invalidate(documentId, scope, branch);\n\t\t\tif (AppendConditionFailedError.isError(error)) for (const stream of error.condition.streams) stores.writeCache.invalidate(stream.documentId, stream.scope, stream.branch);\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${String(error)}`),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\treturn storedOperations;\n\t}\n};\n//#endregion\n//#region src/signer/passthrough-signer.ts\n/**\n* A no-op signer that returns empty values for all methods.\n* Used when signing is not required.\n*/\nvar PassthroughSigner = class {\n\tpublicKey = {};\n\tsign() {\n\t\treturn Promise.resolve(/* @__PURE__ */ new Uint8Array(0));\n\t}\n\tverify() {\n\t\treturn Promise.resolve();\n\t}\n\tsignAction() {\n\t\treturn Promise.resolve([\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\"\n\t\t]);\n\t}\n};\n//#endregion\n//#region src/signer/trust-policy.ts\n/**\n* The policy admission asks: the reactor's own key signing as its own user is\n* accepted, then the host's policy decides, else the default does. `own` is\n* read on every ask, since its user changes on login.\n*/\nfunction admissionTrustPolicy(own, authEnforcement, policy) {\n\treturn { authorizeSigner(signer, key, documentId) {\n\t\tconst identity = actionSignerIdentity(own);\n\t\tif (identity.app.key !== \"\" && key === identity.app.key) {\n\t\t\tif (sameUser(actionSignerIdentity(signer).user, identity.user)) return Promise.resolve(true);\n\t\t}\n\t\tif (policy) return policy.authorizeSigner(signer, key, documentId);\n\t\treturn Promise.resolve(!authEnforcement);\n\t} };\n}\nfunction sameUser(a, b) {\n\treturn a.address.toLowerCase() === b.address.toLowerCase() && a.networkId === b.networkId && a.chainId === b.chainId;\n}\n//#endregion\n//#region src/signer/did-key.ts\nconst DID_KEY_PREFIX = \"did:key:z\";\nconst P256_MULTICODEC = [128, 36];\nconst MAX_CACHED_KEYS = 1024;\nconst P = BigInt(\"0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff\");\nconst A = BigInt(\"0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc\");\nconst B = BigInt(\"0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b\");\n/** A did:key that is not a compressed P-256 public key. */\nvar MalformedDidKeyError = class extends Error {\n\tconstructor(did, detail) {\n\t\tsuper(`Malformed did:key ${did}: ${detail}`);\n\t\tthis.name = \"MalformedDidKeyError\";\n\t}\n};\nconst keyCache = /* @__PURE__ */ new Map();\n/** Cached per process: decompressing the point costs a BigInt modPow. */\nasync function importDidKey(did) {\n\tconst cached = keyCache.get(did);\n\tif (cached) {\n\t\tkeyCache.delete(did);\n\t\tkeyCache.set(did, cached);\n\t\treturn cached;\n\t}\n\tconst raw = decompressP256(compressedPointFromDid(did), did);\n\tconst key = await crypto.subtle.importKey(\"raw\", raw.buffer, {\n\t\tname: \"ECDSA\",\n\t\tnamedCurve: \"P-256\"\n\t}, false, [\"verify\"]);\n\tkeyCache.set(did, key);\n\tif (keyCache.size > MAX_CACHED_KEYS) {\n\t\tconst oldest = keyCache.keys().next().value;\n\t\tif (oldest !== void 0) keyCache.delete(oldest);\n\t}\n\treturn key;\n}\nfunction compressedPointFromDid(did) {\n\tif (!did.startsWith(DID_KEY_PREFIX)) throw new MalformedDidKeyError(did, \"not a base58btc did:key\");\n\tconst decoded = base58Decode(did.slice(9));\n\tif (!decoded || decoded.length !== 35) throw new MalformedDidKeyError(did, \"not a compressed P-256 key\");\n\tif (decoded[0] !== P256_MULTICODEC[0] || decoded[1] !== P256_MULTICODEC[1]) throw new MalformedDidKeyError(did, \"not a P-256 multicodec\");\n\treturn decoded.subarray(2);\n}\nfunction decompressP256(compressed, did) {\n\tconst prefix = compressed[0];\n\tif (prefix !== 2 && prefix !== 3) throw new MalformedDidKeyError(did, `compression prefix ${prefix}`);\n\tlet x = BigInt(0);\n\tfor (let i = 1; i < compressed.length; i++) x = x << BigInt(8) | BigInt(compressed[i]);\n\tif (x >= P) throw new MalformedDidKeyError(did, \"x outside the field\");\n\tconst ySquared = (modPow(x, BigInt(3), P) + A * x + B) % P;\n\tlet y = modPow(ySquared, (P + BigInt(1)) / BigInt(4), P);\n\tif (y * y % P !== ySquared) throw new MalformedDidKeyError(did, \"x is not on the curve\");\n\tif (y % BigInt(2) === BigInt(0) !== (prefix === 2)) y = P - y;\n\tconst uncompressed = /* @__PURE__ */ new Uint8Array(65);\n\tuncompressed[0] = 4;\n\tuncompressed.set(bigIntToBytes(x), 1);\n\tuncompressed.set(bigIntToBytes(y), 33);\n\treturn uncompressed;\n}\nfunction modPow(base, exp, mod) {\n\tlet result = BigInt(1);\n\tlet b = base % mod;\n\tlet e = exp;\n\twhile (e > BigInt(0)) {\n\t\tif (e & BigInt(1)) result = result * b % mod;\n\t\te >>= BigInt(1);\n\t\tb = b * b % mod;\n\t}\n\treturn result;\n}\nfunction bigIntToBytes(value) {\n\tconst bytes = /* @__PURE__ */ new Uint8Array(32);\n\tlet v = value;\n\tfor (let i = 31; i >= 0; i--) {\n\t\tbytes[i] = Number(v & BigInt(255));\n\t\tv >>= BigInt(8);\n\t}\n\treturn bytes;\n}\n//#endregion\n//#region src/signer/verify-action-signature.ts\nconst RENOWN_HASH_LENGTH = 44;\nconst SHARED_HASH_LENGTH = 28;\nconst HEX_SIGNATURE = /^(0x)?([0-9a-fA-F]{2})+$/;\n/**\n* Integrity only: identity binding and the live-id check sit with the caller.\n* `operation` is the incoming operation at load admission.\n*/\nasync function verifyActionSignature(action, target, path, operation) {\n\tconst policy = target.policy ?? \"legacy\";\n\tconst refusal = policyRefusal(action, policy);\n\tif (refusal) return refusal;\n\tconst shape = signerShape(action.context?.signer);\n\tif (shape.kind === \"unsigned\") return policy === \"v2-required\" ? refuse(\"unsigned\", \"UNSIGNED_REQUIRED\", `action ${action.id} is unsigned but ${target.documentId} requires v2 signatures`) : {\n\t\tok: true,\n\t\tscheme: \"unsigned\"\n\t};\n\tif (shape.kind === \"malformed\") return refuse(\"legacy-unknown\", \"MALFORMED_TUPLE\", `action ${action.id} ${shape.reason}`);\n\tconst { signer, tuple } = shape;\n\tconst scheme = schemeOf(tuple[2]);\n\tif (tuple[1] !== signer.app.key) return refuse(scheme, \"KEY_MISMATCH\", `action ${action.id} tuple key does not match signer.app.key`);\n\tif (scheme !== \"v2\" && policy === \"v2-required\") return refuse(scheme, \"SCHEME_BELOW_POLICY\", `action ${action.id} carries a legacy tuple but ${target.documentId} requires v2 signatures`);\n\tif (scheme === \"legacy-unknown\" && path === \"mutation\") return refuse(scheme, \"MALFORMED_TUPLE\", `action ${action.id} carries a hash of unknown length ${tuple[2].length}`);\n\tif (scheme === \"v2\") {\n\t\tconst refusal = await checkV2(action, tuple, target, operation);\n\t\tif (refusal) return refusal;\n\t} else if (path === \"mutation\") {\n\t\tif (await legacyHash(scheme, action, target) !== tuple[2]) return refuse(scheme, \"HASH_MISMATCH\", `action ${action.id} does not match the hash its signature covers`);\n\t}\n\treturn verifyEcdsa(tuple, scheme, action.id);\n}\n/** Refusals a document's policy makes before any tuple is read. */\nfunction policyRefusal(action, policy) {\n\tif (action.type !== \"CREATE_DOCUMENT\") return;\n\tconst scheme = schemeOfAction(action);\n\tconst input = action.input;\n\tconst documentId = input?.documentId ?? \"\";\n\tif (policy === \"legacy\") return isDerivedDocumentId(documentId) ? refuse(scheme, \"ID_MISMATCH\", `action ${action.id}: a legacy document cannot take the content-addressed id ${documentId}`) : void 0;\n\tconst expected = derivedCreateId(input);\n\tif (expected === documentId) return;\n\treturn refuse(scheme, \"ID_MISMATCH\", expected === void 0 ? `action ${action.id} creates v2-required ${documentId} without the header params its id is derived from` : `action ${action.id} creates v2-required ${documentId}, but its header params derive ${expected}`);\n}\nfunction derivedCreateId(input) {\n\tif (!input?.signing || !input.protocolVersions) return;\n\ttry {\n\t\treturn deriveDocumentId({\n\t\t\tdocumentType: input.model,\n\t\t\tcreatedAtUtcIso: input.signing.createdAtUtcIso,\n\t\t\tnonce: input.signing.nonce,\n\t\t\tprotocolVersions: input.protocolVersions\n\t\t});\n\t} catch {\n\t\treturn;\n\t}\n}\nfunction schemeOfAction(action) {\n\tconst shape = signerShape(action.context?.signer);\n\tif (shape.kind === \"unsigned\") return \"unsigned\";\n\treturn shape.kind === \"signed\" ? schemeOf(shape.tuple[2]) : \"legacy-unknown\";\n}\n/** Peers send arbitrary JSON, so nothing past `context` is assumed. */\nfunction signerShape(value) {\n\tif (value === void 0 || value === null) return { kind: \"unsigned\" };\n\tif (!isRecord(value)) return {\n\t\tkind: \"malformed\",\n\t\treason: \"has a signer that is not an object\"\n\t};\n\tconst { app, user, signatures } = value;\n\tif (app !== void 0 && app !== null && !isRecord(app)) return {\n\t\tkind: \"malformed\",\n\t\treason: \"has a signer.app that is not an object\"\n\t};\n\tconst key = isRecord(app) ? app.key : void 0;\n\tif (key !== void 0 && key !== null && typeof key !== \"string\") return {\n\t\tkind: \"malformed\",\n\t\treason: \"has a signer.app.key that is not a string\"\n\t};\n\tif (!key) return { kind: \"unsigned\" };\n\tif (!isRecord(user) || typeof user.address !== \"string\") return {\n\t\tkind: \"malformed\",\n\t\treason: \"has a signer without a user address\"\n\t};\n\tif (!Array.isArray(signatures)) return {\n\t\tkind: \"malformed\",\n\t\treason: \"has a signer whose signatures are not a list\"\n\t};\n\tconst tuple = signatures.at(-1);\n\tif (!isTuple(tuple)) return {\n\t\tkind: \"malformed\",\n\t\treason: signatures.length === 0 ? \"has a signer but no signatures\" : \"carries a malformed signature tuple\"\n\t};\n\treturn {\n\t\tkind: \"signed\",\n\t\tsigner: value,\n\t\ttuple\n\t};\n}\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nasync function checkV2(action, tuple, target, operation) {\n\tconst problem = v2TupleProblem(tuple);\n\tif (problem) return refuse(\"v2\", \"MALFORMED_TUPLE\", `action ${action.id}: ${problem}`);\n\tif (operation && !sameInstant(operation.timestampUtcMs, action.timestampUtcMs)) return refuse(\"v2\", \"TIMESTAMP_MISMATCH\", `action ${action.id} is stamped ${action.timestampUtcMs} but its operation ${operation.timestampUtcMs}`);\n\tlet expected;\n\ttry {\n\t\texpected = await hashActionV2(action, target, action.context.signer);\n\t} catch (error) {\n\t\treturn refuse(\"v2\", \"HASH_MISMATCH\", `action ${action.id} has no v2 hash: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\tif (expected !== tuple[2]) return refuse(\"v2\", \"HASH_MISMATCH\", `action ${action.id} does not match the hash its signature covers`);\n}\nfunction sameInstant(a, b) {\n\tconst left = Date.parse(a);\n\treturn !Number.isNaN(left) && left === Date.parse(b);\n}\nfunction schemeOf(hash) {\n\tif (isV2ActionHash(hash)) return \"v2\";\n\tif (hash.length === RENOWN_HASH_LENGTH) return \"legacy-renown\";\n\tif (hash.length === SHARED_HASH_LENGTH) return \"legacy-shared\";\n\treturn \"legacy-unknown\";\n}\nasync function legacyHash(scheme, action, target) {\n\tif (scheme === \"legacy-renown\") {\n\t\tconst payload = [\n\t\t\taction.scope,\n\t\t\taction.type,\n\t\t\tJSON.stringify(action.input)\n\t\t].join(\"\");\n\t\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(payload));\n\t\treturn bytesToBase64(new Uint8Array(digest));\n\t}\n\tconst signer = action.context.signer;\n\treturn buildOperationSignatureParams({\n\t\tdocumentId: target.documentId,\n\t\tsigner,\n\t\taction,\n\t\tpreviousStateHash: \"\"\n\t})[2];\n}\nasync function verifyEcdsa(tuple, scheme, actionId) {\n\tconst [timestamp, key, hash, prevStateHash, signatureHex] = tuple;\n\tif (!HEX_SIGNATURE.test(signatureHex)) return refuse(scheme, \"MALFORMED_TUPLE\", `action ${actionId} signature is not hex`);\n\tlet cryptoKey;\n\ttry {\n\t\tcryptoKey = await importDidKey(key);\n\t} catch (error) {\n\t\treturn refuse(scheme, \"MALFORMED_TUPLE\", `action ${actionId}: ${error instanceof Error ? error.message : String(error)}`);\n\t}\n\tconst message = buildOperationSignatureMessage([\n\t\ttimestamp,\n\t\tkey,\n\t\thash,\n\t\tprevStateHash\n\t]);\n\tlet valid;\n\ttry {\n\t\tvalid = await crypto.subtle.verify({\n\t\t\tname: \"ECDSA\",\n\t\t\thash: \"SHA-256\"\n\t\t}, cryptoKey, hexToBytes(signatureHex).buffer, message.buffer);\n\t} catch {\n\t\tvalid = false;\n\t}\n\tif (!valid) return refuse(scheme, \"BAD_SIGNATURE\", `action ${actionId} signature does not verify under its key`);\n\treturn {\n\t\tok: true,\n\t\tscheme\n\t};\n}\nfunction isTuple(value) {\n\treturn Array.isArray(value) && value.length === 5 && value.every((element) => typeof element === \"string\");\n}\nfunction refuse(scheme, code, reason) {\n\treturn {\n\t\tok: false,\n\t\tscheme,\n\t\tcode,\n\t\treason\n\t};\n}\nfunction hexToBytes(hex) {\n\tconst clean = hex.startsWith(\"0x\") ? hex.slice(2) : hex;\n\tconst bytes = new Uint8Array(clean.length / 2);\n\tfor (let i = 0; i < bytes.length; i++) bytes[i] = parseInt(clean.substring(i * 2, i * 2 + 2), 16);\n\treturn bytes;\n}\nfunction bytesToBase64(bytes) {\n\tlet binary = \"\";\n\tfor (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);\n\treturn btoa(binary);\n}\n//#endregion\n//#region src/executor/synthesized-signing.ts\n/** Submitted types whose stored action the reducer writes in their place. */\nconst SYNTHESIZING_TYPES = /* @__PURE__ */ new Set([\"UNDO\", \"REDO\"]);\n/**\n* The id of the action synthesized from `submittedId`. Derived, so the stored\n* operation answers for the submitted id at the live-id check.\n*/\nfunction synthesizedActionId(submittedId) {\n\treturn hashBrowser(`synthesized:${submittedId}`, \"sha1\", \"hex\").slice(0, 32);\n}\n/**\n* Whether `operation` stores an action the reducer made from `submitted`\n* rather than `submitted` itself or an operation already in `history`.\n*/\nfunction isSynthesized(submitted, operation, history) {\n\tif (!SYNTHESIZING_TYPES.has(submitted.type)) return false;\n\tconst id = operation.action.id;\n\tif (!id) return true;\n\tif (id === submitted.id) return false;\n\treturn !history.some((existing) => existing.action.id === id);\n}\n/**\n* Signs the synthesized action of `operation` in place as `signer`, under the\n* id {@link synthesizedActionId} derives from the submitted one. A REDO's\n* rebuilt action has no timestamp, so it takes the submitted one; the\n* operation timestamp is set to the action's, which a peer requires of a v2\n* tuple.\n*/\nasync function signSynthesized(operation, submitted, target, signer, signal) {\n\tconst synthesized = operation.action;\n\tconst id = synthesizedActionId(submitted.id);\n\tconst timestampUtcMs = operation.timestampUtcMs || synthesized.timestampUtcMs || submitted.timestampUtcMs;\n\tconst action = {\n\t\tid,\n\t\ttimestampUtcMs,\n\t\ttype: synthesized.type,\n\t\tinput: synthesized.input,\n\t\tscope: synthesized.scope\n\t};\n\tconst signature = await signer.signAction(action, {\n\t\tdocumentId: target.documentId,\n\t\tbranch: target.branch\n\t}, signal);\n\toperation.action = {\n\t\t...action,\n\t\tcontext: { signer: {\n\t\t\t...actionSignerIdentity(signer),\n\t\t\tsignatures: [signature]\n\t\t} }\n\t};\n\toperation.id = deriveOperationId(target.documentId, target.scope, target.branch, id);\n\toperation.timestampUtcMs = timestampUtcMs;\n}\n//#endregion\n//#region src/executor/signature-admission.ts\nconst DEFAULT_TRUST_TIMEOUT_MS = 1e4;\n/** Runs once per write, when this reactor first stores it; never on re-appends. */\nvar SignatureAdmission = class {\n\tmode;\n\tlogger;\n\teventBus;\n\tpolicySource;\n\ttrustPolicy;\n\ttrustTimeoutMs;\n\tconstructor(mode, logger, eventBus, policySource = \"meta\", trust = {\n\t\tauthEnforcement: false,\n\t\ttimeoutMs: DEFAULT_TRUST_TIMEOUT_MS\n\t}) {\n\t\tthis.mode = mode;\n\t\tthis.logger = logger;\n\t\tthis.eventBus = eventBus;\n\t\tthis.policySource = policySource;\n\t\tthis.trustPolicy = admissionTrustPolicy(trust.signer ?? new PassthroughSigner(), trust.authEnforcement, trust.policy);\n\t\tthis.trustTimeoutMs = trust.timeoutMs;\n\t}\n\t/** The first refusal of a mutation's submitted actions, when enforcing. */\n\tasync admitMutation(job, stores, signal) {\n\t\tconst { operationStore } = stores;\n\t\tconst candidates = job.actions.map((action) => candidate(action, mutationStream(action, job)));\n\t\tconst live = await this.liveOperationIds(candidates, operationStore, signal);\n\t\tconst committed = await this.storedAsSubmitted(candidates, live, isRetry(job), operationStore, signal);\n\t\tawait resolvePolicies(candidates, job.actions, (documentId, branch) => storedPolicy(stores, this.policySource, documentId, branch, signal));\n\t\tconst submitted = /* @__PURE__ */ new Set();\n\t\tfor (const entry of candidates) {\n\t\t\tif (committed.has(entry)) continue;\n\t\t\tconst verdict = await this.verdict(entry, live, submitted, \"mutation\", signal);\n\t\t\tsubmitted.add(entry.opId);\n\t\t\tif (verdict.ok) continue;\n\t\t\tconst refusal = this.record(job, entry, verdict, \"mutation\");\n\t\t\tif (refusal) return {\n\t\t\t\tkind: \"refused\",\n\t\t\t\terror: refusal\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tkind: \"admitted\",\n\t\t\tcommitted: [...committed.values()]\n\t\t};\n\t}\n\t/** The incoming operations a load drops, empty unless enforcing. */\n\tasync admitLoad(job, operations, stores, signal) {\n\t\tconst { operationStore } = stores;\n\t\tconst stream = {\n\t\t\tdocumentId: job.documentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t};\n\t\tconst candidates = operations.map((operation) => ({\n\t\t\t...candidate(operation.action, stream),\n\t\t\toperation\n\t\t}));\n\t\tconst live = await this.liveOperationIds(candidates, operationStore, signal);\n\t\tconst redelivered = await this.redelivered(candidates, live, operationStore, signal);\n\t\tawait resolvePolicies(candidates, job.operations.map((operation) => operation.action), (documentId, branch) => storedPolicy(stores, this.policySource, documentId, branch, signal));\n\t\tconst dropped = /* @__PURE__ */ new Set();\n\t\tfor (let i = 0; i < candidates.length; i++) {\n\t\t\tconst verdict = await this.verdict(candidates[i], live, void 0, \"load\", signal, redelivered.has(candidates[i]));\n\t\t\tif (verdict.ok) continue;\n\t\t\tif (this.record(job, candidates[i], verdict, \"load\")) dropped.add(operations[i]);\n\t\t}\n\t\treturn dropped;\n\t}\n\t/** A marker is held to v2 and enforced whatever the policy and mode. */\n\tasync admitMarker(job, marker, signal) {\n\t\tconst entry = {\n\t\t\t...candidate(marker.action, {\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tscope: \"document\",\n\t\t\t\tbranch: job.branch\n\t\t\t}),\n\t\t\toperation: marker,\n\t\t\tpolicy: \"v2-required\"\n\t\t};\n\t\tconst verdict = await this.verdict(entry, /* @__PURE__ */ new Set(), void 0, \"load\", signal);\n\t\tif (verdict.ok) return;\n\t\treturn this.record(job, entry, verdict, \"load\", true);\n\t}\n\tasync verdict(entry, live, submitted, path, signal, known = false) {\n\t\tconst verdict = await verifyActionSignature(entry.action, {\n\t\t\tdocumentId: entry.stream.documentId,\n\t\t\tbranch: entry.stream.branch,\n\t\t\tpolicy: entry.policy\n\t\t}, path, entry.operation);\n\t\tif (!verdict.ok) return verdict;\n\t\tif (!known && (isLive(entry, live) || submitted?.has(entry.opId))) return {\n\t\t\tok: false,\n\t\t\tscheme: verdict.scheme,\n\t\t\tcode: \"DUPLICATE_ACTION\",\n\t\t\treason: `action ${entry.action.id} is already in the stream`\n\t\t};\n\t\tif (verdict.scheme === \"unsigned\") {\n\t\t\tconst address = entry.action.context?.signer?.user?.address;\n\t\t\treturn address ? {\n\t\t\t\tok: false,\n\t\t\t\tscheme: \"unsigned\",\n\t\t\t\tcode: \"UNSIGNED_IDENTITY\",\n\t\t\t\treason: `action ${entry.action.id} is unsigned but claims to act as ${address}`\n\t\t\t} : verdict;\n\t\t}\n\t\tif (known) return verdict;\n\t\tconst signer = entry.action.context.signer;\n\t\tif (!await this.authorize(signer, entry.stream.documentId, signal)) return {\n\t\t\tok: false,\n\t\t\tscheme: verdict.scheme,\n\t\t\tcode: \"SIGNER_UNAUTHORIZED\",\n\t\t\treason: `action ${entry.action.id}: key ${signer.app.key} may not sign as ${signer.user.address}`\n\t\t};\n\t\treturn verdict;\n\t}\n\t/** Throws when the policy does, times out or the job is aborted. */\n\tasync authorize(signer, documentId, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tlet timer;\n\t\tlet onAbort;\n\t\tconst stop = new Promise((_, reject) => {\n\t\t\ttimer = setTimeout(() => {\n\t\t\t\treject(/* @__PURE__ */ new Error(`signature trust policy did not answer for ${signer.app.key} within ${this.trustTimeoutMs}ms`));\n\t\t\t}, this.trustTimeoutMs);\n\t\t\tif (signal) {\n\t\t\t\tonAbort = () => reject(signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason)));\n\t\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t}\n\t\t});\n\t\ttry {\n\t\t\treturn await Promise.race([this.trustPolicy.authorizeSigner(signer, signer.app.key, documentId), stop]);\n\t\t} finally {\n\t\t\tclearTimeout(timer);\n\t\t\tif (onAbort) signal?.removeEventListener(\"abort\", onAbort);\n\t\t}\n\t}\n\t/**\n\t* The live candidates stored exactly as submitted and still standing: one\n\t* an undo or a reshuffle has since superseded is refused, not re-emitted with\n\t* the state it once produced. A synthesized operation\n\t* holds another action, so it cannot be compared; only a retry, whose first\n\t* attempt this job was, takes it as committed.\n\t*/\n\tasync storedAsSubmitted(candidates, live, retry, operationStore, signal) {\n\t\tconst committed = /* @__PURE__ */ new Map();\n\t\tconst toCompare = [];\n\t\tfor (const entry of candidates) if (entry.synthesizedOpId && live.has(entry.synthesizedOpId)) {\n\t\t\tif (retry) committed.set(entry, committedWrite(entry, entry.synthesizedOpId));\n\t\t} else if (live.has(entry.opId)) toCompare.push(entry);\n\t\tfor (const [stream, entries] of byStream(toCompare)) {\n\t\t\tconst stored = await operationStore.getOperationsByIds(stream.documentId, stream.scope, stream.branch, entries.map((entry) => entry.opId), signal);\n\t\t\tconst byId = new Map(stored.map((operation) => [operation.id, operation]));\n\t\t\tconst matching = entries.filter((entry) => {\n\t\t\t\tconst operation = byId.get(entry.opId);\n\t\t\t\treturn operation && sameContent(operation.action, entry.action);\n\t\t\t});\n\t\t\tif (matching.length === 0) continue;\n\t\t\tconst later = await operationStore.getSince(stream.documentId, stream.scope, stream.branch, Math.min(...matching.map((entry) => byId.get(entry.opId).index)), void 0, void 0, signal);\n\t\t\tfor (const entry of matching) if (!isSuperseded(byId.get(entry.opId), later.results)) committed.set(entry, committedWrite(entry, entry.opId));\n\t\t}\n\t\treturn committed;\n\t}\n\t/**\n\t* The load candidates stored exactly as they arrive, timestamp included: a\n\t* peer re-sending what this stream holds, not a replay of its action.\n\t*/\n\tasync redelivered(candidates, live, operationStore, signal) {\n\t\tconst found = /* @__PURE__ */ new Set();\n\t\tconst toCompare = candidates.filter((entry) => live.has(entry.opId) && !(entry.synthesizedOpId && live.has(entry.synthesizedOpId)));\n\t\tfor (const [stream, entries] of byStream(toCompare)) {\n\t\t\tconst stored = await operationStore.getOperationsByIds(stream.documentId, stream.scope, stream.branch, entries.map((entry) => entry.opId), signal);\n\t\t\tfor (const entry of entries) if (stored.some((operation) => operation.id === entry.opId && Date.parse(operation.timestampUtcMs) === Date.parse(entry.operation?.timestampUtcMs ?? \"\") && sameContent(operation.action, entry.action))) found.add(entry);\n\t\t}\n\t\treturn found;\n\t}\n\tasync liveOperationIds(candidates, operationStore, signal) {\n\t\tconst live = /* @__PURE__ */ new Set();\n\t\tfor (const [stream, entries] of byStream(candidates)) {\n\t\t\tconst found = await operationStore.findOperationIds(stream.documentId, stream.scope, stream.branch, entries.flatMap((entry) => entry.synthesizedOpId ? [entry.opId, entry.synthesizedOpId] : [entry.opId]), signal);\n\t\t\tfor (const opId of found) live.add(opId);\n\t\t}\n\t\treturn live;\n\t}\n\t/** Logs and counts a refusal; returns the error only when enforcing. */\n\trecord(job, entry, refusal, path, enforced = this.mode === \"enforce\") {\n\t\tconst event = {\n\t\t\tjobId: job.id,\n\t\t\tdocumentId: entry.stream.documentId,\n\t\t\tscope: entry.stream.scope,\n\t\t\tbranch: entry.stream.branch,\n\t\t\tactionId: entry.action.id,\n\t\t\tcode: refusal.code,\n\t\t\tscheme: refusal.scheme,\n\t\t\tpath,\n\t\t\tenforced,\n\t\t\treason: refusal.reason\n\t\t};\n\t\tthis.logger.warn(enforced ? \"Signature refused: @Refusal\" : \"Signature refusal logged, write admitted: @Refusal\", event);\n\t\tthis.eventBus.emit(ReactorEventTypes.SIGNATURE_REFUSED, event).catch((error) => {\n\t\t\tthis.logger.error(\"Failed to emit SIGNATURE_REFUSED: @Error\", error);\n\t\t});\n\t\treturn enforced ? new InvalidSignatureError(entry.stream.documentId, refusal.code, refusal.reason) : void 0;\n\t}\n};\n/**\n* A CREATE_DOCUMENT is verified under its own input. Anything else takes the\n* stored document's policy, or, for a document this job creates, that CREATE's.\n*/\nasync function resolvePolicies(candidates, jobActions, stored) {\n\tconst resolved = /* @__PURE__ */ new Map();\n\tfor (const entry of candidates) {\n\t\tif (entry.action.type === \"CREATE_DOCUMENT\") {\n\t\t\tentry.policy = createPolicy(entry.action);\n\t\t\tcontinue;\n\t\t}\n\t\tconst { documentId, branch } = entry.stream;\n\t\tconst key = `${documentId}\\u0000${branch}`;\n\t\tlet policy = resolved.get(key);\n\t\tif (policy === void 0) {\n\t\t\tpolicy = await stored(documentId, branch) ?? createdPolicy(jobActions, documentId) ?? \"legacy\";\n\t\t\tresolved.set(key, policy);\n\t\t}\n\t\tentry.policy = policy;\n\t}\n}\nasync function storedPolicy(stores, source, documentId, branch, signal) {\n\ttry {\n\t\tif (source === \"write-cache\") {\n\t\t\tconst document = await stores.writeCache.getState(documentId, \"document\", branch, void 0, signal);\n\t\t\treturn signaturePolicyOf(document.header);\n\t\t}\n\t\tconst meta = await stores.documentMetaCache.getDocumentMeta(documentId, branch, signal);\n\t\treturn signaturePolicyOf(meta.protocolVersions);\n\t} catch (error) {\n\t\tif (DocumentNotFoundError.isError(error)) return;\n\t\tthrow error;\n\t}\n}\nfunction createdPolicy(actions, documentId) {\n\tconst create = actions.find((action) => action.type === \"CREATE_DOCUMENT\" && action.input?.documentId === documentId);\n\treturn create ? createPolicy(create) : void 0;\n}\nfunction createPolicy(action) {\n\treturn signaturePolicyOf(action.input);\n}\nfunction candidate(action, stream) {\n\tconst opId = (actionId) => deriveOperationId(stream.documentId, stream.scope, stream.branch, actionId);\n\treturn {\n\t\taction,\n\t\tstream,\n\t\topId: opId(action.id),\n\t\tsynthesizedOpId: SYNTHESIZING_TYPES.has(action.type) ? opId(synthesizedActionId(action.id)) : void 0\n\t};\n}\nfunction isLive(entry, live) {\n\treturn live.has(entry.opId) || entry.synthesizedOpId !== void 0 && live.has(entry.synthesizedOpId);\n}\nfunction mutationStream(action, job) {\n\treturn {\n\t\t...actionSigningTarget(action, job.documentId, job.branch),\n\t\tscope: job.scope\n\t};\n}\nfunction byStream(candidates) {\n\tconst groups = /* @__PURE__ */ new Map();\n\tfor (const entry of candidates) {\n\t\tconst key = `${entry.stream.documentId}\\u0000${entry.stream.scope}\\u0000${entry.stream.branch}`;\n\t\tconst group = groups.get(key) ?? [entry.stream, []];\n\t\tgroup[1].push(entry);\n\t\tgroups.set(key, group);\n\t}\n\treturn [...groups.values()];\n}\nfunction isRetry(job) {\n\treturn job.errorHistory.length > 0 || (job.retryCount ?? 0) > 0;\n}\nfunction committedWrite(entry, opId) {\n\treturn {\n\t\t...entry.stream,\n\t\tactionId: entry.action.id,\n\t\topId\n\t};\n}\nfunction isSuperseded(operation, later) {\n\treturn later.some((next) => next.index > operation.index && next.skip > 0 && next.index - next.skip <= operation.index);\n}\nfunction sameContent(stored, submitted) {\n\ttry {\n\t\treturn canonicalJson(stored) === canonicalJson(submitted);\n\t} catch {\n\t\treturn false;\n\t}\n}\n//#endregion\n//#region src/executor/simple-job-executor.ts\nconst MAX_SKIP_THRESHOLD = 1e3;\nconst ISO_TIMESTAMP_REGEX = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$/;\nfunction isValidISOTimestamp(value) {\n\tif (!ISO_TIMESTAMP_REGEX.test(value)) return false;\n\treturn !isNaN(new Date(value).getTime());\n}\n/**\n* Carries a failed job out of the execution scope so its transaction rolls\n* back. A scope callback that returns commits, whatever result it returns, so\n* a returned failure would leave the writes the job made before it failed\n* standing. Never escapes executeJob: the failure goes back to being a\n* returned JobResult there, which is what the queue, the worker protocol and\n* every test expect a failed job to look like.\n*/\n/** The ids of a purge job's request, which a drive purge may precede. */\nfunction purgeRequestDocumentIds(job) {\n\tconst ids = job.meta.purgeRequestDocumentIds;\n\treturn Array.isArray(ids) ? ids.filter((id) => typeof id === \"string\") : [];\n}\nconst MARKER_INPUT_KEYS = /* @__PURE__ */ new Set([\n\t\"documentId\",\n\t\"documentType\",\n\t\"purgedAtUtcIso\",\n\t\"requestId\"\n]);\n/** A peer's marker must name this job's id on main and carry nothing else. */\nfunction malformedMarker(job) {\n\tconst action = job.operations.find((operation) => isPurgeMarker(operation))?.action;\n\tconst input = action?.input;\n\tconst refuse = (reason) => new InvalidSignatureError(job.documentId, \"ID_MISMATCH\", `marker ${action?.id ?? \"?\"} ${reason}`);\n\tif (typeof input !== \"object\" || input === null) return refuse(\"carries no input\");\n\tconst extra = Object.keys(input).filter((key) => !MARKER_INPUT_KEYS.has(key));\n\tif (extra.length > 0) return refuse(`carries unexpected input ${extra.join(\", \")}`);\n\tfor (const key of MARKER_INPUT_KEYS) if (typeof input[key] !== \"string\" || input[key] === \"\") return refuse(`input.${key} is not a non-empty string`);\n\tconst purgedAt = Date.parse(input.purgedAtUtcIso);\n\tif (Number.isNaN(purgedAt) || new Date(purgedAt).toISOString() !== input.purgedAtUtcIso) return refuse(\"input.purgedAtUtcIso is not an ISO timestamp\");\n\tif (input.documentId !== job.documentId || job.branch !== \"main\" || action?.scope !== \"document\") return refuse(`does not purge ${job.documentId} on document/main`);\n}\nvar JobRollbackSignal = class extends Error {\n\tresult;\n\tconstructor(result) {\n\t\tsuper(\"job rolled back\");\n\t\tthis.result = result;\n\t\tthis.name = \"JobRollbackSignal\";\n\t}\n};\nvar SimpleJobExecutor = class {\n\tlogger;\n\tregistry;\n\toperationStore;\n\teventBus;\n\twriteCache;\n\toperationIndex;\n\tdocumentMetaCache;\n\tcollectionMembershipCache;\n\tdriveContainerTypes;\n\tconfig;\n\tfeatureFlags;\n\tdecisionModel;\n\tsignatureAdmission;\n\tdocumentActionHandler;\n\texecutionScope;\n\tsigner;\n\t/**\n\t* `signer` signs the operations the reducer synthesizes; unsigned if omitted.\n\t* `trustPolicy` decides which keys may sign as which users at admission.\n\t*/\n\tconstructor(logger, registry, operationStore, eventBus, writeCache, operationIndex, documentMetaCache, collectionMembershipCache, driveContainerTypes, config, executionScope, signer, trustPolicy) {\n\t\tthis.logger = logger;\n\t\tthis.registry = registry;\n\t\tthis.operationStore = operationStore;\n\t\tthis.eventBus = eventBus;\n\t\tthis.writeCache = writeCache;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t\tthis.signer = signer ?? new PassthroughSigner();\n\t\tthis.featureFlags = resolveFeatureFlags(config.featureFlags);\n\t\tthis.config = {\n\t\t\tfeatureFlags: config.featureFlags ?? {},\n\t\t\tmaxSkipThreshold: config.maxSkipThreshold ?? MAX_SKIP_THRESHOLD,\n\t\t\tmaxConcurrency: config.maxConcurrency ?? 1,\n\t\t\tjobTimeoutMs: config.jobTimeoutMs ?? 3e4,\n\t\t\tdeferredJobTtlMs: config.deferredJobTtlMs ?? 3e4,\n\t\t\tretryBaseDelayMs: config.retryBaseDelayMs ?? 100,\n\t\t\tretryMaxDelayMs: config.retryMaxDelayMs ?? 5e3,\n\t\t\tyieldDeadlineMs: config.yieldDeadlineMs ?? 50,\n\t\t\tbatchApplies: config.batchApplies ?? true,\n\t\t\tsignatureVerification: config.signatureVerification ?? \"enforce\",\n\t\t\tprotocolSupport: config.protocolSupport ?? localSupports(PEER_CAPABILITIES, this.featureFlags).protocols,\n\t\t\tmaxPurgeOperations: config.maxPurgeOperations ?? 2e5\n\t\t};\n\t\tthis.decisionModel = selectDecisionModel(this.featureFlags, registry);\n\t\tthis.signatureAdmission = new SignatureAdmission(this.config.signatureVerification, logger, eventBus, this.featureFlags.documentDecisions ? \"write-cache\" : \"meta\", {\n\t\t\tsigner: this.signer,\n\t\t\tauthEnforcement: this.featureFlags.authEnforcement,\n\t\t\tpolicy: trustPolicy,\n\t\t\ttimeoutMs: Math.min(DEFAULT_TRUST_TIMEOUT_MS, this.config.jobTimeoutMs / 2)\n\t\t});\n\t\tthis.documentActionHandler = new DocumentActionHandler(registry, logger, driveContainerTypes, this.featureFlags, this.decisionModel, this.config.protocolSupport);\n\t\tthis.executionScope = executionScope ?? new DefaultExecutionScope(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache);\n\t}\n\t/**\n\t* Execute a single job by applying all its actions through the appropriate reducers.\n\t* Actions are processed sequentially in order.\n\t*\n\t* The whole job runs inside one execution scope, and a scope callback that\n\t* returns commits. A failed job must therefore leave the scope by throwing,\n\t* or the writes it made before it failed would be durable: JobRollbackSignal\n\t* carries the failure out through the transaction and this method turns it\n\t* back into the returned JobResult every caller expects. A job either fully\n\t* applies or leaves nothing durable behind.\n\t*\n\t* Durable is the whole of the guarantee. The caches are shared with the\n\t* copies the scope hands the job, so a failed job's writes sit in them from\n\t* the moment it makes them until the eviction below, and a concurrent read\n\t* in that window sees a write that is never going to commit. The window is\n\t* not new -- it has always been there for a job that failed by throwing --\n\t* but nothing here closes it, and a caller that needs to know a write is\n\t* real has the job status to ask.\n\t*/\n\tasync executeJob(job, signal) {\n\t\tconst startTime = Date.now();\n\t\tconst touchedStreams = new TouchedStreams();\n\t\tconst postCommitInvalidations = [];\n\t\tconst postCommitMembershipInvalidations = [];\n\t\tconst postCommitMetaInvalidations = [];\n\t\tlet outcome;\n\t\ttry {\n\t\t\toutcome = await this.executionScope.run(async (stores) => {\n\t\t\t\tconst scoped = await this.executeInScope({\n\t\t\t\t\tjob,\n\t\t\t\t\tstartTime,\n\t\t\t\t\tstores,\n\t\t\t\t\tsignal,\n\t\t\t\t\ttouchedStreams,\n\t\t\t\t\tpostCommitInvalidations,\n\t\t\t\t\tpostCommitMembershipInvalidations,\n\t\t\t\t\tpostCommitMetaInvalidations\n\t\t\t\t});\n\t\t\t\tif (!scoped.result.success) throw new JobRollbackSignal(scoped.result);\n\t\t\t\treturn scoped;\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tthis.evictTouchedStreams(touchedStreams);\n\t\t\tif (error instanceof JobRollbackSignal) return error.result;\n\t\t\tthrow error;\n\t\t}\n\t\tfor (const entry of postCommitInvalidations) this.writeCache.invalidate(entry.documentId, entry.scope, entry.branch);\n\t\tfor (const documentId of postCommitMembershipInvalidations) this.collectionMembershipCache.invalidate(documentId);\n\t\tfor (const documentId of postCommitMetaInvalidations) this.documentMetaCache.invalidate(documentId);\n\t\tconst { pendingEvent } = outcome;\n\t\tif (pendingEvent) this.eventBus.emit(ReactorEventTypes.JOB_WRITE_READY, pendingEvent).catch((error) => {\n\t\t\tthis.logger.error(\"Failed to emit JOB_WRITE_READY event: @Event : @Error\", pendingEvent, error);\n\t\t});\n\t\treturn outcome.result;\n\t}\n\t/**\n\t* The body of a job, run inside the execution scope's transaction.\n\t*\n\t* The stores and caches it works through are the copies scoped to that\n\t* transaction, so nothing it does is durable until the scope commits. The\n\t* write-ready event is handed back rather than emitted, because a job that\n\t* has not committed yet has nothing to announce.\n\t*/\n\tasync executeInScope(params) {\n\t\tconst { job, startTime, stores: scopeStores, signal, touchedStreams, postCommitInvalidations, postCommitMembershipInvalidations } = params;\n\t\tlet pendingEvent;\n\t\tif (job.kind === \"mutation\") {\n\t\t\tconst reserved = job.actions.find((action) => isPurgeMarker(action));\n\t\t\tif (reserved) return { result: buildErrorResult(job, new ReservedActionError(job.documentId, reserved.type), startTime) };\n\t\t}\n\t\tif (job.kind === \"purge\" || job.kind === \"load\" && job.operations.some((op) => isPurgeMarker(op))) return this.executePurge(params);\n\t\tconst lockedIds = jobWriteIds(job);\n\t\tconst lockFailure = (error) => ({ result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) });\n\t\ttry {\n\t\t\tawait scopeStores.documentLocks.shared(lockedIds);\n\t\t} catch (error) {\n\t\t\treturn lockFailure(error);\n\t\t}\n\t\tlet purged;\n\t\ttry {\n\t\t\tpurged = await scopeStores.documentLocks.purged(lockedIds);\n\t\t} catch (error) {\n\t\t\treturn lockFailure(error);\n\t\t}\n\t\tconst purgedRefusal = this.purgedRefusal(job, purged);\n\t\tif (purgedRefusal) return { result: buildErrorResult(job, purgedRefusal, startTime) };\n\t\tconst purgeFence = new PurgeFence(scopeStores.documentLocks, new Set(lockedIds), purged);\n\t\tconst stores = {\n\t\t\t...scopeStores,\n\t\t\twriteCache: new FencedWriteCache(scopeStores.writeCache, purgeFence, (documentId) => {\n\t\t\t\tscopeStores.writeCache.invalidate(documentId);\n\t\t\t\tscopeStores.documentMetaCache.invalidate(documentId);\n\t\t\t})\n\t\t};\n\t\tconst unsupported = await this.unsupportedStoredProtocol(job, stores, signal);\n\t\tif (unsupported) return { result: buildErrorResult(job, unsupported, startTime) };\n\t\tconst indexTxn = stores.operationIndex.start();\n\t\tif (job.kind === \"load\") {\n\t\t\tconst loadResult = await this.executeLoadJob({\n\t\t\t\tjob,\n\t\t\t\tstartTime,\n\t\t\t\tindexTxn,\n\t\t\t\tstores,\n\t\t\t\tsignal,\n\t\t\t\treplayingAcceptedHistory: true,\n\t\t\t\tevaluatedByPosition: false,\n\t\t\t\tpostCommitInvalidations,\n\t\t\t\tpostCommitMembershipInvalidations,\n\t\t\t\ttouchedStreams,\n\t\t\t\tpurgeFence\n\t\t\t});\n\t\t\tif (loadResult.success && loadResult.operationsWithContext) {\n\t\t\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\t\t\tpostCommitMembershipInvalidations.push(...indexTxn.getMembershipInvalidations());\n\t\t\t\tfor (let i = 0; i < loadResult.operationsWithContext.length; i++) loadResult.operationsWithContext[i].context.ordinal = ordinals[i];\n\t\t\t\tconst collectionMemberships = loadResult.operationsWithContext.length > 0 ? await this.getCollectionMembershipsForOperations(loadResult.operationsWithContext, stores) : {};\n\t\t\t\tpendingEvent = {\n\t\t\t\t\tjobId: job.id,\n\t\t\t\t\toperations: loadResult.operationsWithContext,\n\t\t\t\t\tjobMeta: job.meta,\n\t\t\t\t\tcollectionMemberships\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tresult: loadResult,\n\t\t\t\tpendingEvent\n\t\t\t};\n\t\t}\n\t\tif (job.kind === \"reevaluation\") {\n\t\t\tconst reevalResult = await this.executeReevaluationJob({\n\t\t\t\tjob,\n\t\t\t\tstartTime,\n\t\t\t\tindexTxn,\n\t\t\t\tstores,\n\t\t\t\tsignal,\n\t\t\t\treplayingAcceptedHistory: false,\n\t\t\t\tevaluatedByPosition: false,\n\t\t\t\tpostCommitInvalidations,\n\t\t\t\tpostCommitMembershipInvalidations,\n\t\t\t\ttouchedStreams,\n\t\t\t\tpurgeFence\n\t\t\t});\n\t\t\tif (reevalResult.success && reevalResult.operationsWithContext) {\n\t\t\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\t\t\tpostCommitMembershipInvalidations.push(...indexTxn.getMembershipInvalidations());\n\t\t\t\tfor (let i = 0; i < reevalResult.operationsWithContext.length; i++) reevalResult.operationsWithContext[i].context.ordinal = ordinals[i];\n\t\t\t\tif (reevalResult.operationsWithContext.length > 0) {\n\t\t\t\t\tconst collectionMemberships = await this.getCollectionMembershipsForOperations(reevalResult.operationsWithContext, stores);\n\t\t\t\t\tpendingEvent = {\n\t\t\t\t\t\tjobId: job.id,\n\t\t\t\t\t\toperations: reevalResult.operationsWithContext,\n\t\t\t\t\t\tjobMeta: job.meta,\n\t\t\t\t\t\tcollectionMemberships\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tresult: reevalResult,\n\t\t\t\tpendingEvent\n\t\t\t};\n\t\t}\n\t\tlet admission;\n\t\ttry {\n\t\t\tadmission = await this.signatureAdmission.admitMutation(job, stores, signal);\n\t\t} catch (error) {\n\t\t\treturn { result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) };\n\t\t}\n\t\tif (admission.kind === \"refused\") return { result: buildErrorResult(job, admission.error, startTime) };\n\t\tlet committed;\n\t\ttry {\n\t\t\tcommitted = await this.reloadCommitted(admission.committed, stores, signal);\n\t\t} catch (error) {\n\t\t\treturn { result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) };\n\t\t}\n\t\tconst committedIds = new Set(admission.committed.map((write) => write.actionId));\n\t\tconst fresh = committedIds.size === 0 ? job : {\n\t\t\t...job,\n\t\t\tactions: job.actions.filter((action) => !committedIds.has(action.id))\n\t\t};\n\t\tif (fresh.actions.length === 0) return this.committedOutcome(job, committed, [], [], stores, startTime);\n\t\tconst positioned = await this.positionByTimestamp(fresh, stores, signal);\n\t\tif (positioned.error) return { result: buildErrorResult(job, positioned.error, startTime) };\n\t\tconst executing = {\n\t\t\tjob: fresh,\n\t\t\tstartTime,\n\t\t\tindexTxn,\n\t\t\tstores,\n\t\t\tsignal,\n\t\t\treplayingAcceptedHistory: false,\n\t\t\tevaluatedByPosition: positioned.evaluatedByPosition,\n\t\t\tpostCommitInvalidations,\n\t\t\tpostCommitMembershipInvalidations,\n\t\t\ttouchedStreams,\n\t\t\tpurgeFence\n\t\t};\n\t\tconst actionResult = await this.processActions(positioned.writes, executing);\n\t\tif (!actionResult.success) return { result: {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: actionResult.error,\n\t\t\tduration: Date.now() - startTime\n\t\t} };\n\t\tconst reevaluationError = await this.reevaluateIfCriteriaMet({\n\t\t\tscope: job.scope,\n\t\t\toperations: actionResult.generatedOperations\n\t\t}, executing);\n\t\tif (reevaluationError) return { result: {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: reevaluationError,\n\t\t\tduration: Date.now() - startTime\n\t\t} };\n\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\tpostCommitMembershipInvalidations.push(...indexTxn.getMembershipInvalidations());\n\t\tfor (let i = 0; i < actionResult.operationsWithContext.length; i++) actionResult.operationsWithContext[i].context.ordinal = ordinals[i];\n\t\treturn this.committedOutcome(job, committed, actionResult.operationsWithContext, actionResult.generatedOperations, stores, startTime);\n\t}\n\t/** A load names only its own id purged; a foreign one is ID_MISMATCH. */\n\tpurgedRefusal(job, purged) {\n\t\tif (purged.size === 0) return;\n\t\tif (purged.has(job.documentId)) return new DocumentPurgedError(job.documentId);\n\t\tconst actions = [...job.actions, ...job.operations.map((operation) => operation.action)];\n\t\tfor (const action of actions) {\n\t\t\tif (!DOCUMENT_SCOPE_ACTIONS.has(action.type)) continue;\n\t\t\tconst target = targetDocumentId(action, job.documentId);\n\t\t\tif (!purged.has(target)) continue;\n\t\t\tif (job.kind === \"mutation\") return new DocumentPurgedError(target);\n\t\t\treturn new InvalidSignatureError(job.documentId, \"ID_MISMATCH\", `${action.type} ${action.id} in ${job.documentId} writes purged ${target}`);\n\t\t}\n\t\tif (job.kind !== \"mutation\") return;\n\t\tfor (const action of job.actions) {\n\t\t\tconst target = relationshipTarget(action);\n\t\t\tif (action.type === \"ADD_RELATIONSHIP\" && target !== void 0 && purged.has(target)) return new DocumentPurgedError(target, `${action.type} target ${target} was purged`);\n\t\t\tif (action.scope !== \"auth\") continue;\n\t\t\tconst group = mentionedGroupIds(action).find((id) => purged.has(id));\n\t\t\tif (group !== void 0) return new DocumentPurgedError(group, `${action.type} names purged group ${group}`);\n\t\t}\n\t}\n\t/** A purge job or a marker load: the exclusive lock is the job's only lock. */\n\tasync executePurge(params) {\n\t\tconst { job, startTime, stores } = params;\n\t\tconst fail = (error) => ({ result: buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime) });\n\t\tif (job.kind === \"load\") {\n\t\t\tconst malformed = malformedMarker(job);\n\t\t\tif (malformed) return fail(malformed);\n\t\t}\n\t\tconst purger = stores.purger;\n\t\tif (!purger) return fail(/* @__PURE__ */ new Error(`Purge of ${job.documentId} needs a transactional scope`));\n\t\ttry {\n\t\t\tawait stores.documentLocks.exclusive(job.documentId);\n\t\t} catch (error) {\n\t\t\treturn fail(error);\n\t\t}\n\t\tlet alreadyPurged;\n\t\ttry {\n\t\t\talreadyPurged = (await stores.documentLocks.purged([job.documentId])).has(job.documentId);\n\t\t} catch (error) {\n\t\t\treturn fail(error);\n\t\t}\n\t\tif (alreadyPurged) return {\n\t\t\tresult: {\n\t\t\t\tjob,\n\t\t\t\tsuccess: true,\n\t\t\t\toperations: [],\n\t\t\t\toperationsWithContext: [],\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t},\n\t\t\tpendingEvent: {\n\t\t\t\tjobId: job.id,\n\t\t\t\toperations: [],\n\t\t\t\tjobMeta: job.meta,\n\t\t\t\tcollectionMemberships: {}\n\t\t\t}\n\t\t};\n\t\tlet commit;\n\t\ttry {\n\t\t\tcommit = job.kind === \"purge\" ? await this.preparePurgeJob(params, purger) : await this.preparePurgeLoad(params, purger);\n\t\t} catch (error) {\n\t\t\treturn fail(error);\n\t\t}\n\t\tif (commit instanceof Error) return fail(commit);\n\t\ttry {\n\t\t\treturn await this.commitPurge(params, commit);\n\t\t} catch (error) {\n\t\t\treturn fail(error);\n\t\t}\n\t}\n\t/** Preconditions 1-5, then the marker this host signs. */\n\tasync preparePurgeJob(params, purger) {\n\t\tconst { job, stores, signal } = params;\n\t\tconst documentId = job.documentId;\n\t\tif (!job.purge) return /* @__PURE__ */ new Error(`Purge job ${job.id} carries no purge options`);\n\t\tconst held = await this.heldStreams(purger, documentId);\n\t\tif (held.branches.length === 0) return new DocumentNotDeletedError(documentId, `Document ${documentId} is not held here`);\n\t\tlet documentType;\n\t\tfor (const branch of held.branches) {\n\t\t\tlet meta;\n\t\t\ttry {\n\t\t\t\tmeta = await stores.documentMetaCache.getDocumentMeta(documentId, branch, signal);\n\t\t\t} catch (error) {\n\t\t\t\treturn new DocumentNotDeletedError(documentId, `Document ${documentId} has no readable state on ${branch}: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\t}\n\t\t\tif (!meta.state.isDeleted) return new DocumentNotDeletedError(documentId, `Document ${documentId} is not deleted on branch ${branch}`);\n\t\t\tdocumentType ??= meta.documentType;\n\t\t}\n\t\tif (documentType === void 0) return new DocumentNotDeletedError(documentId);\n\t\tif (documentType === groupDocumentType) {\n\t\t\tconst referencers = await purger.groupReferencersInHistory(documentId);\n\t\t\tif (referencers.length > 0) return new GroupInUseError(documentId, referencers);\n\t\t}\n\t\tlet survivors = [];\n\t\tif (this.driveContainerTypes.has(documentType)) {\n\t\t\tconst requested = new Set(purgeRequestDocumentIds(job));\n\t\t\tconst members = await this.driveMembers(purger, stores, documentId, held.branches);\n\t\t\tconst blocking = members.required.filter((id) => !requested.has(id));\n\t\t\tif (blocking.length > 0) return new DocumentNotDeletedError(documentId, `Drive ${documentId} cannot be purged: ${blocking.join(\", \")} neither purged nor in the request`);\n\t\t\tsurvivors = members.survivors;\n\t\t}\n\t\tconst operationCount = await purger.operationCount(documentId);\n\t\tif (operationCount > this.config.maxPurgeOperations && !job.purge.allowLarge) return new PurgeTooLargeError(documentId, operationCount, this.config.maxPurgeOperations);\n\t\treturn {\n\t\t\tpurger,\n\t\t\tmarker: await this.signMarker(documentId, documentType, job.purge.requestId, signal),\n\t\t\tdocumentType,\n\t\t\theld,\n\t\t\tsourceRemote: \"\",\n\t\t\tcollectionIds: [],\n\t\t\tsurvivors\n\t\t};\n\t}\n\t/** A peer's marker, admitted alone; a receiver cannot refuse an erasure. */\n\tasync preparePurgeLoad(params, purger) {\n\t\tconst { job, stores, signal } = params;\n\t\tconst documentId = job.documentId;\n\t\tconst marker = job.operations.find((operation) => isPurgeMarker(operation));\n\t\tconst refusal = await this.signatureAdmission.admitMarker(job, marker, signal);\n\t\tif (refusal) return refusal;\n\t\tconst held = await this.heldStreams(purger, documentId);\n\t\tlet documentType = marker.action.input.documentType;\n\t\tlet appliedDeletion = held.branches.length > 0;\n\t\tif (held.branches.length > 0) try {\n\t\t\tconst meta = await stores.documentMetaCache.getDocumentMeta(documentId, held.branches.includes(\"main\") ? \"main\" : held.branches[0], signal);\n\t\t\tdocumentType = meta.documentType;\n\t\t\tappliedDeletion = !meta.state.isDeleted;\n\t\t} catch {}\n\t\tlet survivors = [];\n\t\tif (this.driveContainerTypes.has(documentType)) {\n\t\t\tconst members = await this.driveMembers(purger, stores, documentId, held.branches);\n\t\t\tsurvivors = [...members.required, ...members.survivors];\n\t\t}\n\t\tconst sourceRemote = typeof job.meta.sourceRemote === \"string\" ? job.meta.sourceRemote : \"\";\n\t\tconst collectionId = sourceRemote ? await purger.remoteCollection(sourceRemote) : void 0;\n\t\treturn {\n\t\t\tpurger,\n\t\t\tmarker: purgeMarkerOperation(marker.action),\n\t\t\tdocumentType,\n\t\t\theld,\n\t\t\tsourceRemote,\n\t\t\tcollectionIds: collectionId === void 0 ? [] : [collectionId],\n\t\t\tsurvivors,\n\t\t\t...appliedDeletion ? { appliedDeletion: true } : {}\n\t\t};\n\t}\n\t/** Execution: delete, write the marker and its twin, tombstone, reopen. */\n\tasync commitPurge(params, commit) {\n\t\tconst { job, startTime, stores, signal, touchedStreams } = params;\n\t\tconst { purger, marker, documentType, held, sourceRemote } = commit;\n\t\tconst documentId = job.documentId;\n\t\tconst streams = [...held.streams, {\n\t\t\tscope: \"document\",\n\t\t\tbranch: \"main\"\n\t\t}];\n\t\tfor (const stream of streams) {\n\t\t\ttouchedStreams.add(documentId, stream.scope, stream.branch);\n\t\t\tparams.postCommitInvalidations.push({\n\t\t\t\tdocumentId,\n\t\t\t\t...stream\n\t\t\t});\n\t\t}\n\t\tparams.postCommitMetaInvalidations.push(documentId);\n\t\tconst removedRows = await purger.deleteRows(documentId);\n\t\tconst [stored] = await stores.operationStore.apply(documentId, documentType, \"document\", \"main\", 0, (txn) => {\n\t\t\ttxn.addOperations(marker);\n\t\t}, signal);\n\t\tconst indexTxn = stores.operationIndex.start();\n\t\tindexTxn.write([{\n\t\t\t...stored,\n\t\t\tdocumentId,\n\t\t\tdocumentType,\n\t\t\tscope: \"document\",\n\t\t\tbranch: \"main\",\n\t\t\tsourceRemote\n\t\t}]);\n\t\tconst [ordinal] = await stores.operationIndex.commit(indexTxn, signal);\n\t\tawait purger.writeTombstone({\n\t\t\tdocumentId,\n\t\t\tordinal,\n\t\t\tremovedRows,\n\t\t\tpurgedAtUtc: marker.action.input.purgedAtUtcIso,\n\t\t\trequestId: marker.action.input.requestId\n\t\t});\n\t\tconst collections = await purger.reopenMemberships(documentId, ordinal, commit.collectionIds);\n\t\tparams.postCommitMembershipInvalidations.push(documentId, ...commit.survivors, ...indexTxn.getMembershipInvalidations());\n\t\tconst operationWithContext = {\n\t\t\toperation: stored,\n\t\t\tcontext: {\n\t\t\t\tdocumentId,\n\t\t\t\tscope: \"document\",\n\t\t\t\tbranch: \"main\",\n\t\t\t\tdocumentType,\n\t\t\t\tordinal,\n\t\t\t\t...commit.appliedDeletion ? { appliedDeletion: true } : {}\n\t\t\t}\n\t\t};\n\t\treturn {\n\t\t\tresult: {\n\t\t\t\tjob,\n\t\t\t\tsuccess: true,\n\t\t\t\toperations: [stored],\n\t\t\t\toperationsWithContext: [operationWithContext],\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t},\n\t\t\tpendingEvent: {\n\t\t\t\tjobId: job.id,\n\t\t\t\toperations: [operationWithContext],\n\t\t\t\tjobMeta: job.meta,\n\t\t\t\tcollectionMemberships: { [documentId]: collections }\n\t\t\t}\n\t\t};\n\t}\n\tasync heldStreams(purger, documentId) {\n\t\tconst streams = await purger.streams(documentId);\n\t\treturn {\n\t\t\tstreams,\n\t\t\tbranches: [...new Set(streams.filter((stream) => stream.scope === \"document\").map((stream) => stream.branch))]\n\t\t};\n\t}\n\t/** Members a drive purge needs gone, and those living on elsewhere. */\n\tasync driveMembers(purger, stores, driveId, branches) {\n\t\tconst required = /* @__PURE__ */ new Set();\n\t\tconst survivors = /* @__PURE__ */ new Set();\n\t\tfor (const branch of branches.length > 0 ? branches : [\"main\"]) {\n\t\t\tconst collectionId = DriveCollectionId.forDrive(driveId, branch).key;\n\t\t\tconst members = await purger.collectionMembers(collectionId, driveId, branch);\n\t\t\tconst purged = await stores.documentLocks.purged(members.map((member) => member.documentId));\n\t\t\tfor (const member of members) {\n\t\t\t\tif (purged.has(member.documentId)) continue;\n\t\t\t\tif (member.required) required.add(member.documentId);\n\t\t\t\telse survivors.add(member.documentId);\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\trequired: [...required],\n\t\t\tsurvivors: [...survivors]\n\t\t};\n\t}\n\t/** The marker, signed by this executor's signer as any peer admits it. */\n\tasync signMarker(documentId, documentType, requestId, signal) {\n\t\tconst action = purgeDocumentAction({\n\t\t\tdocumentId,\n\t\t\tdocumentType,\n\t\t\trequestId\n\t\t});\n\t\tconst signature = await this.signer.signAction(action, {\n\t\t\tdocumentId,\n\t\t\tbranch: \"main\"\n\t\t}, signal);\n\t\treturn purgeMarkerOperation({\n\t\t\t...action,\n\t\t\tcontext: { signer: {\n\t\t\t\t...actionSignerIdentity(this.signer),\n\t\t\t\tsignatures: [signature]\n\t\t\t} }\n\t\t});\n\t}\n\t/** A stored document at a version this reactor does not run is read-only here. */\n\tasync unsupportedStoredProtocol(job, stores, signal) {\n\t\tlet versions;\n\t\ttry {\n\t\t\tversions = this.featureFlags.documentDecisions && job.kind !== \"load\" ? (await stores.writeCache.getState(job.documentId, \"document\", job.branch, void 0, signal)).header.protocolVersions : (await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal)).protocolVersions;\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\treturn this.documentActionHandler.unsupportedProtocol(job.documentId, versions);\n\t}\n\t/**\n\t* A successful mutation's result and the write-ready event it owes, carrying\n\t* what earlier attempts committed ahead of what this one wrote.\n\t*/\n\tasync committedOutcome(job, reloaded, written, generated, stores, startTime) {\n\t\tconst operationsWithContext = [...reloaded, ...written];\n\t\tlet pendingEvent;\n\t\tif (operationsWithContext.length > 0) {\n\t\t\tconst collectionMemberships = await this.getCollectionMembershipsForOperations(operationsWithContext, stores);\n\t\t\tpendingEvent = {\n\t\t\t\tjobId: job.id,\n\t\t\t\toperations: operationsWithContext,\n\t\t\t\tjobMeta: job.meta,\n\t\t\t\tsubmittedActionIds: submittedActionIds(job),\n\t\t\t\tcollectionMemberships\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tresult: {\n\t\t\t\tjob,\n\t\t\t\tsuccess: true,\n\t\t\t\toperations: [...reloaded.map((entry) => entry.operation), ...generated],\n\t\t\t\toperationsWithContext,\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t},\n\t\t\tpendingEvent\n\t\t};\n\t}\n\t/**\n\t* The stored operations of writes an earlier attempt committed, as a fresh\n\t* write would report them. State is rebuilt from the write cache, and left\n\t* out when it cannot be.\n\t*/\n\tasync reloadCommitted(writes, stores, signal) {\n\t\tconst streams = /* @__PURE__ */ new Map();\n\t\tfor (const write of writes) {\n\t\t\tconst key = `${write.documentId}\\u0000${write.scope}\\u0000${write.branch}`;\n\t\t\tstreams.set(key, [...streams.get(key) ?? [], write]);\n\t\t}\n\t\tconst reloaded = [];\n\t\tfor (const group of streams.values()) {\n\t\t\tconst { documentId, scope, branch } = group[0];\n\t\t\tconst opIds = [...new Set(group.map((write) => write.opId))];\n\t\t\tconst operations = await stores.operationStore.getOperationsByIds(documentId, scope, branch, opIds, signal);\n\t\t\tconst ordinals = await stores.operationIndex.getOrdinalsByOpIds(documentId, scope, branch, opIds, signal);\n\t\t\tconst { documentType } = await stores.documentMetaCache.getDocumentMeta(documentId, branch, signal);\n\t\t\tfor (const operation of operations.sort((a, b) => a.index - b.index)) reloaded.push({\n\t\t\t\toperation,\n\t\t\t\tcontext: {\n\t\t\t\t\tdocumentId,\n\t\t\t\t\tscope,\n\t\t\t\t\tbranch,\n\t\t\t\t\tdocumentType,\n\t\t\t\t\tresultingState: await this.rebuiltState(stores, {\n\t\t\t\t\t\tdocumentId,\n\t\t\t\t\t\tscope,\n\t\t\t\t\t\tbranch\n\t\t\t\t\t}, operation, signal),\n\t\t\t\t\tordinal: ordinals.get(operation.id) ?? 0\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\treturn reloaded;\n\t}\n\tasync rebuiltState(stores, stream, operation, signal) {\n\t\ttry {\n\t\t\tconst document = await stores.writeCache.getState(stream.documentId, stream.scope, stream.branch, operation.index, signal);\n\t\t\treturn JSON.stringify({\n\t\t\t\t...document.state,\n\t\t\t\theader: document.header\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.logger.warn(\"No state for committed operation @OperationId in @Stream: @Error\", operation.id, stream, error);\n\t\t\treturn;\n\t\t}\n\t}\n\t/**\n\t* Drops the cached state of every stream a job wrote, after its transaction\n\t* did not commit.\n\t*\n\t* The caches are shared by reference with the copies the scope hands the job,\n\t* so a rollback undoes nothing in them: what the job put there survives, as\n\t* does anything a read filled from the store while the job's own writes were\n\t* still uncommitted. An eviction that throws is swallowed rather than allowed\n\t* to replace the failure the caller is owed, and the remaining streams are\n\t* still evicted.\n\t*/\n\tevictTouchedStreams(touchedStreams) {\n\t\tfor (const entry of touchedStreams) try {\n\t\t\tthis.writeCache.invalidate(entry.documentId, entry.scope, entry.branch);\n\t\t\tthis.documentMetaCache.invalidate(entry.documentId, entry.branch);\n\t\t\tthis.collectionMembershipCache.invalidate(entry.documentId);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Failed to evict cached state for rolled back @Stream : @Error\", entry, error);\n\t\t}\n\t}\n\tasync getCollectionMembershipsForOperations(operations, stores) {\n\t\tconst documentIds = [...new Set(operations.map((op) => op.context.documentId))];\n\t\treturn stores.collectionMembershipCache.getCollectionsForDocuments(documentIds);\n\t}\n\tasync processActions(writes, executing) {\n\t\tconst { job, signal } = executing;\n\t\tconst actions = writes.map((write) => write.action);\n\t\tconst generatedOperations = [];\n\t\tconst operationsWithContext = [];\n\t\tfor (const action of actions) if (action.timestampUtcMs && !isValidISOTimestamp(action.timestampUtcMs)) return {\n\t\t\tsuccess: false,\n\t\t\tgeneratedOperations,\n\t\t\toperationsWithContext,\n\t\t\terror: new InvalidOperationTimestampError(job.documentId, action.scope, action.timestampUtcMs, `action ${action.type} (id: ${action.id})`)\n\t\t};\n\t\tlet lastYield = performance.now();\n\t\tif (this.config.batchApplies && this.canBatch(writes, executing)) {\n\t\t\tconst batched = await this.executeRegularActionsBatched(writes, executing);\n\t\t\tconst error = this.accumulateResultOrReturnError(batched, generatedOperations, operationsWithContext);\n\t\t\tif (error !== null) return {\n\t\t\t\tsuccess: false,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext,\n\t\t\t\terror: error.error\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext\n\t\t\t};\n\t\t}\n\t\tfor (const write of writes) {\n\t\t\tconst result = DOCUMENT_SCOPE_ACTIONS.has(write.action.type) ? await this.documentActionHandler.execute(write, executing) : await this.executeRegularAction(write, executing);\n\t\t\tconst error = this.accumulateResultOrReturnError(result, generatedOperations, operationsWithContext);\n\t\t\tif (error !== null) return {\n\t\t\t\tsuccess: false,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext,\n\t\t\t\terror: error.error\n\t\t\t};\n\t\t\tif (performance.now() - lastYield > this.config.yieldDeadlineMs) {\n\t\t\t\tawait yieldToMain();\n\t\t\t\tlastYield = performance.now();\n\t\t\t\tif (signal?.aborted) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\tgeneratedOperations,\n\t\t\t\t\toperationsWithContext,\n\t\t\t\t\terror: /* @__PURE__ */ new Error(\"Aborted\")\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tgeneratedOperations,\n\t\t\toperationsWithContext\n\t\t};\n\t}\n\t/**\n\t* Decides a write and reduces it, without persisting anything.\n\t*\n\t* Split from the commit so one write and a batch of them share this logic\n\t* rather than keeping two copies of it. `baseDocument` lets a batch thread\n\t* the previous action's result forward instead of reading its own write back\n\t* out of the cache, which is the only reason the reduce has to be sequential.\n\t*/\n\tasync prepareRegularWrite(write, executing, baseDocument) {\n\t\tconst { action, skip, sourceOperation, sourceRemote, deniedReason } = write;\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tlet appendCondition;\n\t\tlet documentVersion;\n\t\tconst alreadyEvaluated = this.featureFlags.documentDecisions && (executing.replayingAcceptedHistory || executing.evaluatedByPosition);\n\t\tif (this.featureFlags.documentDecisions && !alreadyEvaluated) {\n\t\t\tconst target = {\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tbranch: job.branch\n\t\t\t};\n\t\t\tlet admission;\n\t\t\ttry {\n\t\t\t\tadmission = await decideAtHead(this.decisionModel, stores.writeCache, target, {\n\t\t\t\t\taddress: action.context?.signer?.user.address,\n\t\t\t\t\tkey: action.context?.signer?.app.key\n\t\t\t\t}, {\n\t\t\t\t\tverb: \"execute\",\n\t\t\t\t\tscope: action.scope,\n\t\t\t\t\toperation: action.type\n\t\t\t\t}, signal, this.featureFlags.authConditions ? {\n\t\t\t\t\tactionInput: action.input,\n\t\t\t\t\tcarriedDocument: baseDocument\n\t\t\t\t} : void 0);\n\t\t\t} catch (error) {\n\t\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t\t}\n\t\t\tif (admission.evaluation.decision === \"deny\") return buildErrorResult(job, refusalError(admission.evaluation.reason, job.documentId, admission.deletedAtUtcIso, action), startTime);\n\t\t\tappendCondition = admission.appendCondition;\n\t\t\tdocumentVersion = admission.documentVersion;\n\t\t} else if (alreadyEvaluated) documentVersion = (await stores.writeCache.getState(job.documentId, \"document\", job.branch, void 0, signal)).state.document.version;\n\t\telse {\n\t\t\tlet docMeta;\n\t\t\ttry {\n\t\t\t\tdocMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);\n\t\t\t} catch (error) {\n\t\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t\t}\n\t\t\tif (docMeta.state.isDeleted) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);\n\t\t\tdocumentVersion = docMeta.state.version;\n\t\t}\n\t\tif (isUndoRedo(action) || skip > 0) stores.writeCache.invalidate(job.documentId, job.scope, job.branch);\n\t\tlet document;\n\t\tif (baseDocument !== void 0) document = baseDocument;\n\t\telse try {\n\t\t\tdocument = await stores.writeCache.getState(job.documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tif (!this.featureFlags.authEnforcement && !executing.replayingAcceptedHistory) {\n\t\t\tconst subject = {\n\t\t\t\taddress: write.action.context?.signer?.user.address,\n\t\t\t\tkey: write.action.context?.signer?.app.key\n\t\t\t};\n\t\t\tif (decide(document.state.auth, subject, {\n\t\t\t\tverb: \"execute\",\n\t\t\t\tscope: action.scope,\n\t\t\t\toperation: action.type\n\t\t\t}) === \"deny\") return buildErrorResult(job, new AuthorizationDeniedError(job.documentId, action.scope, action.type, subject.address), startTime);\n\t\t}\n\t\tlet module;\n\t\ttry {\n\t\t\tmodule = this.registry.getModule(document.header.documentType, normalizeDocumentModelVersion(documentVersion));\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet updatedDocument;\n\t\tif (deniedReason !== void 0) {\n\t\t\tconst index = getNextIndexForScope(document, job.scope);\n\t\t\tconst denied = createOperation(action, index, skip, {\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tscope: job.scope,\n\t\t\t\tbranch: job.branch\n\t\t\t});\n\t\t\tdenied.deniedReason = deniedReason;\n\t\t\tlet standing = document;\n\t\t\tif (skip > 0) try {\n\t\t\t\tstanding = await stores.writeCache.getState(job.documentId, job.scope, job.branch, index - skip - 1, signal);\n\t\t\t} catch (error) {\n\t\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t\t}\n\t\t\tdenied.hash = hashDocumentStateForScope(standing, job.scope);\n\t\t\tupdatedDocument = {\n\t\t\t\t...standing,\n\t\t\t\toperations: {\n\t\t\t\t\t...standing.operations,\n\t\t\t\t\t[job.scope]: [...standing.operations[job.scope] ?? [], denied]\n\t\t\t\t}\n\t\t\t};\n\t\t} else try {\n\t\t\tconst protocolVersion = baseReducerVersion(document.header);\n\t\t\tconst reducerOptions = sourceOperation ? {\n\t\t\t\tskip,\n\t\t\t\tbranch: job.branch,\n\t\t\t\treplayOptions: { operation: sourceOperation },\n\t\t\t\tprotocolVersion\n\t\t\t} : {\n\t\t\t\tskip,\n\t\t\t\tbranch: job.branch,\n\t\t\t\tprotocolVersion\n\t\t\t};\n\t\t\tupdatedDocument = withProtocolVersions(module.reducer(document, action, void 0, reducerOptions), document.header.protocolVersions);\n\t\t} catch (error) {\n\t\t\tconst contextMessage = `Failed to apply action to document:\\n Action type: ${action.type}\\n Document ID: ${job.documentId}\\n Document type: ${document.header.documentType}\\n Scope: ${job.scope}\\n Original error: ${error instanceof Error ? error.message : String(error)}`;\n\t\t\tconst enhancedError = new Error(contextMessage);\n\t\t\tif (error instanceof Error && error.stack) enhancedError.stack = `${contextMessage}\\n\\nOriginal stack trace:\\n${error.stack}`;\n\t\t\treturn buildErrorResult(job, enhancedError, startTime);\n\t\t}\n\t\tconst scope = job.scope;\n\t\tconst operations = updatedDocument.operations[scope];\n\t\tif (operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error(\"No operation generated from action\"), startTime);\n\t\tconst newOperation = operations[operations.length - 1];\n\t\tif (!isUndoRedo(action)) newOperation.skip = skip;\n\t\tif (deniedReason === void 0 && sourceOperation === void 0 && !executing.replayingAcceptedHistory && isSynthesized(action, newOperation, document.operations[scope] ?? [])) try {\n\t\t\tawait signSynthesized(newOperation, action, {\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tscope,\n\t\t\t\tbranch: job.branch\n\t\t\t}, this.signer, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tconst resultingState = JSON.stringify({\n\t\t\t...updatedDocument.state,\n\t\t\theader: updatedDocument.header\n\t\t});\n\t\treturn {\n\t\t\taction,\n\t\t\tsourceRemote,\n\t\t\tscope,\n\t\t\tdocument,\n\t\t\tupdatedDocument,\n\t\t\toperation: newOperation,\n\t\t\tresultingState,\n\t\t\tappendCondition,\n\t\t\tdenied: deniedReason !== void 0\n\t\t};\n\t}\n\t/**\n\t* Persists a run of prepared writes in one store transaction.\n\t*\n\t* The store has always accepted many operations per apply; the executor only\n\t* ever handed it one. Passing the whole run means one advisory lock over the\n\t* read set and one guarded insert for the batch, instead of one of each per\n\t* operation.\n\t*\n\t* The append condition is taken from the first write. Every write in a run\n\t* reads the same streams at the same revisions, because nothing outside the\n\t* run can change them mid-batch, and the caller has already refused to batch\n\t* the scopes where that does not hold.\n\t*/\n\tasync commitPreparedWrites(prepared, executing) {\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tconst first = prepared[0];\n\t\tconst last = prepared[prepared.length - 1];\n\t\tconst scope = first.scope;\n\t\tconst documentType = first.document.header.documentType;\n\t\tconst operations = prepared.map((write) => write.operation);\n\t\texecuting.touchedStreams.add(job.documentId, scope, job.branch);\n\t\tlet storedOperations;\n\t\ttry {\n\t\t\tstoredOperations = await stores.operationStore.apply(job.documentId, documentType, scope, job.branch, first.operation.index, (txn) => {\n\t\t\t\ttxn.addOperations(...operations);\n\t\t\t}, signal, first.appendCondition);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Failed to write operation to IOperationStore (@documentId @scope @branch): @Operation @Error\", job.documentId, scope, job.branch, operations, error);\n\t\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\t\tif (AppendConditionFailedError.isError(error)) for (const stream of error.condition.streams) stores.writeCache.invalidate(stream.documentId, stream.scope, stream.branch);\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${String(error)}`),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\tconst head = storedOperations[storedOperations.length - 1];\n\t\tlast.updatedDocument.header.revision = {\n\t\t\t...last.updatedDocument.header.revision,\n\t\t\t[scope]: head.index + 1\n\t\t};\n\t\tstores.writeCache.putRun(job.documentId, scope, job.branch, storedOperations.map((operation, position) => ({\n\t\t\trevision: operation.index,\n\t\t\tdocument: prepared[position].updatedDocument\n\t\t})));\n\t\tindexTxn.write(storedOperations.map((operation, position) => ({\n\t\t\t...operation,\n\t\t\tdocumentId: job.documentId,\n\t\t\tdocumentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope,\n\t\t\tsourceRemote: prepared[position].sourceRemote\n\t\t})));\n\t\tif (scope === \"auth\") for (const write of prepared) indexTxn.recordGroupReferences(job.documentId, mentionedGroupIds(write.action));\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: storedOperations,\n\t\t\toperationsWithContext: storedOperations.map((operation, position) => ({\n\t\t\t\toperation,\n\t\t\t\tcontext: {\n\t\t\t\t\tdocumentId: job.documentId,\n\t\t\t\t\tscope,\n\t\t\t\t\tbranch: job.branch,\n\t\t\t\t\tdocumentType,\n\t\t\t\t\tresultingState: prepared[position].resultingState,\n\t\t\t\t\tordinal: 0\n\t\t\t\t}\n\t\t\t})),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\t/**\n\t* Whether a job's writes may share one store transaction.\n\t*\n\t* Deliberately narrow. Batching changes only how many transactions the\n\t* operations arrive in, and every condition below is a case where that would\n\t* change something else as well:\n\t*\n\t* - A document-scope action goes through its own handler, which has its own\n\t* apply and its own reasons for it.\n\t* - A positional or replayed run carries skips and re-appended operations,\n\t* whose indices are not a simple ascending run from the head.\n\t* - UNDO, REDO and NOOP-with-skip each invalidate the write cache to\n\t* force a full-history rebuild, so they cannot be reduced against state\n\t* threaded from the write before them.\n\t* - The auth scope decides later writes against the policy earlier ones\n\t* install, so a batch would decide them all against the policy as it stood\n\t* before the batch.\n\t* - The document scope is read by every decision model, so writing it is\n\t* writing part of the read set; the per-write conditions would not agree.\n\t*\n\t* A run that fails any of these is executed one write at a time, unchanged.\n\t*/\n\tcanBatch(writes, executing) {\n\t\tif (writes.length < 2) return false;\n\t\tif (executing.evaluatedByPosition || executing.replayingAcceptedHistory) return false;\n\t\tconst scope = executing.job.scope;\n\t\tif (scope === \"auth\" || scope === \"document\") return false;\n\t\treturn writes.every((write) => {\n\t\t\tconst type = write.action.type;\n\t\t\treturn write.skip === 0 && write.deniedReason === void 0 && write.sourceOperation === void 0 && !DOCUMENT_SCOPE_ACTIONS.has(type) && !isUndoRedo(write.action) && type !== \"NOOP\";\n\t\t});\n\t}\n\t/**\n\t* Decides and reduces a run of writes, then persists them together.\n\t*\n\t* The reduce stays sequential - each action needs the state the one before it\n\t* produced - but the result is threaded in memory rather than read back from\n\t* the cache, and the whole run reaches the store in a single apply.\n\t*\n\t* A write that turns out to be denied abandons the batch and replays the run\n\t* one write at a time, because a denied write holds a position of its own and\n\t* that is the path where the per-write behaviour is load-bearing. A write\n\t* that cannot be prepared fails the job outright: preparing is a read, so the\n\t* replay would only reach the same failure, and the job leaves nothing behind\n\t* either way.\n\t*/\n\tasync executeRegularActionsBatched(writes, executing) {\n\t\tconst prepared = [];\n\t\tlet carried;\n\t\tlet lastYield = performance.now();\n\t\tfor (const write of writes) {\n\t\t\tconst outcome = await this.prepareRegularWrite(write, executing, carried);\n\t\t\tif (\"success\" in outcome) return outcome;\n\t\t\tif (outcome.denied) return this.executeRegularActionsSequentially(writes, executing);\n\t\t\tprepared.push(outcome);\n\t\t\tcarried = outcome.updatedDocument;\n\t\t\tif (performance.now() - lastYield > this.config.yieldDeadlineMs) {\n\t\t\t\tawait yieldToMain();\n\t\t\t\tlastYield = performance.now();\n\t\t\t\tif (executing.signal?.aborted) return buildErrorResult(executing.job, /* @__PURE__ */ new Error(\"Aborted\"), executing.startTime);\n\t\t\t}\n\t\t}\n\t\tif (!this.conditionsAgree(prepared)) return this.executeRegularActionsSequentially(writes, executing);\n\t\treturn this.commitPreparedWrites(prepared, executing);\n\t}\n\t/** Whether every prepared write carries the same read-set condition. */\n\tconditionsAgree(prepared) {\n\t\tconst shape = (write) => write.appendCondition === void 0 ? \"none\" : JSON.stringify([...write.appendCondition.streams].map((stream) => [\n\t\t\tstream.documentId,\n\t\t\tstream.scope,\n\t\t\tstream.branch,\n\t\t\tstream.revision\n\t\t]).sort());\n\t\tconst first = shape(prepared[0]);\n\t\treturn prepared.every((write) => shape(write) === first);\n\t}\n\t/**\n\t* The unbatched path, for a run that turned out not to qualify after its\n\t* writes were prepared. Nothing has been persisted at that point, so\n\t* replaying the whole run per write is safe.\n\t*/\n\tasync executeRegularActionsSequentially(writes, executing) {\n\t\tconst operations = [];\n\t\tconst contexts = [];\n\t\tlet lastYield = performance.now();\n\t\tfor (const write of writes) {\n\t\t\tconst result = await this.executeRegularAction(write, executing);\n\t\t\tif (!result.success) return result;\n\t\t\toperations.push(...result.operations ?? []);\n\t\t\tcontexts.push(...result.operationsWithContext ?? []);\n\t\t\tif (performance.now() - lastYield > this.config.yieldDeadlineMs) {\n\t\t\t\tawait yieldToMain();\n\t\t\t\tlastYield = performance.now();\n\t\t\t\tif (executing.signal?.aborted) return buildErrorResult(executing.job, /* @__PURE__ */ new Error(\"Aborted\"), executing.startTime);\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tjob: executing.job,\n\t\t\tsuccess: true,\n\t\t\toperations,\n\t\t\toperationsWithContext: contexts,\n\t\t\tduration: Date.now() - executing.startTime\n\t\t};\n\t}\n\t/** Decides, reduces and persists one write. */\n\tasync executeRegularAction(write, executing) {\n\t\tconst prepared = await this.prepareRegularWrite(write, executing);\n\t\tif (\"success\" in prepared) return prepared;\n\t\treturn this.commitPreparedWrites([prepared], executing);\n\t}\n\t/**\n\t* Orders a write by timestamp and decides it where it lands. The caller\n\t* supplies the timestamp, so a write can belong before operations already\n\t* stored; those are re-appended alongside it, the way a load reshuffles.\n\t*\n\t* Deciding a backdated write at the stream heads instead of at its position\n\t* would overwrite the verdict every other replica computes for it.\n\t*/\n\tasync positionByTimestamp(job, stores, signal) {\n\t\tconst plain = () => ({\n\t\t\twrites: job.actions.map((action) => ({\n\t\t\t\taction,\n\t\t\t\tskip: 0,\n\t\t\t\tsourceRemote: \"\"\n\t\t\t})),\n\t\t\tevaluatedByPosition: false\n\t\t});\n\t\tif (!this.featureFlags.documentDecisions || job.actions.length === 0) return plain();\n\t\tlet earliest = job.actions[0].timestampUtcMs;\n\t\tlet earliestAt = Date.parse(earliest);\n\t\tfor (const action of job.actions) {\n\t\t\tconst at = Date.parse(action.timestampUtcMs);\n\t\t\tif (at < earliestAt) {\n\t\t\t\tearliest = action.timestampUtcMs;\n\t\t\t\tearliestAt = at;\n\t\t\t}\n\t\t}\n\t\tconst revisions = await stores.operationStore.getRevisions(job.documentId, job.branch, signal);\n\t\tconst backdated = earliestAt < Date.parse(revisions.latestTimestamp);\n\t\tif (this.featureFlags.authEnforcement && job.scope === \"auth\") {\n\t\t\tconst newest = await stores.operationStore.getStreamLatestTimestamp(job.documentId, \"auth\", job.branch, signal);\n\t\t\tconst violation = this.firstNonMonotonicTimestamp(job.actions, newest, job.documentId, job.branch);\n\t\t\tif (violation) return {\n\t\t\t\twrites: [],\n\t\t\t\tevaluatedByPosition: false,\n\t\t\t\terror: violation\n\t\t\t};\n\t\t\tif (!backdated) return plain();\n\t\t\treturn this.evaluatePositioned(job, stores, this.appendedOperations(job, revisions.revision[job.scope] ?? 0), signal);\n\t\t}\n\t\tif (!backdated) return plain();\n\t\tconst conflicting = (await stores.operationStore.getConflicting(job.documentId, job.scope, job.branch, earliest, void 0, signal)).results.filter((operation) => !isGenesisOperation(operation));\n\t\tconst nothingToMove = async () => {\n\t\t\tif (!this.featureFlags.authEnforcement) return plain();\n\t\t\treturn this.evaluatePositioned(job, stores, this.appendedOperations(job, revisions.revision[job.scope] ?? 0), signal);\n\t\t};\n\t\tif (conflicting.length === 0) return nothingToMove();\n\t\tconst nextIndex = revisions.revision[job.scope] ?? 0;\n\t\tlet firstConflicting = conflicting[0].index;\n\t\tfor (const operation of conflicting) if (operation.index < firstConflicting) firstConflicting = operation.index;\n\t\tconst stored = (await stores.operationStore.getSince(job.documentId, job.scope, job.branch, firstConflicting - 1, void 0, void 0, signal)).results;\n\t\tconst conflictingIds = new Set(conflicting.map((operation) => operation.id));\n\t\tconst effective = garbageCollect(sortOperations(stored)).filter((operation) => !isGenesisOperation(operation));\n\t\tconst firstMoving = effective.findIndex((operation) => conflictingIds.has(operation.id));\n\t\tconst moving = firstMoving === -1 ? [] : effective.slice(firstMoving);\n\t\tif (moving.length === 0) return nothingToMove();\n\t\tlet firstRetracted = moving[0].index;\n\t\tfor (const operation of moving) firstRetracted = Math.min(firstRetracted, operation.index - operation.skip);\n\t\tconst incoming = job.actions.map((action, i) => ({\n\t\t\tid: action.id,\n\t\t\tindex: nextIndex + i,\n\t\t\tskip: 0,\n\t\t\thash: \"\",\n\t\t\ttimestampUtcMs: action.timestampUtcMs,\n\t\t\taction\n\t\t}));\n\t\tconst merged = reshuffleByTimestamp({\n\t\t\tindex: nextIndex,\n\t\t\tskip: retractionSkip(nextIndex, firstRetracted)\n\t\t}, moving, incoming);\n\t\tstores.writeCache.invalidate(job.documentId, job.scope, job.branch);\n\t\tif (!this.featureFlags.authEnforcement) return {\n\t\t\twrites: merged.map((operation) => ({\n\t\t\t\taction: operation.action,\n\t\t\t\tskip: operation.skip,\n\t\t\t\tsourceRemote: \"\"\n\t\t\t})),\n\t\t\tevaluatedByPosition: false\n\t\t};\n\t\treturn this.evaluatePositioned(job, stores, merged, signal);\n\t}\n\t/**\n\t* Decides each operation where it lands and carries the verdict on it. A\n\t* refused submitted action is reported to the caller and nothing is stored; a\n\t* refused operation the reshuffle merely moved keeps its verdict, because it\n\t* already holds a position.\n\t*\n\t* The operations carry the indexes and skips they will be stored at, because\n\t* the walk resolves skips before it orders them.\n\t*/\n\tasync evaluatePositioned(job, stores, operations, signal) {\n\t\tconst reasons = await evaluateByPosition(this.decisionModel, {\n\t\t\tdocumentId: job.documentId,\n\t\t\tbranch: job.branch\n\t\t}, {\n\t\t\tscope: job.scope,\n\t\t\toperations\n\t\t}, stores, signal);\n\t\tconst submitted = new Set(job.actions.map((action) => action.id));\n\t\tfor (let i = 0; i < operations.length; i++) {\n\t\t\tconst reason = reasons[i];\n\t\t\tif (reason !== void 0 && submitted.has(operations[i].action.id)) return {\n\t\t\t\twrites: [],\n\t\t\t\tevaluatedByPosition: false,\n\t\t\t\terror: refusalError(reason, job.documentId, null, operations[i].action)\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\twrites: operations.map((operation, i) => ({\n\t\t\t\taction: operation.action,\n\t\t\t\tskip: operation.skip,\n\t\t\t\tsourceRemote: \"\",\n\t\t\t\tdeniedReason: reasons[i]\n\t\t\t})),\n\t\t\tevaluatedByPosition: true\n\t\t};\n\t}\n\t/**\n\t* The scopes a re-evaluation pass visits, in a fixed order.\n\t*\n\t* The revisions map comes from a query with no ORDER BY, and the order is\n\t* load-bearing: each scope's pass re-reads the auth stream, and the walk skips\n\t* an operation by its stored denial, so a denial this pass just wrote is\n\t* visible to a later-visited scope and invisible to an earlier one. The model's\n\t* own projection order leads, then the rest sorted, so the pass is reproducible\n\t* across replicas and across runs.\n\t*/\n\tevaluationOrder(target, revision) {\n\t\tconst definition = this.decisionModel(target);\n\t\tconst evaluated = Object.keys(revision).filter((scope) => definition.evaluatesScope(scope));\n\t\tconst leading = [];\n\t\tfor (const stream of staticReadSet(definition)) {\n\t\t\tconst scope = stream.query.scope;\n\t\t\tif (evaluated.includes(scope) && !leading.includes(scope)) leading.push(scope);\n\t\t}\n\t\tconst rest = evaluated.filter((scope) => !leading.includes(scope)).sort((a, b) => a.localeCompare(b));\n\t\treturn [...leading, ...rest];\n\t}\n\t/**\n\t* The first timestamp in the batch that does not strictly exceed everything\n\t* ahead of it, or undefined when the whole batch is monotonic.\n\t*\n\t* The bound is carried forward rather than compared against one stored maximum,\n\t* because a single execute can carry several auth actions stamped in the same\n\t* millisecond. Letting a tie through would store a stream the position walk\n\t* then refuses to read, with no repair path.\n\t*/\n\tfirstNonMonotonicTimestamp(entries, newest, documentId, branch) {\n\t\tlet boundIso = newest;\n\t\tlet bound = newest === void 0 ? Number.NEGATIVE_INFINITY : Date.parse(newest);\n\t\tfor (const entry of entries) {\n\t\t\tif (!isValidISOTimestamp(entry.timestampUtcMs)) return new InvalidOperationTimestampError(documentId, \"auth\", entry.timestampUtcMs, \"auth operation\");\n\t\t\tconst at = Date.parse(entry.timestampUtcMs);\n\t\t\tif (boundIso !== void 0 && at <= bound) return new AuthTimestampNotMonotonicError(documentId, branch, entry.timestampUtcMs, boundIso);\n\t\t\tbound = at;\n\t\t\tboundIso = entry.timestampUtcMs;\n\t\t}\n\t}\n\t/** The operations a batch of submitted actions appends at the scope's tail. */\n\tappendedOperations(job, nextIndex) {\n\t\treturn job.actions.map((action, i) => ({\n\t\t\tid: action.id,\n\t\t\tindex: nextIndex + i,\n\t\t\tskip: 0,\n\t\t\thash: \"\",\n\t\t\ttimestampUtcMs: action.timestampUtcMs,\n\t\t\taction\n\t\t}));\n\t}\n\t/**\n\t* Re-evaluates the document when a write meets both criteria: it was written\n\t* to a stream the model reads, and it is timestamped before an operation\n\t* already stored. The caller supplies the timestamp and the reactor does not replace\n\t* it, so a mutation job can write such an operation just as a load job can,\n\t* which is why both executeJob and executeLoadJob call this.\n\t*/\n\tasync reevaluateIfCriteriaMet(criteria, executing) {\n\t\tif (!this.featureFlags.documentDecisions) return;\n\t\tconst { job, stores, signal } = executing;\n\t\tconst target = {\n\t\t\tdocumentId: job.documentId,\n\t\t\tbranch: job.branch\n\t\t};\n\t\tif (!staticReadSet(this.decisionModel(target)).some((stream) => stream.query.documentId === job.documentId && stream.query.scope === criteria.scope && stream.query.branch === job.branch)) return;\n\t\tconst revisions = await stores.operationStore.getRevisions(job.documentId, job.branch, signal);\n\t\tconst latest = Date.parse(revisions.latestTimestamp);\n\t\tif (!criteria.operations.some((operation) => Date.parse(operation.timestampUtcMs) < latest)) return;\n\t\treturn (await this.reevaluateDocument(executing)).error;\n\t}\n\t/**\n\t* Re-evaluates every scope the model evaluates. Where an operation's\n\t* evaluation differs from what is stored, the tail from that operation is\n\t* re-appended, carrying a skip that spans the indices it supersedes.\n\t*/\n\tasync reevaluateDocument(executing) {\n\t\tconst { job, stores, signal } = executing;\n\t\tconst target = {\n\t\t\tdocumentId: job.documentId,\n\t\t\tbranch: job.branch\n\t\t};\n\t\tconst reappended = [];\n\t\tconst revisions = await stores.operationStore.getRevisions(job.documentId, job.branch, signal);\n\t\tfor (const scope of this.evaluationOrder(target, revisions.revision)) {\n\t\t\tconst stored = (await stores.operationStore.getSince(job.documentId, scope, job.branch, -1, void 0, void 0, signal)).results;\n\t\t\tconst effective = garbageCollect(sortOperations([...stored]));\n\t\t\tif (effective.length === 0) continue;\n\t\t\tconst reevaluated = await evaluateByPosition(this.decisionModel, target, {\n\t\t\t\tscope,\n\t\t\t\toperations: effective\n\t\t\t}, stores, signal);\n\t\t\tconst firstChange = effective.findIndex((operation, i) => operation.deniedReason !== reevaluated[i]);\n\t\t\tif (firstChange === -1) continue;\n\t\t\tconst tail = effective.slice(firstChange);\n\t\t\tconst nextIndex = revisions.revision[scope];\n\t\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\t\tconst result = await this.processActions(tail.map((operation, i) => ({\n\t\t\t\taction: operation.action,\n\t\t\t\tskip: i === 0 ? retractionSkip(nextIndex, tail[0].index - tail[0].skip) : 0,\n\t\t\t\tsourceRemote: \"\",\n\t\t\t\tdeniedReason: reevaluated[firstChange + i]\n\t\t\t})), {\n\t\t\t\t...executing,\n\t\t\t\tjob: {\n\t\t\t\t\t...job,\n\t\t\t\t\tscope\n\t\t\t\t},\n\t\t\t\treplayingAcceptedHistory: true,\n\t\t\t\tevaluatedByPosition: true\n\t\t\t});\n\t\t\tif (!result.success) return {\n\t\t\t\terror: result.error ?? /* @__PURE__ */ new Error(`Re-evaluation of ${job.documentId} ${scope} failed`),\n\t\t\t\toperationsWithContext: reappended\n\t\t\t};\n\t\t\treappended.push(...result.operationsWithContext);\n\t\t}\n\t\treturn { operationsWithContext: reappended };\n\t}\n\t/**\n\t* Re-judges a document's stored operations because a read-set stream in\n\t* another document (a group) gained an operation. The trigger timestamp\n\t* bounds the work: an operation later than everything this document holds\n\t* cannot change any evaluation, so the pass is skipped.\n\t*/\n\tasync executeReevaluationJob(executing) {\n\t\tconst { job, startTime, stores, signal } = executing;\n\t\tif (!this.featureFlags.documentDecisions) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst trigger = job.meta.triggerTimestampUtcMs;\n\t\tif (typeof trigger === \"string\") {\n\t\t\tlet latestTimestamp;\n\t\t\ttry {\n\t\t\t\tlatestTimestamp = (await stores.operationStore.getRevisions(job.documentId, job.branch, signal)).latestTimestamp;\n\t\t\t} catch {\n\t\t\t\treturn {\n\t\t\t\t\tjob,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\toperations: [],\n\t\t\t\t\toperationsWithContext: [],\n\t\t\t\t\tduration: Date.now() - startTime\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (Date.parse(trigger) > Date.parse(latestTimestamp)) return {\n\t\t\t\tjob,\n\t\t\t\tsuccess: true,\n\t\t\t\toperations: [],\n\t\t\t\toperationsWithContext: [],\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\tconst outcome = await this.reevaluateDocument(executing);\n\t\tif (outcome.error) return buildErrorResult(job, outcome.error, startTime);\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: outcome.operationsWithContext.map((owc) => owc.operation),\n\t\t\toperationsWithContext: outcome.operationsWithContext,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\tasync executeLoadJob(executing) {\n\t\tconst { job, startTime, indexTxn, stores, signal } = executing;\n\t\tif (job.operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error(\"Load job must include at least one operation\"), startTime);\n\t\tlet docMeta;\n\t\ttry {\n\t\t\tdocMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);\n\t\t} catch {}\n\t\tif (docMeta?.state.isDeleted && !this.featureFlags.documentDecisions) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);\n\t\tconst scope = job.scope;\n\t\tconst monotonicAuthStream = this.featureFlags.authEnforcement && scope === \"auth\";\n\t\tlet latestRevision;\n\t\ttry {\n\t\t\tlatestRevision = (await stores.operationStore.getRevisions(job.documentId, job.branch, signal)).revision[scope] ?? 0;\n\t\t} catch {\n\t\t\tlatestRevision = 0;\n\t\t}\n\t\tfor (const operation of job.operations) if (operation.timestampUtcMs && !isValidISOTimestamp(operation.timestampUtcMs)) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: new InvalidOperationTimestampError(job.documentId, scope, operation.timestampUtcMs, `operation (index: ${operation.index})`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst dropped = /* @__PURE__ */ new Set();\n\t\tconst admitted = /* @__PURE__ */ new Set();\n\t\tlet selection = await this.selectLoadWrites(job, job.operations, stores, signal);\n\t\tfor (;;) {\n\t\t\tconst unadmitted = selection.incomingOpsToApply.filter((operation) => !admitted.has(operation));\n\t\t\tif (unadmitted.length === 0) break;\n\t\t\tlet refused;\n\t\t\ttry {\n\t\t\t\trefused = await this.signatureAdmission.admitLoad(job, unadmitted, stores, signal);\n\t\t\t} catch (error) {\n\t\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t\t}\n\t\t\tfor (const operation of unadmitted) if (refused.has(operation)) dropped.add(operation);\n\t\t\telse admitted.add(operation);\n\t\t\tif (refused.size === 0) break;\n\t\t\tconst remaining = job.operations.filter((operation) => !dropped.has(operation));\n\t\t\tif (remaining.length === 0) return {\n\t\t\t\tjob,\n\t\t\t\tsuccess: true,\n\t\t\t\toperations: [],\n\t\t\t\toperationsWithContext: [],\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t\tselection = await this.selectLoadWrites(job, remaining, stores, signal);\n\t\t}\n\t\tconst { nonSupersededOps, allOpsFromMinConflictingIndex, incomingOpsToApply } = selection;\n\t\tconst existingOpsToReshuffle = monotonicAuthStream ? [] : nonSupersededOps.filter((operation) => !isGenesisOperation(operation));\n\t\tconst actionIdCounts = /* @__PURE__ */ new Map();\n\t\tfor (const operation of allOpsFromMinConflictingIndex) actionIdCounts.set(operation.action.id, (actionIdCounts.get(operation.action.id) ?? 0) + 1);\n\t\tconst reshuffleCost = existingOpsToReshuffle.filter((operation) => (actionIdCounts.get(operation.action.id) ?? 0) < 2).length;\n\t\tif (reshuffleCost > this.config.maxSkipThreshold) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: new ExcessiveReshuffleError(job.documentId, scope, reshuffleCost, this.config.maxSkipThreshold),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tlet skipCount = existingOpsToReshuffle.length;\n\t\tif (existingOpsToReshuffle.length > 0) {\n\t\t\tlet minLogicalIndex = Number.POSITIVE_INFINITY;\n\t\t\tfor (const op of existingOpsToReshuffle) {\n\t\t\t\tconst logical = op.index - op.skip;\n\t\t\t\tif (logical < minLogicalIndex) minLogicalIndex = logical;\n\t\t\t}\n\t\t\tconst logicalSkip = latestRevision - minLogicalIndex;\n\t\t\tif (logicalSkip > skipCount) skipCount = logicalSkip;\n\t\t}\n\t\tif (incomingOpsToApply.length === 0) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tif (monotonicAuthStream) {\n\t\t\tconst newest = await stores.operationStore.getStreamLatestTimestamp(job.documentId, \"auth\", job.branch, signal);\n\t\t\tconst violation = this.firstNonMonotonicTimestamp([...incomingOpsToApply].sort((a, b) => a.index - b.index), newest, job.documentId, job.branch);\n\t\t\tif (violation) return {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: violation,\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\tconst reshuffledOperations = existingOpsToReshuffle.length === 0 && skipCount === 0 ? incomingOpsToApply.slice().sort((a, b) => a.index - b.index).map((operation, i) => ({\n\t\t\t...operation,\n\t\t\tindex: latestRevision + i\n\t\t})) : reshuffleByTimestamp({\n\t\t\tindex: latestRevision,\n\t\t\tskip: skipCount\n\t\t}, existingOpsToReshuffle, incomingOpsToApply.map((operation) => ({\n\t\t\t...operation,\n\t\t\tid: operation.id\n\t\t})));\n\t\tconst incomingIds = new Set(incomingOpsToApply.map((operation) => operation.action.id));\n\t\tfor (const operation of reshuffledOperations) if (operation.action.type === \"NOOP\" && operation.skip === 0 && incomingIds.has(operation.action.id)) operation.skip = 1;\n\t\tlet deniedReasons;\n\t\tif (this.featureFlags.documentDecisions) try {\n\t\t\tdeniedReasons = await evaluateByPosition(this.decisionModel, {\n\t\t\t\tdocumentId: job.documentId,\n\t\t\t\tbranch: job.branch\n\t\t\t}, {\n\t\t\t\tscope,\n\t\t\t\toperations: reshuffledOperations\n\t\t\t}, stores, signal);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\tconst effectiveSourceRemote = skipCount > 0 ? \"\" : job.meta.sourceRemote || \"\";\n\t\tconst result = await this.processActions(reshuffledOperations.map((operation, i) => ({\n\t\t\taction: operation.action,\n\t\t\tskip: operation.skip,\n\t\t\tsourceOperation: operation,\n\t\t\tsourceRemote: effectiveSourceRemote,\n\t\t\tdeniedReason: deniedReasons?.[i]\n\t\t})), executing);\n\t\tif (!result.success) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: result.error,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\tif (scope === \"document\") stores.documentMetaCache.invalidate(job.documentId, job.branch);\n\t\tconst reevaluationError = await this.reevaluateIfCriteriaMet({\n\t\t\tscope,\n\t\t\toperations: result.generatedOperations\n\t\t}, executing);\n\t\tif (reevaluationError) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: reevaluationError,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: result.generatedOperations,\n\t\t\toperationsWithContext: result.operationsWithContext,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\t/** The conflicting window a load opens, and which of its operations are new. */\n\tasync selectLoadWrites(job, operations, stores, signal) {\n\t\tconst scope = job.scope;\n\t\tlet minIncomingIndex = Number.POSITIVE_INFINITY;\n\t\tlet minIncomingTimestamp = operations[0]?.timestampUtcMs || \"\";\n\t\tfor (const operation of operations) {\n\t\t\tminIncomingIndex = Math.min(minIncomingIndex, operation.index);\n\t\t\tconst ts = operation.timestampUtcMs || \"\";\n\t\t\tif (Date.parse(ts) < Date.parse(minIncomingTimestamp)) minIncomingTimestamp = ts;\n\t\t}\n\t\tlet conflictingOps;\n\t\ttry {\n\t\t\tconflictingOps = (await stores.operationStore.getConflicting(job.documentId, scope, job.branch, minIncomingTimestamp, void 0, signal)).results;\n\t\t} catch {\n\t\t\tconflictingOps = [];\n\t\t}\n\t\tlet allOpsFromMinConflictingIndex = conflictingOps;\n\t\tif (conflictingOps.length > 0) {\n\t\t\tconst minConflictingIndex = Math.min(...conflictingOps.map((op) => op.index));\n\t\t\ttry {\n\t\t\t\tallOpsFromMinConflictingIndex = (await stores.operationStore.getSince(job.documentId, scope, job.branch, minConflictingIndex - 1, void 0, void 0, signal)).results;\n\t\t\t} catch {\n\t\t\t\tallOpsFromMinConflictingIndex = conflictingOps;\n\t\t\t}\n\t\t}\n\t\tconst incomingActionIds = new Set(operations.map((op) => op.action.id));\n\t\tconst supersededBy = (op) => {\n\t\t\tlet nearest;\n\t\t\tfor (const laterOp of allOpsFromMinConflictingIndex) if (laterOp.index > op.index && laterOp.skip > 0 && laterOp.index - laterOp.skip <= op.index && (nearest === void 0 || laterOp.index < nearest.index)) nearest = laterOp;\n\t\t\treturn nearest;\n\t\t};\n\t\tconst undoneActionIds = /* @__PURE__ */ new Set();\n\t\tlet predecessorBound = minIncomingIndex;\n\t\tconst rowsByActionId = /* @__PURE__ */ new Map();\n\t\tfor (const op of conflictingOps) if (incomingActionIds.has(op.action.id)) rowsByActionId.set(op.action.id, [...rowsByActionId.get(op.action.id) ?? [], op]);\n\t\tconst liveOps = /* @__PURE__ */ new Set();\n\t\tfor (const op of conflictingOps) if (supersededBy(op) === void 0) liveOps.add(op);\n\t\tfor (const [actionId, rows] of rowsByActionId) {\n\t\t\tif (rows.some((row) => liveOps.has(row))) continue;\n\t\t\tif (rows.some((row) => supersededBy(row)?.action.type === \"NOOP\")) undoneActionIds.add(actionId);\n\t\t\telse predecessorBound = Math.min(predecessorBound, Math.max(...rows.map((row) => row.index)));\n\t\t}\n\t\tconst nonSupersededOps = conflictingOps.filter((op) => {\n\t\t\tif (op.index < predecessorBound && !incomingActionIds.has(op.action.id)) return false;\n\t\t\treturn liveOps.has(op);\n\t\t});\n\t\tlet rewoundFrom = Number.POSITIVE_INFINITY;\n\t\tfor (const op of nonSupersededOps) if (!isGenesisOperation(op)) rewoundFrom = Math.min(rewoundFrom, op.index - op.skip);\n\t\tconst reappended = new Set(nonSupersededOps.map((op) => op.index));\n\t\tfor (const op of allOpsFromMinConflictingIndex) if (op.index >= rewoundFrom && !reappended.has(op.index) && supersededBy(op) === void 0) nonSupersededOps.push(op);\n\t\tconst existingActionIds = new Set(nonSupersededOps.map((op) => op.action.id));\n\t\tconst seenIncomingActionIds = /* @__PURE__ */ new Set();\n\t\tconst incomingOpsToApply = operations.filter((op) => {\n\t\t\tif (existingActionIds.has(op.action.id)) return false;\n\t\t\tif (undoneActionIds.has(op.action.id)) return false;\n\t\t\tif (seenIncomingActionIds.has(op.action.id)) return false;\n\t\t\tseenIncomingActionIds.add(op.action.id);\n\t\t\treturn true;\n\t\t});\n\t\treturn {\n\t\t\tnonSupersededOps,\n\t\t\tallOpsFromMinConflictingIndex,\n\t\t\tincomingOpsToApply\n\t\t};\n\t}\n\taccumulateResultOrReturnError(result, generatedOperations, operationsWithContext) {\n\t\tif (!result.success) return result;\n\t\tif (result.operations && result.operations.length > 0) generatedOperations.push(...result.operations);\n\t\tif (result.operationsWithContext) operationsWithContext.push(...result.operationsWithContext);\n\t\treturn null;\n\t}\n};\n//#endregion\n//#region src/registry/implementation.ts\n/**\n* In-memory implementation of the IDocumentModelRegistry interface.\n* Manages document model modules with version-aware storage and upgrade manifest support.\n*/\nvar DocumentModelRegistry = class {\n\tmodules = [];\n\tmanifests = [];\n\tregisterModules(...modules) {\n\t\treturn modules.map((module) => {\n\t\t\ttry {\n\t\t\t\tconst documentType = module.documentModel.global.id;\n\t\t\t\tconst version = module.version ?? 1;\n\t\t\t\tfor (let i = 0; i < this.modules.length; i++) {\n\t\t\t\t\tconst existing = this.modules[i];\n\t\t\t\t\tconst existingType = existing.documentModel.global.id;\n\t\t\t\t\tconst existingVersion = existing.version ?? 1;\n\t\t\t\t\tif (existingType === documentType && existingVersion === version) throw new DuplicateModuleError(documentType, version);\n\t\t\t\t}\n\t\t\t\tthis.modules.push(module);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\titem: module\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\titem: module,\n\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\tunregisterModules(...documentTypes) {\n\t\tlet allFound = true;\n\t\tfor (const documentType of documentTypes) {\n\t\t\tif (!this.modules.some((m) => m.documentModel.global.id === documentType)) allFound = false;\n\t\t\tthis.modules = this.modules.filter((m) => m.documentModel.global.id !== documentType);\n\t\t}\n\t\treturn allFound;\n\t}\n\tgetModule(documentType, version) {\n\t\tlet latestModule;\n\t\tlet latestVersion = -1;\n\t\tfor (let i = 0; i < this.modules.length; i++) {\n\t\t\tconst module = this.modules[i];\n\t\t\tconst moduleType = module.documentModel.global.id;\n\t\t\tconst moduleVersion = module.version ?? 1;\n\t\t\tif (moduleType === documentType) {\n\t\t\t\tif (version !== void 0 && moduleVersion === version) return module;\n\t\t\t\tif (moduleVersion > latestVersion) {\n\t\t\t\t\tlatestModule = module;\n\t\t\t\t\tlatestVersion = moduleVersion;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (version === void 0 && latestModule !== void 0) return latestModule;\n\t\tthrow new ModuleNotFoundError(documentType, version);\n\t}\n\tgetAllModules() {\n\t\treturn [...this.modules];\n\t}\n\tclear() {\n\t\tthis.modules = [];\n\t\tthis.manifests = [];\n\t}\n\tgetSupportedVersions(documentType) {\n\t\tconst versions = [];\n\t\tfor (const module of this.modules) if (module.documentModel.global.id === documentType) versions.push(module.version ?? 1);\n\t\tif (versions.length === 0) throw new ModuleNotFoundError(documentType);\n\t\treturn versions.sort((a, b) => a - b);\n\t}\n\tgetLatestVersion(documentType) {\n\t\tlet latest = -1;\n\t\tlet found = false;\n\t\tfor (const module of this.modules) if (module.documentModel.global.id === documentType) {\n\t\t\tfound = true;\n\t\t\tconst version = module.version ?? 1;\n\t\t\tif (version > latest) latest = version;\n\t\t}\n\t\tif (!found) throw new ModuleNotFoundError(documentType);\n\t\treturn latest;\n\t}\n\tregisterUpgradeManifests(...manifestsToRegister) {\n\t\treturn manifestsToRegister.map((manifestToRegister) => {\n\t\t\ttry {\n\t\t\t\tif (!manifestToRegister.documentType) throw new Error(\"Upgrade manifest is missing a documentType\");\n\t\t\t\tfor (const registeredManifest of this.manifests) if (registeredManifest.documentType === manifestToRegister.documentType) throw new DuplicateManifestError(manifestToRegister.documentType);\n\t\t\t\tthis.manifests.push(manifestToRegister);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\titem: manifestToRegister\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\titem: manifestToRegister,\n\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\tunregisterUpgradeManifests(...documentTypes) {\n\t\tlet allFound = true;\n\t\tfor (const documentType of documentTypes) {\n\t\t\tif (!this.manifests.some((m) => m.documentType === documentType)) allFound = false;\n\t\t\tthis.manifests = this.manifests.filter((m) => m.documentType !== documentType);\n\t\t}\n\t\treturn allFound;\n\t}\n\tgetUpgradeManifest(documentType) {\n\t\tfor (let i = 0; i < this.manifests.length; i++) if (this.manifests[i].documentType === documentType) return this.manifests[i];\n\t\tthrow new ManifestNotFoundError(documentType);\n\t}\n\tcomputeUpgradePath(documentType, fromVersion, toVersion) {\n\t\tif (fromVersion === toVersion) return [];\n\t\tif (toVersion < fromVersion) throw new DowngradeNotSupportedError$1(documentType, fromVersion, toVersion);\n\t\tconst manifest = this.getUpgradeManifest(documentType);\n\t\tconst path = [];\n\t\tfor (let v = fromVersion + 1; v <= toVersion; v++) {\n\t\t\tconst key = `v${v}`;\n\t\t\tif (!(key in manifest.upgrades)) throw new MissingUpgradeTransitionError(documentType, v - 1, v);\n\t\t\tconst transition = manifest.upgrades[key];\n\t\t\tpath.push(transition);\n\t\t}\n\t\treturn path;\n\t}\n\tgetUpgradeReducer(documentType, fromVersion, toVersion) {\n\t\tif (toVersion !== fromVersion + 1) throw new InvalidUpgradeStepError(documentType, fromVersion, toVersion);\n\t\tconst manifest = this.getUpgradeManifest(documentType);\n\t\tconst key = `v${toVersion}`;\n\t\tif (!(key in manifest.upgrades)) throw new MissingUpgradeTransitionError(documentType, fromVersion, toVersion);\n\t\treturn manifest.upgrades[key].upgradeReducer;\n\t}\n};\n//#endregion\n//#region src/storage/kysely/keyframe-store.ts\nvar KyselyKeyframeStore = class KyselyKeyframeStore {\n\tdb;\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyKeyframeStore(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tasync putKeyframe(documentId, scope, branch, revision, document, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst write = async (trx) => {\n\t\t\tawait acquirePurgeLocks(trx, [documentId], \"shared\");\n\t\t\tif ((await findPurged(trx, [documentId])).has(documentId)) return;\n\t\t\tawait trx.insertInto(\"Keyframe\").values({\n\t\t\t\tdocumentId,\n\t\t\t\tdocumentType: document.header.documentType,\n\t\t\t\tscope,\n\t\t\t\tbranch,\n\t\t\t\trevision,\n\t\t\t\tdocument\n\t\t\t}).onConflict((oc) => oc.columns([\n\t\t\t\t\"documentId\",\n\t\t\t\t\"scope\",\n\t\t\t\t\"branch\",\n\t\t\t\t\"revision\"\n\t\t\t]).doUpdateSet({ document })).execute();\n\t\t};\n\t\tif (this.trx) {\n\t\t\tawait write(this.trx);\n\t\t\treturn;\n\t\t}\n\t\tawait this.db.transaction().execute(write);\n\t}\n\tasync findNearestKeyframe(documentId, scope, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst row = await this.queryExecutor.selectFrom(\"Keyframe\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"revision\", \"<=\", targetRevision).orderBy(\"revision\", \"desc\").limit(1).executeTakeFirst();\n\t\tif (!row) return;\n\t\treturn {\n\t\t\trevision: row.revision,\n\t\t\tdocument: row.document\n\t\t};\n\t}\n\tasync listKeyframes(documentId, scope, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.selectFrom(\"Keyframe\").selectAll().where(\"documentId\", \"=\", documentId).orderBy(\"revision\", \"asc\");\n\t\tif (scope !== void 0) query = query.where(\"scope\", \"=\", scope);\n\t\tif (branch !== void 0) query = query.where(\"branch\", \"=\", branch);\n\t\treturn (await query.execute()).map((row) => ({\n\t\t\tscope: row.scope,\n\t\t\tbranch: row.branch,\n\t\t\trevision: row.revision,\n\t\t\tdocument: row.document\n\t\t}));\n\t}\n\tasync deleteKeyframes(documentId, scope, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.deleteFrom(\"Keyframe\").where(\"documentId\", \"=\", documentId);\n\t\tif (scope !== void 0 && branch !== void 0) query = query.where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch);\n\t\telse if (scope !== void 0) query = query.where(\"scope\", \"=\", scope);\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result.numDeletedRows || 0n);\n\t}\n};\n//#endregion\n//#region src/storage/kysely/pagination.ts\nconst DEFAULT_LIMIT = 100;\nfunction paginateRows(rows, paging, cursorOf, toItem, refetch) {\n\tlet hasMore = false;\n\tlet items = rows;\n\tif (paging?.limit && rows.length > paging.limit) {\n\t\thasMore = true;\n\t\titems = rows.slice(0, paging.limit);\n\t}\n\tconst nextCursor = hasMore && items.length > 0 ? cursorOf(items[items.length - 1]).toString() : void 0;\n\tconst cursor = paging?.cursor || \"0\";\n\tconst limit = paging?.limit || DEFAULT_LIMIT;\n\treturn {\n\t\tresults: items.map(toItem),\n\t\toptions: {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t},\n\t\tnextCursor,\n\t\tnext: hasMore ? () => refetch(nextCursor, limit) : void 0\n\t};\n}\n//#endregion\n//#region src/storage/txn.ts\nvar AtomicTransaction = class {\n\tdocumentId;\n\tdocumentType;\n\tscope;\n\tbranch;\n\tbaseRevision;\n\toperations = [];\n\tconstructor(documentId, documentType, scope, branch, baseRevision) {\n\t\tthis.documentId = documentId;\n\t\tthis.documentType = documentType;\n\t\tthis.scope = scope;\n\t\tthis.branch = branch;\n\t\tthis.baseRevision = baseRevision;\n\t}\n\taddOperations(...operations) {\n\t\tfor (const op of operations) this.operations.push({\n\t\t\tjobId: v4(),\n\t\t\topId: op.id,\n\t\t\tprevOpId: \"\",\n\t\t\tdocumentId: this.documentId,\n\t\t\tdocumentType: this.documentType,\n\t\t\tscope: this.scope,\n\t\t\tbranch: this.branch,\n\t\t\ttimestampUtcMs: new Date(op.timestampUtcMs),\n\t\t\tindex: op.index,\n\t\t\taction: JSON.stringify(op.action),\n\t\t\tskip: op.skip,\n\t\t\terror: op.error || null,\n\t\t\tdeniedReason: op.deniedReason || null,\n\t\t\thash: op.hash\n\t\t});\n\t}\n\tgetOperations() {\n\t\treturn this.operations;\n\t}\n};\n//#endregion\n//#region src/storage/kysely/store.ts\nvar _UniqueConstraintContext = class extends Error {\n\tdocumentId;\n\tscope;\n\tbranch;\n\trevision;\n\tstagedOps;\n\tconstructor(documentId, scope, branch, revision, stagedOps) {\n\t\tsuper(\"unique constraint\");\n\t\tthis.documentId = documentId;\n\t\tthis.scope = scope;\n\t\tthis.branch = branch;\n\t\tthis.revision = revision;\n\t\tthis.stagedOps = stagedOps;\n\t\tthis.name = \"UniqueConstraintContext\";\n\t}\n};\nvar KyselyOperationStore = class KyselyOperationStore {\n\tdb;\n\ttrx;\n\tliveIds;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\t/** `liveIds`: ids the transaction read untombstoned under its shared lock. */\n\twithTransaction(trx, liveIds) {\n\t\tconst instance = new KyselyOperationStore(this.db);\n\t\tinstance.trx = trx;\n\t\tinstance.liveIds = liveIds;\n\t\treturn instance;\n\t}\n\tasync apply(documentId, documentType, scope, branch, revision, fn, signal, condition) {\n\t\tif (this.trx) {\n\t\t\tlet executeResult = null;\n\t\t\tlet uniqueCtx = null;\n\t\t\ttry {\n\t\t\t\texecuteResult = await this.executeApply(this.trx, documentId, documentType, scope, branch, revision, fn, signal, condition);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof _UniqueConstraintContext) uniqueCtx = error;\n\t\t\t\telse throw error;\n\t\t\t}\n\t\t\tif (uniqueCtx !== null) return this.resolveUniqueConstraint(uniqueCtx);\n\t\t\treturn executeResult;\n\t\t} else {\n\t\t\tlet transactionResult = null;\n\t\t\tlet uniqueCtx = null;\n\t\t\ttry {\n\t\t\t\ttransactionResult = await this.db.transaction().execute(async (trx) => {\n\t\t\t\t\treturn this.executeApply(trx, documentId, documentType, scope, branch, revision, fn, signal, condition);\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof _UniqueConstraintContext) uniqueCtx = error;\n\t\t\t\telse throw error;\n\t\t\t}\n\t\t\tif (uniqueCtx !== null) return this.resolveUniqueConstraint(uniqueCtx);\n\t\t\treturn transactionResult;\n\t\t}\n\t}\n\tasync resolveUniqueConstraint(ctx) {\n\t\tlet replayOps = null;\n\t\ttry {\n\t\t\treplayOps = await this.findIdempotentReplay(this.db, ctx.documentId, ctx.scope, ctx.branch, ctx.revision, ctx.stagedOps);\n\t\t} catch {}\n\t\tif (replayOps !== null) return replayOps;\n\t\tconst op = ctx.stagedOps[0];\n\t\tthrow new DuplicateOperationError(`${op.opId} at index ${op.index} with skip ${op.skip}`);\n\t}\n\tasync executeApply(trx, documentId, documentType, scope, branch, revision, fn, signal, condition) {\n\t\tthrowIfAborted(signal);\n\t\tconst atomicTxn = new AtomicTransaction(documentId, documentType, scope, branch, revision);\n\t\tawait fn(atomicTxn);\n\t\tconst operations = atomicTxn.getOperations();\n\t\tif (operations.length === 0) return [];\n\t\tconst purgedHead = this.liveIds?.has(documentId) ? void 0 : await this.refusePurgedAppend(trx, documentId, operations);\n\t\tif (purgedHead !== void 0) return purgedHead;\n\t\tif (condition) await this.acquireStreamLocks(trx, documentId, scope, branch, condition);\n\t\tconst latestOp = await trx.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).orderBy(\"index\", \"desc\").limit(1).executeTakeFirst();\n\t\tconst currentRevision = latestOp ? latestOp.index : -1;\n\t\tif (currentRevision !== revision - 1) {\n\t\t\tlet replayOps = null;\n\t\t\ttry {\n\t\t\t\treplayOps = await this.findIdempotentReplay(trx, documentId, scope, branch, revision, operations);\n\t\t\t} catch {}\n\t\t\tif (replayOps !== null) return replayOps;\n\t\t\tif (revision === 0 && this.isCreate(operations)) throw new DocumentAlreadyExistsError(documentId, scope, currentRevision);\n\t\t\tthrow new RevisionMismatchError(currentRevision + 1, revision);\n\t\t}\n\t\tlet prevOpId = latestOp?.opId || \"\";\n\t\tfor (const op of operations) {\n\t\t\top.prevOpId = prevOpId;\n\t\t\tprevOpId = op.opId;\n\t\t}\n\t\tlet insertedCount = operations.length;\n\t\ttry {\n\t\t\tif (condition && condition.streams.length > 0) insertedCount = await this.insertGuarded(trx, operations, condition);\n\t\t\telse await trx.insertInto(\"Operation\").values(operations).execute();\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message.includes(\"unique constraint\")) throw new _UniqueConstraintContext(documentId, scope, branch, revision, operations);\n\t\t\tthrow error;\n\t\t}\n\t\tif (insertedCount !== operations.length) throw new AppendConditionFailedError(condition);\n\t\treturn operations.map((op) => ({\n\t\t\tindex: op.index,\n\t\t\ttimestampUtcMs: op.timestampUtcMs.toISOString(),\n\t\t\thash: op.hash,\n\t\t\tskip: op.skip,\n\t\t\terror: op.error || void 0,\n\t\t\tdeniedReason: op.deniedReason || void 0,\n\t\t\tid: op.opId,\n\t\t\taction: JSON.parse(op.action)\n\t\t}));\n\t}\n\t/**\n\t* Locks the written stream and every read-set stream, in sorted key order\n\t* so that overlapping concurrent appends serialize rather than deadlock.\n\t* The locks are still taken one row at a time, so the query preserves that\n\t* order. It must stay separate from the guarded insert, which would\n\t* otherwise read a snapshot taken before the locks were held.\n\t*/\n\tasync acquireStreamLocks(trx, documentId, scope, branch, condition) {\n\t\tconst keys = /* @__PURE__ */ new Set([`${documentId}:${scope}:${branch}`]);\n\t\tfor (const stream of condition.streams) keys.add(`${stream.documentId}:${stream.scope}:${stream.branch}`);\n\t\tconst sortedKeys = sql.join([...keys].sort());\n\t\tawait sql`\n with ordered as materialized (\n select key\n from unnest(array[${sortedKeys}]::text[]) with ordinality as t(key, ord)\n order by ord\n )\n select pg_advisory_xact_lock(hashtext(key)) from ordered\n `.execute(trx);\n\t}\n\t/**\n\t* Inserts the staged operations with the condition compiled in as a WHERE\n\t* NOT EXISTS guard, making the check and the append one statement. Returns\n\t* the rows inserted; zero means the guard failed and nothing was written.\n\t*/\n\tasync insertGuarded(trx, operations, condition) {\n\t\tconst branches = operations.map((op) => trx.selectNoFrom([\n\t\t\tsql`${op.jobId}::text`.as(\"jobId\"),\n\t\t\tsql`${op.opId}::text`.as(\"opId\"),\n\t\t\tsql`${op.prevOpId}::text`.as(\"prevOpId\"),\n\t\t\tsql`${op.documentId}::text`.as(\"documentId\"),\n\t\t\tsql`${op.documentType}::text`.as(\"documentType\"),\n\t\t\tsql`${op.scope}::text`.as(\"scope\"),\n\t\t\tsql`${op.branch}::text`.as(\"branch\"),\n\t\t\tsql`${op.timestampUtcMs}::timestamptz`.as(\"timestampUtcMs\"),\n\t\t\tsql`${op.index}::integer`.as(\"index\"),\n\t\t\tsql`${op.action}::jsonb`.as(\"action\"),\n\t\t\tsql`${op.skip}::integer`.as(\"skip\"),\n\t\t\tsql`${op.error ?? null}::text`.as(\"error\"),\n\t\t\tsql`${op.deniedReason ?? null}::text`.as(\"deniedReason\"),\n\t\t\tsql`${op.hash}::text`.as(\"hash\")\n\t\t]).where((eb) => eb.not(eb.exists(eb.selectFrom(\"Operation\").select(\"Operation.id\").where((web) => web.or(condition.streams.map((s) => web.and([\n\t\t\tweb(\"Operation.documentId\", \"=\", s.documentId),\n\t\t\tweb(\"Operation.scope\", \"=\", s.scope),\n\t\t\tweb(\"Operation.branch\", \"=\", s.branch),\n\t\t\tweb(\"Operation.index\", \">\", s.revision)\n\t\t]))))))));\n\t\tlet expression = branches[0];\n\t\tfor (let i = 1; i < branches.length; i++) expression = expression.unionAll(branches[i]);\n\t\treturn (await trx.insertInto(\"Operation\").columns([\n\t\t\t\"jobId\",\n\t\t\t\"opId\",\n\t\t\t\"prevOpId\",\n\t\t\t\"documentId\",\n\t\t\t\"documentType\",\n\t\t\t\"scope\",\n\t\t\t\"branch\",\n\t\t\t\"timestampUtcMs\",\n\t\t\t\"index\",\n\t\t\t\"action\",\n\t\t\t\"skip\",\n\t\t\t\"error\",\n\t\t\t\"deniedReason\",\n\t\t\t\"hash\"\n\t\t]).expression(expression).returning(\"id\").execute()).length;\n\t}\n\tasync findIdempotentReplay(executor, documentId, scope, branch, revision, stagedOps) {\n\t\tconst minIndex = revision;\n\t\tconst maxIndex = revision + stagedOps.length - 1;\n\t\tconst storedRows = await executor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"index\", \">=\", minIndex).where(\"index\", \"<=\", maxIndex).orderBy(\"index\", \"asc\").execute();\n\t\tif (storedRows.length !== stagedOps.length) return null;\n\t\tfor (let i = 0; i < stagedOps.length; i++) {\n\t\t\tconst staged = stagedOps[i];\n\t\t\tconst stored = storedRows[i];\n\t\t\tif (stored.opId !== staged.opId || stored.index !== staged.index || stored.skip !== staged.skip) return null;\n\t\t}\n\t\treturn storedRows.map((row) => this.rowToOperation(row));\n\t}\n\t/** A purged stream refuses appends; a marker gets the stored one back. */\n\tasync refusePurgedAppend(trx, documentId, operations) {\n\t\tif (!(await findPurged(trx, [documentId])).has(documentId)) return;\n\t\tif (!operations.every((operation) => this.isMarker(operation))) throw new DocumentPurgedError(documentId);\n\t\treturn (await trx.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(sql`action->>'type' = ${PURGE_DOCUMENT}`).orderBy(\"index\", \"asc\").execute()).map((row) => this.rowToOperation(row));\n\t}\n\tisMarker(operation) {\n\t\treturn this.actionType(operation) === PURGE_DOCUMENT;\n\t}\n\tactionType(operation) {\n\t\tlet action = operation.action;\n\t\tif (typeof action === \"string\") try {\n\t\t\taction = JSON.parse(action);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (typeof action === \"object\" && action !== null && \"type\" in action && typeof action.type === \"string\") return action.type;\n\t}\n\t/** True when the staged write creates a document rather than appending to one. */\n\tisCreate(operations) {\n\t\tfor (const operation of operations) {\n\t\t\tlet action = operation.action;\n\t\t\tif (typeof action === \"string\") try {\n\t\t\t\taction = JSON.parse(action);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (typeof action === \"object\" && action !== null && \"type\" in action && typeof action.type === \"string\" && action.type === \"CREATE_DOCUMENT\") return true;\n\t\t}\n\t\treturn false;\n\t}\n\t/**\n\t* The paging cursor here encodes the index to resume from (one past the\n\t* last row returned), not the last row's own index. This keeps \"0\" an\n\t* unambiguous start-of-stream sentinel even when a page ends at index 0\n\t* (e.g. `limit: 1` on a fresh stream), which would otherwise make\n\t* `nextCursor` equal the start cursor and loop a caller that walks pages\n\t* forever.\n\t*/\n\tasync getSince(documentId, scope, branch, revision, filter, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"index\", \">\", revision).orderBy(\"index\", \"asc\");\n\t\tif (filter) {\n\t\t\tif (filter.actionTypes && filter.actionTypes.length > 0) {\n\t\t\t\tconst actionTypesArray = filter.actionTypes.map((t) => `'${t.replace(/'/g, \"''\")}'`).join(\",\");\n\t\t\t\tquery = query.where(sql`action->>'type' = ANY(ARRAY[${sql.raw(actionTypesArray)}]::text[])`);\n\t\t\t}\n\t\t\tif (filter.timestampFrom) query = query.where(\"timestampUtcMs\", \">=\", new Date(filter.timestampFrom));\n\t\t\tif (filter.timestampTo) query = query.where(\"timestampUtcMs\", \"<=\", new Date(filter.timestampTo));\n\t\t\tif (filter.sinceRevision !== void 0) query = query.where(\"index\", \">=\", filter.sinceRevision);\n\t\t}\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (Number.isFinite(cursorValue) && cursorValue > 0) query = query.where(\"index\", \">=\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.index + 1, (row) => this.rowToOperation(row), (cursor, limit) => this.getSince(documentId, scope, branch, revision, filter, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getSinceId(id, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"id\", \">\", id).orderBy(\"id\", \"asc\");\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (cursorValue > 0) query = query.where(\"id\", \">\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.id, (row) => this.rowToOperationWithContext(row), (cursor, limit) => this.getSinceId(id, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\t/**\n\t* The paging cursor here encodes the index to resume from (one past the\n\t* last row returned), not the last row's own index, for the same reason as\n\t* `getSince`: a page ending at index 0 must not produce a cursor that is\n\t* indistinguishable from the start-of-stream sentinel.\n\t*/\n\tasync getConflicting(documentId, scope, branch, minTimestamp, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"timestampUtcMs\", \">=\", new Date(minTimestamp)).orderBy(\"index\", \"asc\");\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (Number.isFinite(cursorValue) && cursorValue > 0) query = query.where(\"index\", \">=\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.index + 1, (row) => this.rowToOperation(row), (cursor, limit) => this.getConflicting(documentId, scope, branch, minTimestamp, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getRevisions(documentId, branch, signal) {\n\t\tthrowIfAborted(signal);\n\t\tconst scopeRevisions = await this.queryExecutor.selectFrom(\"Operation\").select(\"scope\").select((eb) => eb.fn.max(\"index\").as(\"index\")).where(\"documentId\", \"=\", documentId).where(\"branch\", \"=\", branch).groupBy(\"scope\").execute();\n\t\tconst latest = await this.queryExecutor.selectFrom(\"Operation\").select((eb) => eb.fn.max(\"timestampUtcMs\").as(\"latestTimestamp\")).where(\"documentId\", \"=\", documentId).where(\"branch\", \"=\", branch).executeTakeFirst();\n\t\tconst revision = {};\n\t\tfor (const row of scopeRevisions) revision[row.scope] = row.index + 1;\n\t\treturn {\n\t\t\trevision,\n\t\t\tlatestTimestamp: latest?.latestTimestamp ? new Date(latest.latestTimestamp).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString()\n\t\t};\n\t}\n\tasync getStreamLatestTimestamp(documentId, scope, branch, signal) {\n\t\tconst latest = await this.queryExecutor.selectFrom(\"Operation\").select((eb) => eb.fn.max(\"timestampUtcMs\").as(\"latestTimestamp\")).where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).executeTakeFirst();\n\t\treturn latest?.latestTimestamp ? new Date(latest.latestTimestamp).toISOString() : void 0;\n\t}\n\tasync findOperationIds(documentId, scope, branch, opIds, signal) {\n\t\tthrowIfAborted(signal);\n\t\tif (opIds.length === 0) return /* @__PURE__ */ new Set();\n\t\tconst rows = await this.queryExecutor.selectFrom(\"Operation\").select(\"opId\").distinct().where(\"opId\", \"in\", opIds).where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).execute();\n\t\treturn new Set(rows.map((row) => row.opId));\n\t}\n\tasync getOperationsByIds(documentId, scope, branch, opIds, signal) {\n\t\tthrowIfAborted(signal);\n\t\tif (opIds.length === 0) return [];\n\t\tconst rows = await this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"opId\", \"in\", opIds).where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).orderBy(\"index\", \"asc\").execute();\n\t\tconst latest = /* @__PURE__ */ new Map();\n\t\tfor (const row of rows) latest.set(row.opId, this.rowToOperation(row));\n\t\treturn [...latest.values()];\n\t}\n\trowToOperation(row) {\n\t\treturn {\n\t\t\tindex: row.index,\n\t\t\ttimestampUtcMs: row.timestampUtcMs.toISOString(),\n\t\t\thash: row.hash,\n\t\t\tskip: row.skip,\n\t\t\terror: row.error || void 0,\n\t\t\tdeniedReason: row.deniedReason || void 0,\n\t\t\tid: row.opId,\n\t\t\taction: row.action\n\t\t};\n\t}\n\trowToOperationWithContext(row) {\n\t\treturn {\n\t\t\toperation: this.rowToOperation(row),\n\t\t\tcontext: {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tscope: row.scope,\n\t\t\t\tbranch: row.branch,\n\t\t\t\tordinal: row.id\n\t\t\t}\n\t\t};\n\t}\n};\n//#endregion\n//#region src/storage/pool-instrumentation.ts\n/**\n* Wraps an existing pg.Pool with acquire-wait timing and an event\n* subscription surface. The pool is mutated in place: pool.connect()\n* is replaced with a timing wrapper so all callers (Kysely included)\n* pick up the instrumentation transparently.\n*/\nfunction instrumentPgPool(pool, name) {\n\tconst listeners = /* @__PURE__ */ new Set();\n\tconst originalConnect = pool.connect.bind(pool);\n\tconst wrappedConnect = async () => {\n\t\tconst start = performance.now();\n\t\tconst client = await originalConnect();\n\t\tconst durationMs = performance.now() - start;\n\t\tfor (const listener of listeners) try {\n\t\t\tlistener(durationMs);\n\t\t} catch {}\n\t\treturn client;\n\t};\n\tpool.connect = wrappedConnect;\n\treturn {\n\t\tname,\n\t\tgetStats() {\n\t\t\treturn {\n\t\t\t\tsize: pool.totalCount,\n\t\t\t\tidle: pool.idleCount,\n\t\t\t\twaiting: pool.waitingCount\n\t\t\t};\n\t\t},\n\t\tonAcquire(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t}\n\t};\n}\nfunction createForwardingPoolInstrumentation(name) {\n\tconst listeners = /* @__PURE__ */ new Set();\n\tlet stats = {\n\t\tsize: 0,\n\t\tidle: 0,\n\t\twaiting: 0\n\t};\n\treturn {\n\t\tname,\n\t\tgetStats() {\n\t\t\treturn stats;\n\t\t},\n\t\tonAcquire(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tpushSamples(durations) {\n\t\t\tfor (const durationMs of durations) for (const listener of listeners) try {\n\t\t\t\tlistener(durationMs);\n\t\t\t} catch {}\n\t\t},\n\t\tupdateStats(next) {\n\t\t\tstats = next;\n\t\t}\n\t};\n}\n//#endregion\n//#region src/storage/migrations/001_create_operation_table.ts\nvar _001_create_operation_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$25 });\nasync function up$25(db) {\n\tawait db.schema.createTable(\"Operation\").addColumn(\"id\", \"serial\", (col) => col.primaryKey()).addColumn(\"jobId\", \"text\", (col) => col.notNull()).addColumn(\"opId\", \"text\", (col) => col.notNull()).addColumn(\"prevOpId\", \"text\", (col) => col.notNull()).addColumn(\"writeTimestampUtcMs\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"timestampUtcMs\", \"timestamptz\", (col) => col.notNull()).addColumn(\"index\", \"integer\", (col) => col.notNull()).addColumn(\"action\", \"jsonb\", (col) => col.notNull()).addColumn(\"skip\", \"integer\", (col) => col.notNull()).addColumn(\"error\", \"text\").addColumn(\"hash\", \"text\", (col) => col.notNull()).addUniqueConstraint(\"unique_revision\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"index\"\n\t]).addUniqueConstraint(\"unique_operation_instance\", [\n\t\t\"opId\",\n\t\t\"index\",\n\t\t\"skip\"\n\t]).execute();\n\tawait db.schema.createIndex(\"streamOperations\").on(\"Operation\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"id\"\n\t]).execute();\n\tawait db.schema.createIndex(\"branchlessStreamOperations\").on(\"Operation\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"id\"\n\t]).execute();\n}\n//#endregion\n//#region src/storage/migrations/002_create_keyframe_table.ts\nvar _002_create_keyframe_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$24 });\nasync function up$24(db) {\n\tawait db.schema.createTable(\"Keyframe\").addColumn(\"id\", \"serial\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"revision\", \"integer\", (col) => col.notNull()).addColumn(\"document\", \"jsonb\", (col) => col.notNull()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_keyframe\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"revision\"\n\t]).execute();\n\tawait db.schema.createIndex(\"keyframe_lookup\").on(\"Keyframe\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"revision\"\n\t]).execute();\n}\n//#endregion\n//#region src/storage/migrations/003_create_document_table.ts\nvar _003_create_document_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$23 });\nasync function up$23(db) {\n\tawait db.schema.createTable(\"Document\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/004_create_document_relationship_table.ts\nvar _004_create_document_relationship_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$22 });\nasync function up$22(db) {\n\tawait db.schema.createTable(\"DocumentRelationship\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"sourceId\", \"text\", (col) => col.notNull().references(\"Document.id\").onDelete(\"cascade\")).addColumn(\"targetId\", \"text\", (col) => col.notNull().references(\"Document.id\").onDelete(\"cascade\")).addColumn(\"relationshipType\", \"text\", (col) => col.notNull()).addColumn(\"metadata\", \"jsonb\").addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_source_target_type\", [\n\t\t\"sourceId\",\n\t\t\"targetId\",\n\t\t\"relationshipType\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_relationship_source\").on(\"DocumentRelationship\").column(\"sourceId\").execute();\n\tawait db.schema.createIndex(\"idx_relationship_target\").on(\"DocumentRelationship\").column(\"targetId\").execute();\n\tawait db.schema.createIndex(\"idx_relationship_type\").on(\"DocumentRelationship\").column(\"relationshipType\").execute();\n}\n//#endregion\n//#region src/storage/migrations/005_create_indexer_state_table.ts\nvar _005_create_indexer_state_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$21 });\nasync function up$21(db) {\n\tawait db.schema.createTable(\"IndexerState\").addColumn(\"id\", \"integer\", (col) => col.primaryKey().generatedAlwaysAsIdentity()).addColumn(\"lastOperationId\", \"integer\", (col) => col.notNull()).addColumn(\"lastOperationTimestamp\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/006_create_document_snapshot_table.ts\nvar _006_create_document_snapshot_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$20 });\nasync function up$20(db) {\n\tawait db.schema.createTable(\"DocumentSnapshot\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"slug\", \"text\").addColumn(\"name\", \"text\").addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"content\", \"jsonb\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"lastOperationIndex\", \"integer\", (col) => col.notNull()).addColumn(\"lastOperationHash\", \"text\", (col) => col.notNull()).addColumn(\"lastUpdatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"snapshotVersion\", \"integer\", (col) => col.notNull().defaultTo(1)).addColumn(\"identifiers\", \"jsonb\").addColumn(\"metadata\", \"jsonb\").addColumn(\"isDeleted\", \"boolean\", (col) => col.notNull().defaultTo(false)).addColumn(\"deletedAt\", \"timestamptz\").addUniqueConstraint(\"unique_doc_scope_branch\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_slug_scope_branch\").on(\"DocumentSnapshot\").columns([\n\t\t\"slug\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_doctype_scope_branch\").on(\"DocumentSnapshot\").columns([\n\t\t\"documentType\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_last_updated\").on(\"DocumentSnapshot\").column(\"lastUpdatedAt\").execute();\n\tawait db.schema.createIndex(\"idx_is_deleted\").on(\"DocumentSnapshot\").column(\"isDeleted\").execute();\n}\n//#endregion\n//#region src/storage/migrations/007_create_slug_mapping_table.ts\nvar _007_create_slug_mapping_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$19 });\nasync function up$19(db) {\n\tawait db.schema.createTable(\"SlugMapping\").addColumn(\"slug\", \"text\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_docid_scope_branch\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_slug_documentid\").on(\"SlugMapping\").column(\"documentId\").execute();\n}\n//#endregion\n//#region src/storage/migrations/008_create_view_state_table.ts\nvar _008_create_view_state_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$18 });\nasync function up$18(db) {\n\tawait db.schema.createTable(\"ViewState\").addColumn(\"readModelId\", \"text\", (col) => col.primaryKey()).addColumn(\"lastOrdinal\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"lastOperationTimestamp\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/009_create_operation_index_tables.ts\nvar _009_create_operation_index_tables_exports = /* @__PURE__ */ __exportAll({ up: () => up$17 });\nasync function up$17(db) {\n\tawait db.schema.createTable(\"document_collections\").addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"collectionId\", \"text\", (col) => col.notNull()).addColumn(\"joinedOrdinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"leftOrdinal\", \"bigint\").addPrimaryKeyConstraint(\"document_collections_pkey\", [\"documentId\", \"collectionId\"]).execute();\n\tawait db.schema.createIndex(\"idx_document_collections_collectionId\").on(\"document_collections\").column(\"collectionId\").execute();\n\tawait db.schema.createIndex(\"idx_doc_collections_collection_range\").on(\"document_collections\").columns([\"collectionId\", \"joinedOrdinal\"]).execute();\n\tawait db.schema.createTable(\"operation_index_operations\").addColumn(\"ordinal\", \"serial\", (col) => col.primaryKey()).addColumn(\"opId\", \"text\", (col) => col.notNull()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"timestampUtcMs\", \"text\", (col) => col.notNull()).addColumn(\"writeTimestampUtcMs\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"index\", \"integer\", (col) => col.notNull()).addColumn(\"skip\", \"integer\", (col) => col.notNull()).addColumn(\"hash\", \"text\", (col) => col.notNull()).addColumn(\"action\", \"jsonb\", (col) => col.notNull()).execute();\n\tawait db.schema.createIndex(\"idx_operation_index_operations_document\").on(\"operation_index_operations\").columns([\n\t\t\"documentId\",\n\t\t\"branch\",\n\t\t\"scope\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_operation_index_operations_ordinal\").on(\"operation_index_operations\").column(\"ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/010_create_sync_tables.ts\nvar _010_create_sync_tables_exports = /* @__PURE__ */ __exportAll({ up: () => up$16 });\nasync function up$16(db) {\n\tawait db.schema.createTable(\"sync_remotes\").addColumn(\"name\", \"text\", (col) => col.primaryKey()).addColumn(\"collection_id\", \"text\", (col) => col.notNull()).addColumn(\"channel_type\", \"text\", (col) => col.notNull()).addColumn(\"channel_id\", \"text\", (col) => col.notNull().defaultTo(\"\")).addColumn(\"remote_name\", \"text\", (col) => col.notNull().defaultTo(\"\")).addColumn(\"channel_parameters\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'{}'::jsonb`)).addColumn(\"filter_document_ids\", \"jsonb\").addColumn(\"filter_scopes\", \"jsonb\").addColumn(\"filter_branch\", \"text\", (col) => col.notNull().defaultTo(\"main\")).addColumn(\"push_state\", \"text\", (col) => col.notNull().defaultTo(\"idle\")).addColumn(\"push_last_success_utc_ms\", \"text\").addColumn(\"push_last_failure_utc_ms\", \"text\").addColumn(\"push_failure_count\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"pull_state\", \"text\", (col) => col.notNull().defaultTo(\"idle\")).addColumn(\"pull_last_success_utc_ms\", \"text\").addColumn(\"pull_last_failure_utc_ms\", \"text\").addColumn(\"pull_failure_count\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"created_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_remotes_collection\").on(\"sync_remotes\").column(\"collection_id\").execute();\n\tawait db.schema.createTable(\"sync_cursors\").addColumn(\"remote_name\", \"text\", (col) => col.primaryKey().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"cursor_ordinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"last_synced_at_utc_ms\", \"text\").addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_cursors_ordinal\").on(\"sync_cursors\").column(\"cursor_ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/011_add_cursor_type_column.ts\nvar _011_add_cursor_type_column_exports = /* @__PURE__ */ __exportAll({ up: () => up$15 });\nasync function up$15(db) {\n\tawait db.deleteFrom(\"sync_cursors\").where(\"remote_name\", \"like\", \"outbox::%\").execute();\n\tawait db.deleteFrom(\"sync_remotes\").where(\"name\", \"like\", \"outbox::%\").execute();\n\tawait db.schema.dropTable(\"sync_cursors\").execute();\n\tawait db.schema.createTable(\"sync_cursors\").addColumn(\"remote_name\", \"text\", (col) => col.notNull()).addColumn(\"cursor_type\", \"text\", (col) => col.notNull().defaultTo(\"inbox\")).addColumn(\"cursor_ordinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"last_synced_at_utc_ms\", \"text\").addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addPrimaryKeyConstraint(\"sync_cursors_pk\", [\"remote_name\", \"cursor_type\"]).execute();\n\tawait db.schema.createIndex(\"idx_sync_cursors_ordinal\").on(\"sync_cursors\").column(\"cursor_ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/012_add_source_remote_column.ts\nvar _012_add_source_remote_column_exports = /* @__PURE__ */ __exportAll({ up: () => up$14 });\nasync function up$14(db) {\n\tawait db.schema.alterTable(\"operation_index_operations\").addColumn(\"sourceRemote\", \"text\", (col) => col.notNull().defaultTo(\"\")).execute();\n}\n//#endregion\n//#region src/storage/migrations/013_create_sync_dead_letters_table.ts\nvar _013_create_sync_dead_letters_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$13 });\nasync function up$13(db) {\n\tawait db.schema.createTable(\"sync_dead_letters\").addColumn(\"ordinal\", \"serial\", (col) => col.primaryKey()).addColumn(\"id\", \"text\", (col) => col.unique().notNull()).addColumn(\"job_id\", \"text\", (col) => col.notNull()).addColumn(\"job_dependencies\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"remote_name\", \"text\", (col) => col.notNull().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"document_id\", \"text\", (col) => col.notNull()).addColumn(\"scopes\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"operations\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"error_source\", \"text\", (col) => col.notNull()).addColumn(\"error_message\", \"text\", (col) => col.notNull()).addColumn(\"created_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_dead_letters_remote\").on(\"sync_dead_letters\").column(\"remote_name\").execute();\n}\n//#endregion\n//#region src/storage/migrations/014_create_processor_cursor_table.ts\nvar _014_create_processor_cursor_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$12 });\nasync function up$12(db) {\n\tawait db.schema.createTable(\"ProcessorCursor\").addColumn(\"processorId\", \"text\", (col) => col.primaryKey()).addColumn(\"factoryId\", \"text\", (col) => col.notNull()).addColumn(\"driveId\", \"text\", (col) => col.notNull()).addColumn(\"processorIndex\", \"integer\", (col) => col.notNull()).addColumn(\"lastOrdinal\", \"integer\", (col) => col.notNull().defaultTo(sql`0`)).addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(sql`'active'`)).addColumn(\"lastError\", \"text\").addColumn(\"lastErrorTimestamp\", \"timestamptz\").addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/015_add_operation_denied_reason.ts\nvar _015_add_operation_denied_reason_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$11,\n\tup: () => up$11\n});\n/**\n* Records why authorization refused an operation. Separate from `error` so a\n* denial is distinguishable from a reducer failure without matching on a\n* message. Null for every operation written before decisions were enforced.\n*/\nasync function up$11(db) {\n\tawait db.schema.alterTable(\"Operation\").addColumn(\"deniedReason\", \"text\").execute();\n\tawait db.schema.alterTable(\"operation_index_operations\").addColumn(\"deniedReason\", \"text\").execute();\n}\nasync function down$11(db) {\n\tawait db.schema.alterTable(\"operation_index_operations\").dropColumn(\"deniedReason\").execute();\n\tawait db.schema.alterTable(\"Operation\").dropColumn(\"deniedReason\").execute();\n}\n//#endregion\n//#region src/storage/migrations/016_add_dead_letter_error_type.ts\nvar _016_add_dead_letter_error_type_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$10,\n\tup: () => up$10\n});\n/**\n* The classification a dead letter falls into, stored because it decides whether\n* the document stays quarantined and the in-memory error is gone after a restart.\n* Defaulted rather than nullable, so a pre-existing row rehydrates.\n*/\nasync function up$10(db) {\n\tawait db.schema.alterTable(\"sync_dead_letters\").addColumn(\"error_type\", \"text\", (col) => col.notNull().defaultTo(\"UNCLASSIFIED\")).execute();\n}\nasync function down$10(db) {\n\tawait db.schema.alterTable(\"sync_dead_letters\").dropColumn(\"error_type\").execute();\n}\n//#endregion\n//#region src/storage/migrations/017_create_group_references.ts\nvar _017_create_group_references_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$9,\n\tup: () => up$9\n});\n/**\n* One row per (document, group) reference ever discovered from an auth\n* operation's input. Rows are never updated or deleted: auth evaluation is\n* positional, so a grant that named a group at any position keeps that\n* group's stream in the document's read-set even after a later operation\n* removes the reference. Read by documentId for the groups a document\n* requires (sync), and by groupId for the documents a group change affects\n* (re-evaluation).\n*/\nasync function up$9(db) {\n\tawait db.schema.createTable(\"group_references\").addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"groupId\", \"text\", (col) => col.notNull()).addPrimaryKeyConstraint(\"group_references_pkey\", [\"documentId\", \"groupId\"]).execute();\n\tawait db.schema.createIndex(\"idx_group_references_groupId\").on(\"group_references\").column(\"groupId\").execute();\n}\nasync function down$9(db) {\n\tawait db.schema.dropTable(\"group_references\").execute();\n}\n//#endregion\n//#region src/storage/migrations/018_add_sync_remote_bound_address.ts\nvar _018_add_sync_remote_bound_address_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$8,\n\tup: () => up$8\n});\n/**\n* The address a sync channel is bound to, so a channel created by one subject\n* cannot be polled by another.\n*\n* Nullable rather than defaulted: null is a channel nobody has claimed, which is\n* what every pre-existing row is and what an anonymously created channel stays\n* until its first authenticated poll adopts it. A default would claim them all\n* for one address.\n*/\nasync function up$8(db) {\n\tawait db.schema.alterTable(\"sync_remotes\").addColumn(\"bound_address\", \"text\").execute();\n}\nasync function down$8(db) {\n\tawait db.schema.alterTable(\"sync_remotes\").dropColumn(\"bound_address\").execute();\n}\n//#endregion\n//#region src/storage/migrations/019_require_action_id.ts\nvar _019_require_action_id_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$7,\n\tup: () => up$7\n});\n/**\n* Makes an operation whose action carries no id physically unstorable.\n*\n* The id is not decoration: `deriveOperationId` hashes it into the operation id\n* and replay dedupes incoming operations by it, so an action without one\n* collapses every id-less operation on a document/scope/branch onto a single\n* derived operation id. The API rejects such an action now, and this is the\n* last line of defense behind it.\n*\n* Both tables are constrained because sync reads operations from the index\n* rather than the operation table, so poison reaching only the index would\n* still be served to a replica.\n*\n* Pre-existing rows are backfilled rather than left behind a NOT VALID\n* constraint: a row the index and the operation table disagree about is worse\n* than a missing id, because dedup keys off the value each side serves. The\n* backfill therefore mints one id per operation and writes that same id to both\n* tables, joined on the identity they share. Rewriting the action is safe: the\n* operation hash is taken over the resulting state, not over the action, and a\n* signature is verified from the params carried in the signature tuple, which\n* do not include the action id.\n*\n* The empty string is rejected alongside null. It derives the same colliding\n* operation id as an absent id, so admitting it would leave the hole open.\n*/\nasync function up$7(db) {\n\tawait db.updateTable(\"Operation\").set({ action: sql`jsonb_set(action, '{id}', to_jsonb(gen_random_uuid()::text))` }).where(sql`jsonb_typeof(action) = 'object' and coalesce(action->>'id', '') = ''`).execute();\n\tawait db.updateTable(\"operation_index_operations as oio\").from(\"Operation as op\").set({ action: sql`jsonb_set(oio.action, '{id}', to_jsonb(op.action->>'id'))` }).whereRef(\"oio.opId\", \"=\", \"op.opId\").whereRef(\"oio.index\", \"=\", \"op.index\").whereRef(\"oio.skip\", \"=\", \"op.skip\").where(sql`jsonb_typeof(oio.action) = 'object' and coalesce(oio.action->>'id', '') = ''`).where(sql`coalesce(op.action->>'id', '') <> ''`).execute();\n\tawait db.updateTable(\"operation_index_operations\").set({ action: sql`jsonb_set(action, '{id}', to_jsonb(gen_random_uuid()::text))` }).where(sql`jsonb_typeof(action) = 'object' and coalesce(action->>'id', '') = ''`).execute();\n\tawait db.schema.alterTable(\"Operation\").addCheckConstraint(\"action_must_have_id\", sql`action->>'id' is not null and action->>'id' <> ''`).execute();\n\tawait db.schema.alterTable(\"operation_index_operations\").addCheckConstraint(\"action_must_have_id\", sql`action->>'id' is not null and action->>'id' <> ''`).execute();\n}\n/**\n* Only the constraints are dropped. The backfilled ids stay: they are the ids\n* their operations are now known by, and reverting them would reintroduce the\n* collision the migration removed.\n*/\nasync function down$7(db) {\n\tawait db.schema.alterTable(\"operation_index_operations\").dropConstraint(\"action_must_have_id\").execute();\n\tawait db.schema.alterTable(\"Operation\").dropConstraint(\"action_must_have_id\").execute();\n}\n//#endregion\n//#region src/storage/migrations/020_add_snapshot_operation_ordinal.ts\nvar _020_add_snapshot_operation_ordinal_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$6,\n\tup: () => up$6\n});\n/** Orders header row writes across scopes; `lastOperationIndex` is per scope. */\nasync function up$6(db) {\n\tawait db.schema.alterTable(\"DocumentSnapshot\").addColumn(\"lastOperationOrdinal\", \"integer\", (col) => col.notNull().defaultTo(0)).execute();\n}\nasync function down$6(db) {\n\tawait db.schema.alterTable(\"DocumentSnapshot\").dropColumn(\"lastOperationOrdinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/021_add_sync_remote_peer.ts\nvar _021_add_sync_remote_peer_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$5,\n\tup: () => up$5\n});\n/**\n* The peer's manifest as canonical JSON, and when it was heard. Both null: not\n* yet heard. A time with no manifest: a silent peer, which gets the baselines.\n*/\nasync function up$5(db) {\n\tawait db.schema.alterTable(\"sync_remotes\").addColumn(\"peer_manifest\", \"text\").addColumn(\"peer_manifest_at_utc_ms\", \"bigint\").execute();\n}\nasync function down$5(db) {\n\tawait db.schema.alterTable(\"sync_remotes\").dropColumn(\"peer_manifest\").dropColumn(\"peer_manifest_at_utc_ms\").execute();\n}\n//#endregion\n//#region src/storage/migrations/022_create_sync_holds.ts\nvar _022_create_sync_holds_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$4,\n\tup: () => up$4\n});\n/** Documents held back from a remote whose peer cannot run their versions. */\nasync function up$4(db) {\n\tawait db.schema.createTable(\"sync_holds\").addColumn(\"remote_name\", \"text\", (col) => col.notNull().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"document_id\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"protocol\", \"text\", (col) => col.notNull()).addColumn(\"version\", \"integer\", (col) => col.notNull()).addColumn(\"held_at_utc_ms\", \"bigint\", (col) => col.notNull()).addPrimaryKeyConstraint(\"sync_holds_pkey\", [\n\t\t\"remote_name\",\n\t\t\"document_id\",\n\t\t\"branch\"\n\t]).execute();\n}\nasync function down$4(db) {\n\tawait db.schema.dropTable(\"sync_holds\").execute();\n}\n//#endregion\n//#region src/storage/migrations/023_index_created_protocol_versions.ts\nvar _023_index_created_protocol_versions_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$3,\n\tup: () => up$3\n});\n/**\n* One entry per document created with protocolVersions, keyed by a hash so an\n* oversized header cannot make its creation unstorable. Startup reads the\n* distinct values without visiting every document.\n*/\nasync function up$3(db) {\n\tawait db.schema.createIndex(\"idx_operation_created_protocol_versions\").on(\"Operation\").expression(sql`md5((action->'input'->'protocolVersions')::text)`).where(sql`scope = 'document' and \"index\" = 0 and (action->'input'->'protocolVersions') is not null`).execute();\n}\nasync function down$3(db) {\n\tawait db.schema.dropIndex(\"idx_operation_created_protocol_versions\").execute();\n}\n//#endregion\n//#region src/storage/migrations/024_create_document_purges.ts\nvar _024_create_document_purges_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$2,\n\tup: () => up$2\n});\n/** One row per purged document: the tombstone. Written once, never deleted. */\nasync function up$2(db) {\n\tawait db.schema.createTable(\"document_purges\").addColumn(\"documentId\", \"text\", (col) => col.primaryKey()).addColumn(\"ordinal\", \"bigint\", (col) => col.notNull()).addColumn(\"removedRows\", \"jsonb\", (col) => col.notNull()).addColumn(\"purgedAtUtc\", \"timestamptz\", (col) => col.notNull()).addColumn(\"requestId\", \"text\", (col) => col.notNull()).execute();\n}\nasync function down$2(db) {\n\tawait db.schema.dropTable(\"document_purges\").execute();\n}\n//#endregion\n//#region src/storage/migrations/025_create_sync_received_markers.ts\nvar _025_create_sync_received_markers_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$1,\n\tup: () => up$1\n});\n/** Received purge markers awaiting their outcome; removed with their remote. */\nasync function up$1(db) {\n\tawait db.schema.createTable(\"sync_received_markers\").addColumn(\"remote_name\", \"text\", (col) => col.notNull()).addColumn(\"marker_id\", \"text\", (col) => col.notNull()).addColumn(\"document_id\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"operation\", \"jsonb\", (col) => col.notNull()).addColumn(\"received_at_utc_ms\", \"bigint\", (col) => col.notNull()).addPrimaryKeyConstraint(\"sync_received_markers_pkey\", [\"remote_name\", \"marker_id\"]).execute();\n}\nasync function down$1(db) {\n\tawait db.schema.dropTable(\"sync_received_markers\").execute();\n}\n//#endregion\n//#region src/storage/migrations/026_create_sync_purge_refusals.ts\nvar _026_create_sync_purge_refusals_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down,\n\tup: () => up\n});\n/** A remote's refusal of a purge marker; payload-free, kept like the tombstone. */\nasync function up(db) {\n\tawait db.schema.createTable(\"sync_purge_refusals\").addColumn(\"remote_name\", \"text\", (col) => col.notNull()).addColumn(\"document_id\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"refused_at_utc_ms\", \"bigint\", (col) => col.notNull()).addPrimaryKeyConstraint(\"sync_purge_refusals_pkey\", [\n\t\t\"remote_name\",\n\t\t\"document_id\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_sync_purge_refusals_document\").on(\"sync_purge_refusals\").column(\"document_id\").execute();\n}\nasync function down(db) {\n\tawait db.schema.dropTable(\"sync_purge_refusals\").execute();\n}\n//#endregion\n//#region src/storage/migrations/migrator.ts\nconst REACTOR_SCHEMA = \"reactor\";\nconst migrations = {\n\t\"001_create_operation_table\": _001_create_operation_table_exports,\n\t\"002_create_keyframe_table\": _002_create_keyframe_table_exports,\n\t\"003_create_document_table\": _003_create_document_table_exports,\n\t\"004_create_document_relationship_table\": _004_create_document_relationship_table_exports,\n\t\"005_create_indexer_state_table\": _005_create_indexer_state_table_exports,\n\t\"006_create_document_snapshot_table\": _006_create_document_snapshot_table_exports,\n\t\"007_create_slug_mapping_table\": _007_create_slug_mapping_table_exports,\n\t\"008_create_view_state_table\": _008_create_view_state_table_exports,\n\t\"009_create_operation_index_tables\": _009_create_operation_index_tables_exports,\n\t\"010_create_sync_tables\": _010_create_sync_tables_exports,\n\t\"011_add_cursor_type_column\": _011_add_cursor_type_column_exports,\n\t\"012_add_source_remote_column\": _012_add_source_remote_column_exports,\n\t\"013_create_sync_dead_letters_table\": _013_create_sync_dead_letters_table_exports,\n\t\"014_create_processor_cursor_table\": _014_create_processor_cursor_table_exports,\n\t\"015_add_operation_denied_reason\": _015_add_operation_denied_reason_exports,\n\t\"016_add_dead_letter_error_type\": _016_add_dead_letter_error_type_exports,\n\t\"017_create_group_references\": _017_create_group_references_exports,\n\t\"018_add_sync_remote_bound_address\": _018_add_sync_remote_bound_address_exports,\n\t\"019_require_action_id\": _019_require_action_id_exports,\n\t\"020_add_snapshot_operation_ordinal\": _020_add_snapshot_operation_ordinal_exports,\n\t\"021_add_sync_remote_peer\": _021_add_sync_remote_peer_exports,\n\t\"022_create_sync_holds\": _022_create_sync_holds_exports,\n\t\"023_index_created_protocol_versions\": _023_index_created_protocol_versions_exports,\n\t\"024_create_document_purges\": _024_create_document_purges_exports,\n\t\"025_create_sync_received_markers\": _025_create_sync_received_markers_exports,\n\t\"026_create_sync_purge_refusals\": _026_create_sync_purge_refusals_exports\n};\nvar ProgrammaticMigrationProvider = class {\n\tgetMigrations() {\n\t\treturn Promise.resolve(migrations);\n\t}\n};\n/**\n* Applies every pending migration, or every one up to and including `upTo`.\n*\n* The bound exists so a test can reach the schema a data migration is written\n* against, populate it, and then migrate across the migration under test.\n*/\nasync function runMigrations(db, schema = REACTOR_SCHEMA, upTo) {\n\ttry {\n\t\tawait sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(schema)}`.execute(db);\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tmigrationsExecuted: [],\n\t\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Failed to create schema\")\n\t\t};\n\t}\n\tconst migrator = new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema\n\t});\n\tlet error;\n\tlet results;\n\ttry {\n\t\tconst result = upTo ? await migrator.migrateTo(upTo) : await migrator.migrateToLatest();\n\t\terror = result.error;\n\t\tresults = result.results;\n\t} catch (e) {\n\t\terror = e;\n\t\tresults = [];\n\t}\n\tconst migrationsExecuted = results?.map((result) => result.migrationName) ?? [];\n\tif (error) return {\n\t\tsuccess: false,\n\t\tmigrationsExecuted,\n\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Unknown migration error\")\n\t};\n\treturn {\n\t\tsuccess: true,\n\t\tmigrationsExecuted\n\t};\n}\nasync function getMigrationStatus(db, schema = REACTOR_SCHEMA) {\n\treturn await new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema\n\t}).getMigrations();\n}\n//#endregion\n//#region src/core/drive-container-types.ts\nconst DEFAULT_DRIVE_CONTAINER_TYPES = /* @__PURE__ */ new Set([\"powerhouse/document-drive\", \"powerhouse/reactor-drive\"]);\n//#endregion\n//#region src/executor/worker/error-info.ts\nconst MAX_STACK_LENGTH = 8192;\nconst MAX_CAUSE_DEPTH = 8;\nfunction toErrorInfo(err, depth = 0) {\n\tif (depth > MAX_CAUSE_DEPTH) return {\n\t\tname: \"Error\",\n\t\tmessage: \"cause chain truncated\"\n\t};\n\tif (err instanceof Error) {\n\t\tconst info = {\n\t\t\tname: err.name || \"Error\",\n\t\t\tmessage: err.message\n\t\t};\n\t\tif (typeof err.stack === \"string\") info.stack = err.stack.length > MAX_STACK_LENGTH ? err.stack.slice(0, MAX_STACK_LENGTH) : err.stack;\n\t\tif (err.cause !== void 0) info.cause = toErrorInfo(err.cause, depth + 1);\n\t\tconst documentId = err.documentId;\n\t\tif (typeof documentId === \"string\") info.documentId = documentId;\n\t\tconst { documentType, requestedVersion } = err;\n\t\tif (typeof documentType === \"string\") info.documentType = documentType;\n\t\tif (typeof requestedVersion === \"number\") info.requestedVersion = requestedVersion;\n\t\treturn info;\n\t}\n\tif (typeof err === \"string\") return {\n\t\tname: \"Error\",\n\t\tmessage: err\n\t};\n\tif (err && typeof err === \"object\") {\n\t\tconst record = err;\n\t\treturn {\n\t\t\tname: typeof record.name === \"string\" ? record.name : \"Error\",\n\t\t\tmessage: typeof record.message === \"string\" ? record.message : safeStringify(err)\n\t\t};\n\t}\n\treturn {\n\t\tname: \"Error\",\n\t\tmessage: safeStringify(err)\n\t};\n}\nfunction safeStringify(value) {\n\tif (value === null || value === void 0) return String(value);\n\tif (typeof value === \"string\") return value;\n\tif (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\nfunction fromErrorInfo(info) {\n\tconst err = new Error(info.message);\n\tObject.defineProperty(err, \"name\", {\n\t\tvalue: info.name,\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n\tif (info.stack !== void 0) err.stack = info.stack;\n\tif (info.documentId !== void 0) Object.defineProperty(err, \"documentId\", {\n\t\tvalue: info.documentId,\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n\tfor (const key of [\"documentType\", \"requestedVersion\"]) if (info[key] !== void 0) Object.defineProperty(err, key, {\n\t\tvalue: info[key],\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n\tif (info.cause !== void 0) Object.defineProperty(err, \"cause\", {\n\t\tvalue: fromErrorInfo(info.cause),\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n\treturn err;\n}\n//#endregion\n//#region src/executor/worker/sanitize.ts\nconst MAX_DEPTH = 8;\nfunction errorToInfo(err) {\n\treturn toErrorInfo(err);\n}\nfunction sanitizeArg(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {\n\tif (depth > MAX_DEPTH) return \"[Truncated]\";\n\tif (value === null || value === void 0) return null;\n\tif (typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") return value;\n\tif (typeof value === \"string\") return value;\n\tif (typeof value === \"bigint\") return value.toString();\n\tif (typeof value === \"function\" || typeof value === \"symbol\") return null;\n\tif (value instanceof Error) return toErrorInfo(value);\n\tif (value instanceof Date) return value.toISOString();\n\tif (value instanceof Map) {\n\t\tconst obj = {};\n\t\tfor (const [k, v] of value.entries()) obj[String(k)] = sanitizeArg(v, depth + 1, seen);\n\t\treturn obj;\n\t}\n\tif (value instanceof Set) {\n\t\tconst arr = [];\n\t\tfor (const v of value.values()) arr.push(sanitizeArg(v, depth + 1, seen));\n\t\treturn arr;\n\t}\n\tif (Array.isArray(value)) {\n\t\tif (seen.has(value)) return \"[Circular]\";\n\t\tseen.add(value);\n\t\tconst result = value.map((v) => sanitizeArg(v, depth + 1, seen));\n\t\tseen.delete(value);\n\t\treturn result;\n\t}\n\tif (typeof value === \"object\") {\n\t\tconst proto = Object.getPrototypeOf(value);\n\t\tif (proto !== Object.prototype && proto !== null) return { __nonClonable: value.constructor?.name || \"Unknown\" };\n\t\tif (seen.has(value)) return \"[Circular]\";\n\t\tseen.add(value);\n\t\tconst result = {};\n\t\tfor (const [k, v] of Object.entries(value)) result[k] = sanitizeArg(v, depth + 1, seen);\n\t\tseen.delete(value);\n\t\treturn result;\n\t}\n\treturn null;\n}\n//#endregion\n//#region src/executor/worker/forwarding-logger.ts\nfunction createForwardingLogger(post, level = \"info\", tags = []) {\n\tfunction safePost(msg) {\n\t\ttry {\n\t\t\tpost(msg);\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\tprocess.stderr.write(`[forwarding-logger] postMessage failed: ${msg.level} ${msg.message}\\n`);\n\t\t\t} catch {}\n\t\t}\n\t}\n\tfunction emit(wireLevel, message, args) {\n\t\tconst sanitizedArgs = args.map((a) => sanitizeArg(a));\n\t\tsafePost({\n\t\t\ttype: \"log\",\n\t\t\tlevel: wireLevel,\n\t\t\tmessage,\n\t\t\targs: tags.length > 0 ? [sanitizeArg({ tags }), ...sanitizedArgs] : sanitizedArgs,\n\t\t\ttimestamp: Date.now()\n\t\t});\n\t}\n\treturn {\n\t\tlevel,\n\t\tverbose: (message, ...args) => emit(\"debug\", message, args),\n\t\tdebug: (message, ...args) => emit(\"debug\", message, args),\n\t\tinfo: (message, ...args) => emit(\"info\", message, args),\n\t\twarn: (message, ...args) => emit(\"warn\", message, args),\n\t\terror: (message, ...args) => emit(\"error\", message, args),\n\t\terrorHandler: ((...data) => {\n\t\t\tconst first = data[0];\n\t\t\temit(\"error\", typeof first === \"string\" ? first : \"\", data.slice(1));\n\t\t}),\n\t\tchild: (childTags) => createForwardingLogger(post, level, [...tags, ...childTags])\n\t};\n}\n//#endregion\nexport { decideAtHead as $, ProbeSettler as A, ReactorEventTypes as At, JobExecutorEventTypes as B, KyselyWriteCache as C, PurgeTooLargeError as Ct, acquirePurgeLocks as D, UnsupportedStoredProtocolError as Dt, PURGE_NS as E, UnsupportedProtocolVersionError as Et, snapshotFunctionsFor as F, __exportAll as Ft, ModuleNotFoundError as G, DuplicateModuleError as H, DocumentMetaCache as I, createDocumentFromAction as J, GATED_DOCUMENT_ACTIONS as K, CollectionMembershipCache as L, createKyselyWatermarkProbe as M, parsePagingOptions as Mt, describeWaitingSessions as N, throwIfAborted as Nt, findPurged as O, UpgradePreconditionFailedError as Ot, parseSnapshot as P, yieldToMain as Pt, targetDocumentId as Q, DEFAULT_DEFERRED_JOB_TTL_MS as R, EventBus as S, InvalidSignatureError as St, PURGE_LOCK_BUCKETS as T, ReservedActionError as Tt, InvalidModuleError as U, DuplicateManifestError as V, ModelNotWorkerImportableError as W, submittedActionIds as X, createEmptyConsistencyToken as Y, summarizeSubmittedActions as Z, KyselyExecutionScope as _, DocumentNotFoundError as _t, DEFAULT_DRIVE_CONTAINER_TYPES as a, APPEND_CONDITION_FAILED_PREFIX as at, appliedDelete as b, GroupInUseError as bt, runMigrations as c, DocumentExistence as ct, KyselyOperationStore as d, RevisionMismatchError as dt, selectDecisionModel as et, KyselyKeyframeStore as f, AuthEnforcementDisabledError as ft, PassthroughSigner as g, DocumentNotDeletedError as gt, verifyActionSignature as h, DocumentDeletedError as ht, fromErrorInfo as i, DriveCollectionId as it, SettledWatermark as j, matchesScope as jt, listPurged as k, EventBusAggregateError as kt, createForwardingPoolInstrumentation as l, DuplicateOperationError as lt, SimpleJobExecutor as m, AuthorizationDeniedError as mt, errorToInfo as n, authDecisionModel as nt, REACTOR_SCHEMA as o, AppendConditionFailedError as ot, DocumentModelRegistry as p, AuthTimestampNotMonotonicError as pt, createConsistencyToken as q, sanitizeArg as r, buildDecisionModel as rt, getMigrationStatus as s, DocumentAlreadyExistsError as st, createForwardingLogger as t, documentDecisionModel as tt, instrumentPgPool as u, OptimisticLockError as ut, DEFAULT_PURGE_DELETE_BATCH as v, DocumentPurgedError as vt, KyselyOperationIndex as w, RelationshipNotFoundError as wt, resolveFeatureFlags as x, InvalidOperationTimestampError as xt, KyselyDocumentPurger as y, ExcessiveReshuffleError as yt, DEFAULT_MAX_PURGE_OPERATIONS as z };\n\n//# sourceMappingURL=forwarding-logger-BKDP4JnD.js.map","import type { Operation } from \"@powerhousedao/shared/document-model\";\nimport type { AtomicTxn } from \"@powerhousedao/reactor\";\nimport type { StoredOperation } from \"./types.js\";\n\nexport class HypercoreAtomicTransaction implements AtomicTxn {\n private operations: StoredOperation[] = [];\n\n constructor(\n private documentId: string,\n private documentType: string,\n private scope: string,\n private branch: string,\n ) {}\n\n addOperations(...operations: Operation[]): void {\n for (const op of operations) {\n this.operations.push({\n ...op,\n documentId: this.documentId,\n documentType: this.documentType,\n scope: this.scope,\n branch: this.branch,\n });\n }\n }\n\n getOperations(): StoredOperation[] {\n return this.operations;\n }\n}\n","import type { StoredOperation } from \"./types.js\";\n\nconst PAD_WIDTH = 10;\n\nexport const RANGE_UPPER_BOUND = \"9\".repeat(PAD_WIDTH) + \"~\";\n\nexport function pad(n: number): string {\n return n.toString().padStart(PAD_WIDTH, \"0\");\n}\n\nexport function operationKey(\n documentId: string,\n scope: string,\n branch: string,\n index: number,\n): string {\n return `op/${documentId}/${scope}/${branch}/${pad(index)}`;\n}\n\nexport function operationPrefix(\n documentId: string,\n scope: string,\n branch: string,\n): string {\n return `op/${documentId}/${scope}/${branch}/`;\n}\n\nexport function ordinalKey(ordinal: number): string {\n return `ord/${pad(ordinal)}`;\n}\n\nexport function ordinalPrefix(): string {\n return \"ord/\";\n}\n\nexport function duplicateKey(\n opId: string,\n index: number,\n skip: number,\n): string {\n return `dup/${opId}/${pad(index)}/${pad(skip)}`;\n}\n\nexport function headKey(\n documentId: string,\n scope: string,\n branch: string,\n): string {\n return `_meta/head/${documentId}/${scope}/${branch}`;\n}\n\nexport function headPrefix(documentId: string): string {\n return `_meta/head/${documentId}/`;\n}\n\nexport const ORDINAL_COUNTER_KEY = \"_meta/ordinal\";\n\nexport type ParsedOperationKey = {\n documentId: string;\n scope: string;\n branch: string;\n index: number;\n};\n\nexport function parseOperationKey(key: string): ParsedOperationKey {\n const parts = key.split(\"/\");\n return {\n documentId: parts[1],\n scope: parts[2],\n branch: parts[3],\n index: parseInt(parts[4], 10),\n };\n}\n\nexport type OrdinalEntry = {\n documentId: string;\n documentType: string;\n scope: string;\n branch: string;\n index: number;\n operation: StoredOperation;\n};\n\nexport type HeadEntryValue = {\n index: number;\n latestTimestampUtcMs: string;\n};\n","import {\n isPurgeMarker,\n type Operation,\n type OperationWithContext,\n} from \"@powerhousedao/shared/document-model\";\nimport type {\n AppendCondition,\n AtomicTxn,\n DocumentRevisions,\n IOperationStore,\n OperationFilter,\n PagedResults,\n PagingOptions,\n} from \"@powerhousedao/reactor\";\nimport {\n AppendConditionFailedError,\n DocumentAlreadyExistsError,\n DocumentPurgedError,\n DuplicateOperationError,\n RevisionMismatchError,\n} from \"@powerhousedao/reactor\";\nimport type Hyperbee from \"hyperbee\";\nimport { HypercoreAtomicTransaction } from \"./hypercore-atomic-transaction.js\";\nimport {\n ORDINAL_COUNTER_KEY,\n RANGE_UPPER_BOUND,\n duplicateKey,\n headKey,\n headPrefix,\n operationKey,\n operationPrefix,\n ordinalKey,\n ordinalPrefix,\n pad,\n} from \"./key-encoding.js\";\nimport type { HeadEntryValue, OrdinalEntry } from \"./key-encoding.js\";\nimport type { StoredOperation } from \"./types.js\";\n\nexport class HypercoreOperationStore implements IOperationStore {\n private applyLock: Promise<void> = Promise.resolve();\n\n constructor(private bee: Hyperbee) {}\n\n async apply(\n documentId: string,\n documentType: string,\n scope: string,\n branch: string,\n revision: number,\n fn: (txn: AtomicTxn) => void | Promise<void>,\n signal?: AbortSignal,\n condition?: AppendCondition,\n ): Promise<Operation[]> {\n const prevLock = this.applyLock;\n let releaseLock: () => void;\n this.applyLock = new Promise<void>((resolve) => {\n releaseLock = resolve;\n });\n\n await prevLock;\n\n try {\n // Single writer on applyLock: nothing can append between check and write.\n if (condition) {\n await this.assertConditionHolds(condition, signal);\n }\n\n return await this.executeApply(\n documentId,\n documentType,\n scope,\n branch,\n revision,\n fn,\n signal,\n );\n } finally {\n releaseLock!();\n }\n }\n\n /** Throws if any read-set stream has grown past its recorded revision. */\n private async assertConditionHolds(\n condition: AppendCondition,\n signal?: AbortSignal,\n ): Promise<void> {\n for (const stream of condition.streams) {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const entry = await this.bee.get(\n headKey(stream.documentId, stream.scope, stream.branch),\n );\n const head = entry ? (entry.value as HeadEntryValue).index : -1;\n\n if (head > stream.revision) {\n throw new AppendConditionFailedError(condition);\n }\n }\n }\n\n private async executeApply(\n documentId: string,\n documentType: string,\n scope: string,\n branch: string,\n revision: number,\n fn: (txn: AtomicTxn) => void | Promise<void>,\n signal?: AbortSignal,\n ): Promise<Operation[]> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const hKey = headKey(documentId, scope, branch);\n const headEntry = await this.bee.get(hKey);\n const currentRevision = headEntry\n ? (headEntry.value as HeadEntryValue).index\n : -1;\n\n const atomicTxn = new HypercoreAtomicTransaction(\n documentId,\n documentType,\n scope,\n branch,\n );\n await fn(atomicTxn);\n\n const operations = atomicTxn.getOperations();\n\n // No delete path here: a stream purged elsewhere ends in its marker.\n const marker = await this.purgeMarkerAtHead(documentId);\n if (marker !== undefined && operations.length > 0) {\n if (!operations.every((op) => isPurgeMarker(op))) {\n throw new DocumentPurgedError(documentId);\n }\n return [marker];\n }\n\n if (currentRevision !== revision - 1) {\n if (revision === 0 && this.isCreate(operations)) {\n throw new DocumentAlreadyExistsError(\n documentId,\n scope,\n currentRevision,\n );\n }\n\n throw new RevisionMismatchError(currentRevision + 1, revision);\n }\n\n if (operations.length === 0) {\n return [];\n }\n\n for (const op of operations) {\n const dupKey = duplicateKey(op.id, op.index, op.skip);\n const existing = await this.bee.get(dupKey);\n if (existing) {\n throw new DuplicateOperationError(\n `${op.id} at index ${op.index} with skip ${op.skip}`,\n );\n }\n }\n\n const ordinalEntry = await this.bee.get(ORDINAL_COUNTER_KEY);\n let nextOrdinal: number = ordinalEntry ? (ordinalEntry.value as number) : 0;\n\n const batch = this.bee.batch();\n\n for (const op of operations) {\n const opKey = operationKey(documentId, scope, branch, op.index);\n const serialized = this.serializeOperation(op);\n await batch.put(opKey, serialized);\n\n const ordEntry: OrdinalEntry = {\n documentId,\n documentType,\n scope,\n branch,\n index: op.index,\n operation: serialized,\n };\n await batch.put(ordinalKey(nextOrdinal), ordEntry);\n\n await batch.put(duplicateKey(op.id, op.index, op.skip), \"\");\n\n nextOrdinal++;\n }\n\n const lastOp = operations[operations.length - 1];\n const headValue: HeadEntryValue = {\n index: lastOp.index,\n latestTimestampUtcMs: lastOp.timestampUtcMs,\n };\n await batch.put(hKey, headValue);\n await batch.put(ORDINAL_COUNTER_KEY, nextOrdinal);\n\n await batch.flush();\n\n return operations.map((op) => this.toOperation(op));\n }\n\n /** A purge marker is written to document/main whichever branch it erases. */\n private async purgeMarkerAtHead(\n documentId: string,\n ): Promise<Operation | undefined> {\n const branch = \"main\";\n const head = await this.bee.get(headKey(documentId, \"document\", branch));\n if (!head) {\n return undefined;\n }\n const index = (head.value as HeadEntryValue).index;\n const entry = await this.bee.get(\n operationKey(documentId, \"document\", branch, index),\n );\n const stored = entry?.value as StoredOperation | undefined;\n return stored && isPurgeMarker(stored)\n ? this.toOperation(stored)\n : undefined;\n }\n\n private isCreate(operations: StoredOperation[]): boolean {\n return operations.some((op) => op.action.type === \"CREATE_DOCUMENT\");\n }\n\n /**\n * The paging cursor encodes the index to resume from (one past the last\n * row returned), not the last row's own index; \"\" or \"0\" (or anything\n * unparsable) means the start of the stream. This keeps \"0\" an unambiguous\n * start-of-stream sentinel even when a page ends at index 0, which would\n * otherwise make `nextCursor` equal the start cursor and loop a caller that\n * walks pages forever. Mirrors the encoding in the Kysely store.\n */\n async getSince(\n documentId: string,\n scope: string,\n branch: string,\n revision: number,\n filter?: OperationFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Operation>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = operationPrefix(documentId, scope, branch);\n const startIndex = revision + 1;\n const parsedCursor = paging?.cursor\n ? Number.parseInt(paging.cursor, 10)\n : NaN;\n const cursorIndex =\n Number.isFinite(parsedCursor) && parsedCursor > 0\n ? parsedCursor\n : startIndex;\n const effectiveStart = Math.max(startIndex, cursorIndex);\n\n const gt = prefix + pad(effectiveStart - 1);\n const lt = prefix + RANGE_UPPER_BOUND;\n const limit = paging?.limit ? paging.limit + 1 : undefined;\n\n const items: Operation[] = [];\n const stream = this.bee.createReadStream({ gt, lt, limit });\n\n for await (const entry of stream) {\n const stored = entry.value as StoredOperation;\n\n if (filter) {\n if (\n filter.actionTypes &&\n filter.actionTypes.length > 0 &&\n !filter.actionTypes.includes((stored.action as { type: string }).type)\n ) {\n continue;\n }\n if (\n filter.timestampFrom &&\n stored.timestampUtcMs < filter.timestampFrom\n ) {\n continue;\n }\n if (filter.timestampTo && stored.timestampUtcMs > filter.timestampTo) {\n continue;\n }\n if (\n filter.sinceRevision !== undefined &&\n stored.index < filter.sinceRevision\n ) {\n continue;\n }\n }\n\n items.push(this.toOperation(stored));\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? (resultItems[resultItems.length - 1].index + 1).toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getSince(\n documentId,\n scope,\n branch,\n revision,\n filter,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n /**\n * The paging cursor encodes the ordinal to resume from (one past the last\n * ordinal returned), not the last ordinal itself; \"\" or \"0\" (or anything\n * unparsable) means the start of the stream. Unlike the Kysely store's\n * `getSinceId` (whose auto-increment id starts at 1), this store's ordinal\n * counter starts at 0, so 0 is a real, valid ordinal and the same\n * ambiguous-cursor hazard as `getSince`/`getConflicting` applies here too.\n */\n async getSinceId(\n id: number,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<OperationWithContext>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const startId = id + 1;\n const parsedCursor = paging?.cursor\n ? Number.parseInt(paging.cursor, 10)\n : NaN;\n const cursorId =\n Number.isFinite(parsedCursor) && parsedCursor > 0\n ? parsedCursor\n : startId;\n const effectiveStart = Math.max(startId, cursorId);\n\n const gt = ordinalPrefix() + pad(effectiveStart - 1);\n const lt = ordinalPrefix() + RANGE_UPPER_BOUND;\n const limit = paging?.limit ? paging.limit + 1 : undefined;\n\n const items: OperationWithContext[] = [];\n const stream = this.bee.createReadStream({ gt, lt, limit });\n\n for await (const entry of stream) {\n const ordEntry = entry.value as OrdinalEntry;\n const ordinal = parseInt(entry.key.split(\"/\")[1], 10);\n\n items.push({\n operation: this.toOperation(ordEntry.operation),\n context: {\n documentId: ordEntry.documentId,\n documentType: ordEntry.documentType,\n scope: ordEntry.scope,\n branch: ordEntry.branch,\n ordinal,\n },\n });\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? (resultItems[resultItems.length - 1].context.ordinal + 1).toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getSinceId(\n id,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n /**\n * The paging cursor here encodes the index to resume from (one past the\n * last row returned), not the last row's own index, for the same reason as\n * `getSince`: a page ending at index 0 must not produce a cursor that is\n * indistinguishable from the start-of-stream sentinel.\n */\n async getConflicting(\n documentId: string,\n scope: string,\n branch: string,\n minTimestamp: string,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Operation>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = operationPrefix(documentId, scope, branch);\n const parsedCursor = paging?.cursor\n ? Number.parseInt(paging.cursor, 10)\n : NaN;\n const cursorIndex =\n Number.isFinite(parsedCursor) && parsedCursor > 0 ? parsedCursor : -1;\n\n const gte = cursorIndex >= 0 ? prefix + pad(cursorIndex) : prefix;\n const lt = prefix + RANGE_UPPER_BOUND;\n\n const stream = this.bee.createReadStream({ gte, lt });\n\n // One row past the page is all this needs: it proves a next page exists\n // and is dropped again below. The limit cannot be pushed down into\n // createReadStream, because minTimestamp is applied per entry as it is\n // read -- a raw range limit would stop short while matching operations\n // still lay further along the range.\n const readLimit = paging?.limit ? paging.limit + 1 : undefined;\n\n const items: Operation[] = [];\n\n for await (const entry of stream) {\n const stored = entry.value as StoredOperation;\n if (stored.timestampUtcMs >= minTimestamp) {\n items.push(this.toOperation(stored));\n // Every operation of a document shares one key prefix, so without\n // this the range walk drains the whole document to hand back a\n // single page. Breaking closes the stream: for-await calls the\n // iterator's return() on the way out.\n if (readLimit !== undefined && items.length >= readLimit) break;\n }\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? (resultItems[resultItems.length - 1].index + 1).toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getConflicting(\n documentId,\n scope,\n branch,\n minTimestamp,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n async getRevisions(\n documentId: string,\n branch: string,\n signal?: AbortSignal,\n ): Promise<DocumentRevisions> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = headPrefix(documentId);\n const stream = this.bee.createReadStream({\n gte: prefix,\n lt: prefix + \"~\",\n });\n\n const revision: Record<string, number> = {};\n let latestTimestamp = new Date(0).toISOString();\n\n for await (const entry of stream) {\n const parts = entry.key.split(\"/\");\n const entryScope = parts[3];\n const entryBranch = parts[4];\n\n if (entryBranch !== branch) {\n continue;\n }\n\n const headValue = entry.value as HeadEntryValue;\n revision[entryScope] = headValue.index + 1;\n\n if (headValue.latestTimestampUtcMs > latestTimestamp) {\n latestTimestamp = headValue.latestTimestampUtcMs;\n }\n }\n\n return { revision, latestTimestamp };\n }\n\n /**\n * A real maximum over the rows, not the head record's `latestTimestampUtcMs`:\n * that holds the last-indexed timestamp, which a re-append can leave behind a\n * later one, so it would under-report and admit a backdated auth write.\n */\n async getStreamLatestTimestamp(\n documentId: string,\n scope: string,\n branch: string,\n signal?: AbortSignal,\n ): Promise<string | undefined> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const stored = await this.getSince(\n documentId,\n scope,\n branch,\n -1,\n undefined,\n undefined,\n signal,\n );\n\n let latest: string | undefined;\n for (const operation of stored.results) {\n if (latest === undefined || operation.timestampUtcMs > latest) {\n latest = operation.timestampUtcMs;\n }\n }\n\n return latest;\n }\n\n async findOperationIds(\n documentId: string,\n scope: string,\n branch: string,\n opIds: string[],\n signal?: AbortSignal,\n ): Promise<Set<string>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const found = new Set<string>();\n if (opIds.length === 0) {\n return found;\n }\n\n const wanted = new Set(opIds);\n const stored = await this.getSince(\n documentId,\n scope,\n branch,\n -1,\n undefined,\n undefined,\n signal,\n );\n for (const operation of stored.results) {\n if (wanted.has(operation.id)) {\n found.add(operation.id);\n }\n }\n\n return found;\n }\n\n async getOperationsByIds(\n documentId: string,\n scope: string,\n branch: string,\n opIds: string[],\n signal?: AbortSignal,\n ): Promise<Operation[]> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n if (opIds.length === 0) {\n return [];\n }\n\n const wanted = new Set(opIds);\n const stored = await this.getSince(\n documentId,\n scope,\n branch,\n -1,\n undefined,\n undefined,\n signal,\n );\n const latest = new Map<string, Operation>();\n for (const operation of stored.results) {\n if (wanted.has(operation.id)) {\n latest.set(operation.id, operation);\n }\n }\n return [...latest.values()];\n }\n\n private serializeOperation(op: StoredOperation): StoredOperation {\n return {\n id: op.id,\n index: op.index,\n skip: op.skip,\n timestampUtcMs: op.timestampUtcMs,\n hash: op.hash,\n error: op.error,\n deniedReason: op.deniedReason,\n action: op.action,\n documentId: op.documentId,\n documentType: op.documentType,\n scope: op.scope,\n branch: op.branch,\n };\n }\n\n private toOperation(stored: StoredOperation): Operation {\n return {\n id: stored.id,\n index: stored.index,\n skip: stored.skip,\n timestampUtcMs: stored.timestampUtcMs,\n hash: stored.hash,\n error: stored.error || undefined,\n deniedReason: stored.deniedReason || undefined,\n action: stored.action,\n };\n }\n}\n","import Corestore from \"corestore\";\nimport Hyperbee from \"hyperbee\";\n\nexport class StorageManager {\n private store: Corestore;\n private bee: Hyperbee | undefined;\n\n constructor(storagePath: string) {\n this.store = new Corestore(storagePath);\n }\n\n async open(): Promise<void> {\n await this.store.ready();\n const core = this.store.get({ name: \"operations\" });\n this.bee = new Hyperbee(core, {\n keyEncoding: \"utf-8\",\n valueEncoding: \"json\",\n });\n await this.bee.ready();\n }\n\n async close(): Promise<void> {\n if (this.bee) {\n await this.bee.close();\n }\n await this.store.close();\n }\n\n getBee(): Hyperbee {\n if (!this.bee) {\n throw new Error(\"StorageManager not opened. Call open() first.\");\n }\n return this.bee;\n }\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103],"mappings":";;;;AAUA,SAAgB,YAAY,KAAK;CAC7B,OAAO,OAAO,QAAQ,eAAe,QAAQ,KAAA;AACjD;AACA,SAAgB,SAAS,KAAK;CAC1B,OAAO,OAAO,QAAQ;AAC1B;AACA,SAAgB,SAAS,KAAK;CAC1B,OAAO,OAAO,QAAQ;AAC1B;AACA,SAAgB,UAAU,KAAK;CAC3B,OAAO,OAAO,QAAQ;AAC1B;AACA,SAAgB,OAAO,KAAK;CACxB,OAAO,QAAQ;AACnB;AAIA,SAAgB,SAAS,KAAK;CAC1B,OAAO,OAAO,QAAQ;AAC1B;AAMA,SAAgB,WAAW,KAAK;CAC5B,OAAO,OAAO,QAAQ;AAC1B;AACA,SAAgB,SAAS,KAAK;CAC1B,OAAO,OAAO,QAAQ,YAAY,QAAQ;AAC9C;AAoBA,SAAgB,OAAO,KAAK;CACxB,OAAO,OAAO,OAAO,GAAG;AAC5B;AACA,SAAgB,QAAQ,KAAK;CACzB,IAAI,gBAAgB,GAAG,GACnB,OAAO;MAGP,OAAO,CAAC,GAAG;AAEnB;AASA,SAAgB,gBAAgB,KAAK;CACjC,OAAO,MAAM,QAAQ,GAAG;AAC5B;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":[],"sources":["../../reactor/dist/load-spec-f2ppXyKZ.js","../src/hypercore-atomic-transaction.ts","../src/key-encoding.ts","../src/hypercore-operation-store.ts","../src/storage-manager.ts"],"sourcesContent":["import { DOCUMENT_DELETED_REASON, DOCUMENT_SCOPE_ACTION_TYPES, DowngradeNotSupportedError as DowngradeNotSupportedError$1, PURGE_DOCUMENT, appendWithoutApplying, applyDeleteDocumentAction, applyDeleteDocumentAction as applyDeleteDocumentAction$1, applyUpgradeDocumentAction, applyUpgradeDocumentAction as applyUpgradeDocumentAction$1, baseReducerVersion, createDocumentState, createPresignedHeader, defaultBaseState, deriveOperationId, isDenied, isPurgeMarker, mentionedGroupIds, normalizeDocumentModelVersion, operationOutcome, purgedProtocolVersions, targetDocumentId, withProtocolVersions } from \"@powerhousedao/shared/document-model\";\nimport { v4 } from \"uuid\";\nimport { Migrator, TableNode, sql } from \"kysely\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region src/shared/utils.ts\nfunction matchesScope(view = {}, scope) {\n\tif (view.scopes) return view.scopes.includes(scope);\n\treturn true;\n}\nfunction yieldToMain() {\n\tconst s = globalThis.scheduler;\n\tif (s?.yield) return s.yield();\n\treturn new Promise((resolve) => setTimeout(resolve, 0));\n}\nconst defaultAbortError = () => /* @__PURE__ */ new Error(\"Operation aborted\");\nfunction throwIfAborted(signal, makeError = defaultAbortError) {\n\tif (signal?.aborted) throw makeError();\n}\n/**\n* Validates PagingOptions and returns a normalized offset and limit.\n* Throws if the cursor is not empty and not a non-negative integer, or if\n* limit is less than 1. When `paging` is undefined, returns offset 0 and\n* the caller-supplied `defaultLimit`.\n*/\nfunction parsePagingOptions(paging, defaultLimit) {\n\tif (paging === void 0) return {\n\t\toffset: 0,\n\t\tlimit: defaultLimit\n\t};\n\tif (!Number.isInteger(paging.limit) || paging.limit < 1) throw new Error(`Invalid paging limit: ${String(paging.limit)} (must be an integer >= 1)`);\n\tif (paging.cursor === \"\") return {\n\t\toffset: 0,\n\t\tlimit: paging.limit\n\t};\n\tconst parsed = Number(paging.cursor);\n\tif (!Number.isInteger(parsed) || parsed < 0) throw new Error(`Invalid paging cursor: ${JSON.stringify(paging.cursor)} (must be empty or a non-negative integer)`);\n\treturn {\n\t\toffset: parsed,\n\t\tlimit: paging.limit\n\t};\n}\n//#endregion\n//#region src/events/types.ts\n/**\n* Custom error class that aggregates multiple errors from event subscribers.\n*/\nvar EventBusAggregateError = class extends Error {\n\terrors;\n\tconstructor(errors) {\n\t\tconst message = `EventBus emit failed with ${errors.length} error(s): ${errors.map((e) => {\n\t\t\tif (e && typeof e === \"object\" && \"message\" in e) return e.message;\n\t\t\treturn String(e);\n\t\t}).join(\"; \")}`;\n\t\tsuper(message);\n\t\tthis.name = \"EventBusAggregateError\";\n\t\tthis.errors = errors;\n\t}\n};\n/**\n* Event types for reactor lifecycle events.\n*/\nconst ReactorEventTypes = {\n\tJOB_PENDING: 10001,\n\tJOB_RUNNING: 10002,\n\tJOB_WRITE_READY: 10003,\n\tJOB_READ_READY: 10004,\n\tJOB_FAILED: 10005,\n\tREADMODEL_BATCH_COMPLETED: 10006,\n\tREADMODEL_INDEXED: 10007,\n\tMODEL_LOADED: 10008,\n\tSIGNATURE_REFUSED: 10009,\n\tCATCHUP_SWEPT: 10010\n};\n//#endregion\n//#region src/shared/errors.ts\n/**\n* Error thrown when attempting to access a deleted document.\n*/\nvar DocumentDeletedError = class DocumentDeletedError extends Error {\n\tdocumentId;\n\tdeletedAtUtcIso;\n\tconstructor(documentId, deletedAtUtcIso = null) {\n\t\tconst message = deletedAtUtcIso ? `Document ${documentId} was deleted at ${deletedAtUtcIso}` : `Document ${documentId} has been deleted`;\n\t\tsuper(message);\n\t\tthis.name = \"DocumentDeletedError\";\n\t\tthis.documentId = documentId;\n\t\tthis.deletedAtUtcIso = deletedAtUtcIso;\n\t\tError.captureStackTrace(this, DocumentDeletedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentDeletedError\";\n\t}\n};\n/**\n* Error thrown when the auth policy denies an action at the executor gate.\n*/\nvar AuthorizationDeniedError = class AuthorizationDeniedError extends Error {\n\tdocumentId;\n\tscope;\n\toperation;\n\tsubject;\n\tconstructor(documentId, scope, operation, subject) {\n\t\tsuper(`Authorization denied: ${subject ?? \"anonymous\"} may not execute ${operation} in scope \"${scope}\" of document ${documentId}`);\n\t\tthis.name = \"AuthorizationDeniedError\";\n\t\tthis.documentId = documentId;\n\t\tthis.scope = scope;\n\t\tthis.operation = operation;\n\t\tthis.subject = subject;\n\t\tError.captureStackTrace(this, AuthorizationDeniedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"AuthorizationDeniedError\";\n\t}\n};\n/**\n* An auth operation did not strictly exceed the newest timestamp in its stream.\n*\n* Terminal and asymmetric by design: no ordering rule can reconcile two replicas\n* that each accepted an auth operation offline, because either order hands one\n* authority the other never granted, so the replica ahead holds the arrival.\n*/\nvar AuthTimestampNotMonotonicError = class AuthTimestampNotMonotonicError extends Error {\n\tdocumentId;\n\tbranch;\n\ttimestampUtcMs;\n\tnewestTimestampUtcMs;\n\tconstructor(documentId, branch, timestampUtcMs, newestTimestampUtcMs) {\n\t\tsuper(`Auth timestamp not monotonic: ${timestampUtcMs} does not exceed ${newestTimestampUtcMs} in the auth stream of document ${documentId} on branch ${branch}`);\n\t\tthis.name = \"AuthTimestampNotMonotonicError\";\n\t\tthis.documentId = documentId;\n\t\tthis.branch = branch;\n\t\tthis.timestampUtcMs = timestampUtcMs;\n\t\tthis.newestTimestampUtcMs = newestTimestampUtcMs;\n\t\tError.captureStackTrace(this, AuthTimestampNotMonotonicError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"AuthTimestampNotMonotonicError\";\n\t}\n};\n/**\n* An operation or action carried a timestamp that is not an ISO-8601 UTC\n* instant.\n*\n* Terminal rather than retryable: the value does not change between attempts,\n* so a retry re-runs the whole job to fail identically. Quarantining, unlike a\n* held auth operation — this is malformed data rather than two replicas\n* disagreeing, and nothing further from that source should be trusted until it\n* is looked at.\n*/\nvar InvalidOperationTimestampError = class InvalidOperationTimestampError extends Error {\n\tdocumentId;\n\tscope;\n\ttimestampUtcMs;\n\tconstructor(documentId, scope, timestampUtcMs, context) {\n\t\tsuper(`Invalid timestamp \"${timestampUtcMs}\" on ${context} in scope \"${scope}\" of document ${documentId}`);\n\t\tthis.name = \"InvalidOperationTimestampError\";\n\t\tthis.documentId = documentId;\n\t\tthis.scope = scope;\n\t\tthis.timestampUtcMs = timestampUtcMs;\n\t\tError.captureStackTrace(this, InvalidOperationTimestampError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"InvalidOperationTimestampError\";\n\t}\n};\n/** A document requires a protocol version this reactor does not run. Terminal. */\nvar UnsupportedProtocolVersionError = class UnsupportedProtocolVersionError extends Error {\n\tdocumentId;\n\tprotocol;\n\tversion;\n\tconstructor(documentId, protocol, version) {\n\t\tsuper(`Document ${documentId} requires ${protocol} ${version}, which this reactor does not support`);\n\t\tthis.name = \"UnsupportedProtocolVersionError\";\n\t\tthis.documentId = documentId;\n\t\tthis.protocol = protocol;\n\t\tthis.version = version;\n\t\tError.captureStackTrace(this, UnsupportedProtocolVersionError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"UnsupportedProtocolVersionError\";\n\t}\n};\n/**\n* A load would move more operations than the bound allows, indicating a real\n* divergence between local and incoming history. Counts only first-time moves,\n* so a re-evaluation pass's re-appends do not make busy documents\n* revocation-proof. Terminal: the condition is deterministic.\n*/\nvar ExcessiveReshuffleError = class ExcessiveReshuffleError extends Error {\n\tdocumentId;\n\tscope;\n\tcount;\n\tthreshold;\n\tconstructor(documentId, scope, count, threshold) {\n\t\tsuper(`Excessive reshuffle detected: ${count} operations in scope \"${scope}\" of document ${documentId} exceeds the threshold of ${threshold}. This indicates a significant divergence between local and incoming operations.`);\n\t\tthis.name = \"ExcessiveReshuffleError\";\n\t\tthis.documentId = documentId;\n\t\tthis.scope = scope;\n\t\tthis.count = count;\n\t\tthis.threshold = threshold;\n\t\tError.captureStackTrace(this, ExcessiveReshuffleError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"ExcessiveReshuffleError\";\n\t}\n};\n/** The message carries the code: only name and message cross the queue. */\nvar InvalidSignatureError = class InvalidSignatureError extends Error {\n\tdocumentId;\n\tcode;\n\treason;\n\tconstructor(documentId, code, reason) {\n\t\tsuper(`Invalid signature in document ${documentId} [${code}]: ${reason}`);\n\t\tthis.name = \"InvalidSignatureError\";\n\t\tthis.documentId = documentId;\n\t\tthis.code = code;\n\t\tthis.reason = reason;\n\t\tError.captureStackTrace(this, InvalidSignatureError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"InvalidSignatureError\";\n\t}\n};\n/**\n* An UPGRADE_DOCUMENT action's preconditions (fromVersion and the per-scope\n* revision snapshot) did not match the document state the executor loaded.\n*\n* Terminal rather than retryable: the action carries the client's snapshot,\n* which stays stale no matter how often the job re-runs. The client is\n* expected to re-read the document and submit a fresh action instead.\n*/\nvar UpgradePreconditionFailedError = class UpgradePreconditionFailedError extends Error {\n\tdocumentId;\n\tdetail;\n\tconstructor(documentId, detail) {\n\t\tsuper(`Upgrade precondition failed for document ${documentId}: ${detail}`);\n\t\tthis.name = \"UpgradePreconditionFailedError\";\n\t\tthis.documentId = documentId;\n\t\tthis.detail = detail;\n\t\tError.captureStackTrace(this, UpgradePreconditionFailedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"UpgradePreconditionFailedError\";\n\t}\n};\n/**\n* Error thrown when a document is not found (no operations exist for the document ID).\n*/\nvar DocumentNotFoundError = class DocumentNotFoundError extends Error {\n\tdocumentId;\n\t/**\n\t* @param message Overrides the default text. A handler that knows which of\n\t* several documents an action reads - a relationship's source, say - says so\n\t* here rather than rewrapping in a bare Error, which would strip the name the\n\t* executor classifies by.\n\t*/\n\tconstructor(documentId, message) {\n\t\tsuper(message ?? `Document ${documentId} not found`);\n\t\tthis.name = \"DocumentNotFoundError\";\n\t\tthis.documentId = documentId;\n\t\tError.captureStackTrace(this, DocumentNotFoundError);\n\t}\n\t/** Also true for DocumentPurgedError: only the name crosses the queue. */\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && (error.name === \"DocumentNotFoundError\" || error.name === \"DocumentPurgedError\");\n\t}\n};\n/** The document was purged; readers treat it as absent. Terminal. */\nvar DocumentPurgedError = class DocumentPurgedError extends DocumentNotFoundError {\n\tpurged = true;\n\tconstructor(documentId, message) {\n\t\tsuper(documentId, message ?? `Document ${documentId} was purged`);\n\t\tthis.name = \"DocumentPurgedError\";\n\t\tError.captureStackTrace(this, DocumentPurgedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentPurgedError\";\n\t}\n};\n/** A purge was asked for a document that is not deleted. Terminal. */\nvar DocumentNotDeletedError = class DocumentNotDeletedError extends Error {\n\tdocumentId;\n\tconstructor(documentId, message) {\n\t\tsuper(message ?? `Document ${documentId} is not deleted`);\n\t\tthis.name = \"DocumentNotDeletedError\";\n\t\tthis.documentId = documentId;\n\t\tError.captureStackTrace(this, DocumentNotDeletedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentNotDeletedError\";\n\t}\n};\n/** A surviving document's accepted auth history names the group. Terminal. */\nvar GroupInUseError = class GroupInUseError extends Error {\n\tgroupId;\n\treferencingDocumentIds;\n\tconstructor(groupId, referencingDocumentIds) {\n\t\tsuper(`Group ${groupId} cannot be purged: the auth history of ${referencingDocumentIds.join(\", \")} names it`);\n\t\tthis.name = \"GroupInUseError\";\n\t\tthis.groupId = groupId;\n\t\tthis.referencingDocumentIds = referencingDocumentIds;\n\t\tError.captureStackTrace(this, GroupInUseError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"GroupInUseError\";\n\t}\n};\n/** A purge above maxPurgeOperations without allowLarge. Terminal. */\nvar PurgeTooLargeError = class PurgeTooLargeError extends Error {\n\tdocumentId;\n\toperationCount;\n\tmaxPurgeOperations;\n\tconstructor(documentId, operationCount, maxPurgeOperations) {\n\t\tsuper(`Document ${documentId} has ${operationCount} operations, above the purge limit of ${maxPurgeOperations}; request it with allowLarge`);\n\t\tthis.name = \"PurgeTooLargeError\";\n\t\tthis.documentId = documentId;\n\t\tthis.operationCount = operationCount;\n\t\tthis.maxPurgeOperations = maxPurgeOperations;\n\t\tError.captureStackTrace(this, PurgeTooLargeError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"PurgeTooLargeError\";\n\t}\n};\n/** A regular write carried an action type only the reactor issues. Terminal. */\nvar ReservedActionError = class ReservedActionError extends Error {\n\tdocumentId;\n\tactionType;\n\tconstructor(documentId, actionType) {\n\t\tsuper(`Action ${actionType} is reserved and cannot be submitted to document ${documentId}`);\n\t\tthis.name = \"ReservedActionError\";\n\t\tthis.documentId = documentId;\n\t\tthis.actionType = actionType;\n\t\tError.captureStackTrace(this, ReservedActionError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"ReservedActionError\";\n\t}\n};\n/**\n* An authorization preflight was asked for while the reactor's decision model\n* is off, so there is no model to answer from.\n*\n* Thrown rather than answered from the legacy host-side permission tables. The\n* two systems do not compose: the tables record which addresses a host lets\n* near a drive, the policy records what a document's own grants permit, and an\n* answer stitched from both would report an admission verdict neither system\n* would reach. A caller that cannot get a prediction disables nothing, which\n* leaves the submit path -- and its real gate -- as the only authority.\n*\n* Detection is by `name`, not `instanceof`: the SharedWorker RPC boundary\n* rebuilds a thrown error from `{ name, message, stack, cause }` alone\n* (`reactor-browser/src/rpc/error-info.ts`), so the class identity and any\n* custom field are lost in transit. This error therefore carries no fields.\n*/\nvar AuthEnforcementDisabledError = class AuthEnforcementDisabledError extends Error {\n\tconstructor() {\n\t\tsuper(\"Authorization evaluation requires the authEnforcement feature flag; this reactor holds no decision model, and the legacy host-table permission system cannot answer for one\");\n\t\tthis.name = \"AuthEnforcementDisabledError\";\n\t\tError.captureStackTrace(this, AuthEnforcementDisabledError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"AuthEnforcementDisabledError\";\n\t}\n};\n/**\n* Error thrown when a relationship edge an operation names does not exist.\n*\n* Detection is by `name`, not `instanceof`: the SharedWorker RPC boundary\n* rebuilds a thrown error from `{ name, message, stack, cause }` alone\n* (`reactor-browser/src/rpc/error-info.ts`), so the class identity is lost in\n* transit.\n*/\nvar RelationshipNotFoundError = class RelationshipNotFoundError extends Error {\n\tsourceId;\n\ttargetId;\n\trelationshipType;\n\tconstructor(sourceId, targetId, relationshipType) {\n\t\tsuper(`No ${relationshipType} relationship from ${sourceId} to ${targetId}`);\n\t\tthis.name = \"RelationshipNotFoundError\";\n\t\tthis.sourceId = sourceId;\n\t\tthis.targetId = targetId;\n\t\tthis.relationshipType = relationshipType;\n\t\tError.captureStackTrace(this, RelationshipNotFoundError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"RelationshipNotFoundError\";\n\t}\n};\n/** The store holds documents at protocol versions this reactor does not run. */\nvar UnsupportedStoredProtocolError = class UnsupportedStoredProtocolError extends Error {\n\tversions;\n\tdocuments;\n\tconstructor(versions, documents) {\n\t\tconst named = versions.map(({ protocol, version }) => `${protocol} ${version}`).join(\", \");\n\t\tsuper(`${documents} stored document(s) require ${named}, which this reactor does not run. Start a build that runs them, or accept them read-only with withUnsupportedStoredDocuments(\"read-only\")`);\n\t\tthis.name = \"UnsupportedStoredProtocolError\";\n\t\tthis.versions = versions;\n\t\tthis.documents = documents;\n\t\tError.captureStackTrace(this, UnsupportedStoredProtocolError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"UnsupportedStoredProtocolError\";\n\t}\n};\n//#endregion\n//#region src/storage/interfaces.ts\n/**\n* Thrown when an operation with the same identity already exists in the store.\n*/\nvar DuplicateOperationError = class extends Error {\n\tconstructor(description) {\n\t\tsuper(`Duplicate operation: ${description}`);\n\t\tthis.name = \"DuplicateOperationError\";\n\t}\n};\n/**\n* Thrown when a concurrent write conflict is detected during an atomic apply.\n*/\nvar OptimisticLockError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"OptimisticLockError\";\n\t}\n};\n/**\n* Thrown when the caller-provided revision does not match the current\n* stored revision, indicating a stale read.\n*/\nvar RevisionMismatchError = class extends Error {\n\tconstructor(expected, actual) {\n\t\tsuper(`Revision mismatch: expected ${expected}, got ${actual}`);\n\t\tthis.name = \"RevisionMismatchError\";\n\t}\n};\n/**\n* A create based on an empty stream that already has operations: the id is\n* taken, and no retry can resolve it. Matched by `name`, all the RPC boundary keeps.\n*/\nvar DocumentAlreadyExistsError = class extends Error {\n\tdocumentId;\n\tconstructor(documentId, scope, headRevision) {\n\t\tsuper(`Document ${documentId} already exists: create requested revision 0 but the \"${scope}\" stream is at revision ${headRevision}`);\n\t\tthis.name = \"DocumentAlreadyExistsError\";\n\t\tthis.documentId = documentId;\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentAlreadyExistsError\";\n\t}\n};\n/** Error history keeps messages, not classes, so failures match by prefix. */\nconst APPEND_CONDITION_FAILED_PREFIX = \"Append condition failed: \";\n/**\n* A read-set stream grew before the append committed. A concurrency\n* conflict, not a fault: the caller retries against the new stream heads.\n*/\nvar AppendConditionFailedError = class extends Error {\n\tcondition;\n\tconstructor(condition) {\n\t\tconst streams = condition.streams.map((s) => `${s.documentId}:${s.scope}:${s.branch}@${s.revision}`).join(\", \");\n\t\tsuper(`${APPEND_CONDITION_FAILED_PREFIX}a read-set stream advanced [${streams}]`);\n\t\tthis.condition = condition;\n\t\tthis.name = \"AppendConditionFailedError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"AppendConditionFailedError\";\n\t}\n\t/** True when a recorded error message is an append-condition failure. */\n\tstatic isFailureMessage(message) {\n\t\treturn message.startsWith(APPEND_CONDITION_FAILED_PREFIX);\n\t}\n};\n/**\n* Which sense of \"exists\" a caller of {@link IDocumentView.exists} means.\n*/\nlet DocumentExistence = /* @__PURE__ */ function(DocumentExistence) {\n\t/**\n\t* A document that is present and not deleted. This is the question a read\n\t* asks: a deleted document is not readable, so it does not exist.\n\t*/\n\tDocumentExistence[\"LiveOnly\"] = \"LiveOnly\";\n\t/**\n\t* Whether the id is taken, deleted or not. This is the question a write\n\t* asks: a deleted document keeps its operation stream, so its id can never\n\t* be reused, and answering from snapshots alone would say otherwise whenever\n\t* a snapshot row is missing while the stream is intact.\n\t*/\n\tDocumentExistence[\"IncludingDeleted\"] = \"IncludingDeleted\";\n\treturn DocumentExistence;\n}({});\n//#endregion\n//#region src/executor/util.ts\n/** Actions the reactor reduces itself, onto the document scope. */\nconst DOCUMENT_SCOPE_ACTIONS = DOCUMENT_SCOPE_ACTION_TYPES;\n/**\n* `CREATE_DOCUMENT` is exempt by necessity: it runs before the document exists,\n* so building a decision model would throw and defer the job forever.\n*/\nconst GATED_DOCUMENT_ACTIONS = new Set([...DOCUMENT_SCOPE_ACTIONS].filter((type) => type !== \"CREATE_DOCUMENT\"));\n/**\n* Creates a PHDocument from a CREATE_DOCUMENT action input.\n* Reconstructs the document header and initializes the base state.\n*\n* @param action - The CREATE_DOCUMENT action containing the document parameters\n* @returns A newly constructed PHDocument with initialized header and base state\n*/\nfunction createDocumentFromAction(action) {\n\tconst input = action.input;\n\tconst header = createPresignedHeader();\n\theader.id = input.documentId;\n\theader.documentType = input.model;\n\tif (input.signing) {\n\t\theader.createdAtUtcIso = input.signing.createdAtUtcIso;\n\t\theader.lastModifiedAtUtcIso = input.signing.createdAtUtcIso;\n\t\theader.sig = {\n\t\t\tpublicKey: input.signing.publicKey,\n\t\t\tnonce: input.signing.nonce\n\t\t};\n\t}\n\tif (input.slug !== void 0) header.slug = input.slug;\n\tif (!header.slug) header.slug = input.documentId;\n\tif (input.name !== void 0) header.name = input.name;\n\tif (input.branch !== void 0) header.branch = input.branch;\n\tif (input.meta !== void 0) header.meta = input.meta;\n\tif (input.protocolVersions !== void 0) header.protocolVersions = input.protocolVersions;\n\tconst baseState = defaultBaseState();\n\treturn {\n\t\theader,\n\t\toperations: {},\n\t\tstate: baseState,\n\t\tinitialState: baseState,\n\t\tclipboard: []\n\t};\n}\n/**\n* Calculate the next operation index for a specific scope.\n* Each scope maintains its own independent index sequence.\n*\n* Per-scope indexing means:\n* - Each scope (document, global, local, etc.) has independent indexes\n* - Indexes start at 0 for each scope\n* - Different scopes can have operations with the same index value\n*\n* This function uses header.revision which is populated by the cache/storage layer\n* and contains the next available index for each scope. This design avoids requiring\n* the full operation history to be loaded, which is crucial for snapshot-based caching.\n*\n* @param document - The document whose header.revision to inspect\n* @param scope - The scope to calculate the next index for\n* @returns The next available index in the specified scope\n*/\nconst getNextIndexForScope = (document, scope) => {\n\treturn document.header.revision[scope] || 0;\n};\n/**\n* Creates an empty consistency token with no coordinates.\n* Used when a job is registered or fails without writing operations.\n*\n* @returns A consistency token with an empty coordinates array\n*/\nfunction createEmptyConsistencyToken() {\n\treturn {\n\t\tversion: 1,\n\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tcoordinates: []\n\t};\n}\n/**\n* Creates a consistency token from operations written during job execution.\n* Maps each operation to a consistency coordinate tracking (documentId, scope, branch, operationIndex).\n* If no operations are provided, returns an empty token.\n*\n* @param operationsWithContext - Array of operations with their execution context\n* @returns A consistency token representing all operations written\n*/\nfunction createConsistencyToken(operationsWithContext) {\n\tif (operationsWithContext.length === 0) return createEmptyConsistencyToken();\n\tconst coordinates = [];\n\tfor (let i = 0; i < operationsWithContext.length; i++) {\n\t\tconst opWithContext = operationsWithContext[i];\n\t\tcoordinates.push({\n\t\t\tdocumentId: opWithContext.context.documentId,\n\t\t\tscope: opWithContext.context.scope,\n\t\t\tbranch: opWithContext.context.branch,\n\t\t\toperationIndex: opWithContext.operation.index\n\t\t});\n\t}\n\treturn {\n\t\tversion: 1,\n\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tcoordinates\n\t};\n}\nfunction createOperation(action, index, skip, context) {\n\treturn {\n\t\tid: deriveOperationId(context.documentId, context.scope, context.branch, action.id),\n\t\tindex,\n\t\ttimestampUtcMs: action.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString(),\n\t\thash: \"\",\n\t\tskip,\n\t\taction\n\t};\n}\nfunction updateDocumentRevision(document, scope, operationIndex) {\n\tdocument.header.revision = {\n\t\t...document.header.revision,\n\t\t[scope]: operationIndex + 1\n\t};\n}\nfunction buildSuccessResult(job, operation, documentId, documentType, resultingState, startTime) {\n\treturn {\n\t\tjob,\n\t\tsuccess: true,\n\t\toperations: [operation],\n\t\toperationsWithContext: [{\n\t\t\toperation,\n\t\t\tcontext: {\n\t\t\t\tdocumentId,\n\t\t\t\tscope: job.scope,\n\t\t\t\tbranch: job.branch,\n\t\t\t\tdocumentType,\n\t\t\t\tresultingState,\n\t\t\t\tordinal: 0\n\t\t\t}\n\t\t}],\n\t\tduration: Date.now() - startTime\n\t};\n}\nfunction buildErrorResult(job, error, startTime) {\n\treturn {\n\t\tjob,\n\t\tsuccess: false,\n\t\terror,\n\t\tduration: Date.now() - startTime\n\t};\n}\n/**\n* The error a refusal surfaces as. Both classes are already terminal in the job\n* result handler, so a refusal never burns a retry.\n*/\nfunction refusalError(reason, documentId, deletedAtUtcIso, action) {\n\tif (reason === DOCUMENT_DELETED_REASON) return new DocumentDeletedError(documentId, deletedAtUtcIso);\n\treturn new AuthorizationDeniedError(documentId, action.scope, action.type, action.context?.signer?.user.address);\n}\n/**\n* Whether this operation is part of the document's creation. The create and the\n* upgrade from version zero hold the first two indexes for the life of the\n* document, so a reshuffle has to leave them where they are.\n*/\nfunction isGenesisOperation(operation) {\n\tif (operation.action.type === \"CREATE_DOCUMENT\") return true;\n\tif (operation.action.type !== \"UPGRADE_DOCUMENT\") return false;\n\treturn operation.action.input.fromVersion === 0;\n}\n/**\n* The distinct streams a job wrote, collected so a rollback knows what to evict.\n*\n* A write records its stream on every apply, and a long run applies the same\n* stream hundreds of times, so this keeps one entry per stream rather than one\n* per write: the eviction only cares which streams were touched, and the\n* successful jobs that never read this back pay for a lookup instead of an\n* allocation.\n*/\nvar TouchedStreams = class {\n\tstreams = /* @__PURE__ */ new Map();\n\tadd(documentId, scope, branch) {\n\t\tconst key = `${documentId}\\u0000${scope}\\u0000${branch}`;\n\t\tif (this.streams.has(key)) return;\n\t\tthis.streams.set(key, {\n\t\t\tdocumentId,\n\t\t\tscope,\n\t\t\tbranch\n\t\t});\n\t}\n\t[Symbol.iterator]() {\n\t\treturn this.streams.values();\n\t}\n};\n/**\n* The ids of the actions the caller handed to a job. Load and reevaluation\n* jobs write operations nobody submitted, so they report none.\n*/\nfunction submittedActionIds(job) {\n\treturn job.kind === \"mutation\" ? job.actions.map((action) => action.id) : [];\n}\n/**\n* Reports what became of each submitted action.\n*\n* A job's operations can include ones it only moved to a new index, so only\n* those carrying a submitted action are reported. Returns undefined when the\n* job submitted nothing, which keeps `JobInfo.result` null for the jobs that\n* have no caller to answer to.\n*/\nfunction summarizeSubmittedActions(operations, submitted) {\n\tif (!submitted || submitted.length === 0) return;\n\tconst ids = new Set(submitted);\n\tconst actions = [];\n\tfor (const { operation, context } of operations) {\n\t\tif (!ids.has(operation.action.id)) continue;\n\t\tactions.push({\n\t\t\tactionId: operation.action.id,\n\t\t\tscope: context.scope,\n\t\t\tindex: operation.index,\n\t\t\t...operationOutcome(operation)\n\t\t});\n\t}\n\tif (actions.length === 0) return;\n\treturn {\n\t\tactions,\n\t\tallApplied: actions.every((action) => action.kind === \"applied\")\n\t};\n}\n/** Tombstones a job has read, each under the shared lock it took first. */\nvar PurgeFence = class {\n\tlocks;\n\tchecked;\n\tpurged;\n\tconstructor(locks, checked, purged) {\n\t\tthis.locks = locks;\n\t\tthis.checked = checked;\n\t\tthis.purged = purged;\n\t}\n\t/** Locks and reads an id the job start did not resolve. */\n\tasync isPurged(documentId) {\n\t\tawait this.isPurgedMany([documentId]);\n\t\treturn this.purged.has(documentId);\n\t}\n\t/** Locks and reads the unresolved ids in one lock and one lookup. */\n\tasync isPurgedMany(documentIds) {\n\t\tconst unchecked = [...new Set(documentIds)].filter((id) => !this.checked.has(id));\n\t\tif (unchecked.length > 0) {\n\t\t\tawait this.locks.shared(unchecked);\n\t\t\tconst found = await this.locks.purged(unchecked);\n\t\t\tfor (const id of unchecked) this.checked.add(id);\n\t\t\tfor (const id of found) this.purged.add(id);\n\t\t}\n\t\treturn new Set(documentIds.filter((id) => this.purged.has(id)));\n\t}\n};\n/** Locks and checks an id on its first read; a purged id reads as purged. */\nvar FencedWriteCache = class {\n\tinner;\n\tpurgeFence;\n\tevict;\n\tevicted = /* @__PURE__ */ new Set();\n\tconstructor(inner, purgeFence, evict) {\n\t\tthis.inner = inner;\n\t\tthis.purgeFence = purgeFence;\n\t\tthis.evict = evict;\n\t}\n\t/** Fences ids known before their reads in one round trip. */\n\tasync fence(documentIds) {\n\t\tawait this.purgeFence.isPurgedMany(documentIds);\n\t}\n\tasync getState(documentId, scope, branch, targetRevision, signal) {\n\t\tif (await this.purgeFence.isPurged(documentId)) {\n\t\t\tif (!this.evicted.has(documentId)) {\n\t\t\t\tthis.evicted.add(documentId);\n\t\t\t\tthis.evict(documentId);\n\t\t\t}\n\t\t\tthrow new DocumentPurgedError(documentId);\n\t\t}\n\t\treturn this.inner.getState(documentId, scope, branch, targetRevision, signal);\n\t}\n\tputState(documentId, scope, branch, revision, document, position) {\n\t\tthis.inner.putState(documentId, scope, branch, revision, document, position);\n\t}\n\tputRun(documentId, scope, branch, run) {\n\t\tthis.inner.putRun(documentId, scope, branch, run);\n\t}\n\tinvalidate(documentId, scope, branch) {\n\t\treturn this.inner.invalidate(documentId, scope, branch);\n\t}\n\tclear() {\n\t\tthis.inner.clear();\n\t}\n\tstartup() {\n\t\treturn this.inner.startup();\n\t}\n\tshutdown() {\n\t\treturn this.inner.shutdown();\n\t}\n};\n/** The target whose membership an ADD or REMOVE_RELATIONSHIP writes. */\nfunction relationshipTarget(action) {\n\tif (action.type !== \"ADD_RELATIONSHIP\" && action.type !== \"REMOVE_RELATIONSHIP\") return;\n\tconst target = action.input?.targetId;\n\treturn typeof target === \"string\" && target.length > 0 ? target : void 0;\n}\n/** The ids a job's locks cover, sorted: its write ids and groups it names. */\nfunction jobWriteIds(job) {\n\tconst ids = /* @__PURE__ */ new Set([job.documentId]);\n\tconst actions = [...job.actions, ...job.operations.map((operation) => operation.action)];\n\tfor (const action of actions) {\n\t\tif (DOCUMENT_SCOPE_ACTIONS.has(action.type)) ids.add(targetDocumentId(action, job.documentId));\n\t\tconst target = relationshipTarget(action);\n\t\tif (target !== void 0) ids.add(target);\n\t\tif (action.scope === \"auth\") for (const groupId of mentionedGroupIds(action)) ids.add(groupId);\n\t}\n\treturn [...ids].sort();\n}\n//#endregion\n//#region src/registry/errors.ts\n/**\n* Error thrown when a document model module is not found in the registry.\n*/\nvar ModuleNotFoundError = class extends Error {\n\tdocumentType;\n\trequestedVersion;\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` version ${version}` : \"\";\n\t\tsuper(`Document model module not found for type: ${documentType}${versionSuffix}`);\n\t\tthis.name = \"ModuleNotFoundError\";\n\t\tthis.documentType = documentType;\n\t\tthis.requestedVersion = version;\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"ModuleNotFoundError\";\n\t}\n};\n/** The host has the model only as a live module, which workers cannot import. */\nvar ModelNotWorkerImportableError = class extends Error {\n\tdocumentType;\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` version ${version}` : \"\";\n\t\tsuper(`Document model ${documentType}${versionSuffix} is registered on the host only as a live module, so executor workers cannot load it. Register it from a { filePath } or { packageName } source.`);\n\t\tthis.name = \"ModelNotWorkerImportableError\";\n\t\tthis.documentType = documentType;\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"ModelNotWorkerImportableError\";\n\t}\n};\n/**\n* Error thrown when attempting to register a module that already exists.\n*/\nvar DuplicateModuleError = class extends Error {\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` (version ${version})` : \"\";\n\t\tsuper(`Document model module already registered for type: ${documentType}${versionSuffix}`);\n\t\tthis.name = \"DuplicateModuleError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DuplicateModuleError\";\n\t}\n};\n/**\n* Error thrown when a module is invalid or malformed.\n*/\nvar InvalidModuleError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(`Invalid document model module: ${message}`);\n\t\tthis.name = \"InvalidModuleError\";\n\t}\n};\n/**\n* Error thrown when attempting to register an upgrade manifest that already exists.\n*/\nvar DuplicateManifestError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Upgrade manifest already registered for type: ${documentType}`);\n\t\tthis.name = \"DuplicateManifestError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DuplicateManifestError\";\n\t}\n};\n/**\n* Error thrown when an upgrade manifest is not found.\n*/\nvar ManifestNotFoundError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Upgrade manifest not found for type: ${documentType}`);\n\t\tthis.name = \"ManifestNotFoundError\";\n\t}\n};\n/**\n* Error thrown when a required upgrade transition is missing from the manifest.\n*/\nvar MissingUpgradeTransitionError = class extends Error {\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Missing upgrade transition for ${documentType}: v${fromVersion} to v${toVersion}`);\n\t\tthis.name = \"MissingUpgradeTransitionError\";\n\t}\n};\n/**\n* Error thrown when getUpgradeReducer is called with a non-single-step version increment.\n*/\nvar InvalidUpgradeStepError = class extends Error {\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Invalid upgrade step for ${documentType}: must be single version increment, got v${fromVersion} to v${toVersion}`);\n\t\tthis.name = \"InvalidUpgradeStepError\";\n\t}\n};\n//#endregion\n//#region src/cache/collection-membership-cache.ts\nvar CollectionMembershipCache = class CollectionMembershipCache {\n\toperationIndex;\n\tcache = /* @__PURE__ */ new Map();\n\tconstructor(operationIndex) {\n\t\tthis.operationIndex = operationIndex;\n\t}\n\twithScopedIndex(operationIndex) {\n\t\tconst scoped = new CollectionMembershipCache(operationIndex);\n\t\tscoped.cache = this.cache;\n\t\treturn scoped;\n\t}\n\tasync getCollectionsForDocuments(documentIds) {\n\t\tconst result = {};\n\t\tconst missing = [];\n\t\tfor (const docId of documentIds) {\n\t\t\tconst cached = this.cache.get(docId);\n\t\t\tif (cached !== void 0) result[docId] = cached;\n\t\t\telse missing.push(docId);\n\t\t}\n\t\tif (missing.length > 0) {\n\t\t\tconst fromDb = await this.operationIndex.getCollectionsForDocuments(missing);\n\t\t\tfor (const docId of missing) {\n\t\t\t\tconst collections = fromDb[docId] ?? [];\n\t\t\t\tresult[docId] = collections;\n\t\t\t\tthis.cache.set(docId, collections);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tinvalidate(documentId) {\n\t\tthis.cache.delete(documentId);\n\t}\n};\n//#endregion\n//#region src/cache/lru/lru-tracker.ts\nvar LRUNode = class {\n\tkey;\n\tprev;\n\tnext;\n\tconstructor(key) {\n\t\tthis.key = key;\n\t\tthis.prev = void 0;\n\t\tthis.next = void 0;\n\t}\n};\nvar LRUTracker = class {\n\tmap;\n\thead;\n\ttail;\n\tconstructor() {\n\t\tthis.map = /* @__PURE__ */ new Map();\n\t\tthis.head = void 0;\n\t\tthis.tail = void 0;\n\t}\n\tget size() {\n\t\treturn this.map.size;\n\t}\n\ttouch(key) {\n\t\tconst node = this.map.get(key);\n\t\tif (node) this.moveToFront(node);\n\t\telse this.addToFront(key);\n\t}\n\tevict() {\n\t\tif (!this.tail) return;\n\t\tconst key = this.tail.key;\n\t\tthis.remove(key);\n\t\treturn key;\n\t}\n\tremove(key) {\n\t\tconst node = this.map.get(key);\n\t\tif (!node) return;\n\t\tthis.removeNode(node);\n\t\tthis.map.delete(key);\n\t}\n\tclear() {\n\t\tthis.map.clear();\n\t\tthis.head = void 0;\n\t\tthis.tail = void 0;\n\t}\n\taddToFront(key) {\n\t\tconst node = new LRUNode(key);\n\t\tthis.map.set(key, node);\n\t\tif (!this.head) {\n\t\t\tthis.head = node;\n\t\t\tthis.tail = node;\n\t\t} else {\n\t\t\tnode.next = this.head;\n\t\t\tthis.head.prev = node;\n\t\t\tthis.head = node;\n\t\t}\n\t}\n\tmoveToFront(node) {\n\t\tif (node === this.head) return;\n\t\tthis.removeNode(node);\n\t\tnode.prev = void 0;\n\t\tnode.next = this.head;\n\t\tif (this.head) this.head.prev = node;\n\t\tthis.head = node;\n\t\tif (!this.tail) this.tail = node;\n\t}\n\tremoveNode(node) {\n\t\tif (node.prev) node.prev.next = node.next;\n\t\telse this.head = node.next;\n\t\tif (node.next) node.next.prev = node.prev;\n\t\telse this.tail = node.prev;\n\t}\n};\n//#endregion\n//#region src/cache/document-meta-cache.ts\n/**\n* In-memory document metadata cache with LRU eviction.\n*\n* Caches PHDocumentState per (documentId, branch) key. On cache miss,\n* rebuilds from document scope operations. Provides an explicit cross-scope\n* contract for accessing document scope metadata.\n*\n* **Thread Safety:**\n* Not thread-safe. Designed for single-threaded job executor environment.\n*/\nvar DocumentMetaCache = class DocumentMetaCache {\n\tcache;\n\tlruTracker;\n\toperationStore;\n\tconfig;\n\tconstructor(operationStore, config) {\n\t\tthis.operationStore = operationStore;\n\t\tthis.config = { maxDocuments: config.maxDocuments };\n\t\tthis.cache = /* @__PURE__ */ new Map();\n\t\tthis.lruTracker = new LRUTracker();\n\t}\n\twithScopedStore(operationStore) {\n\t\tconst scoped = new DocumentMetaCache(operationStore, this.config);\n\t\tscoped.cache = this.cache;\n\t\tscoped.lruTracker = this.lruTracker;\n\t\treturn scoped;\n\t}\n\tasync startup() {\n\t\treturn Promise.resolve();\n\t}\n\tasync shutdown() {\n\t\treturn Promise.resolve();\n\t}\n\tasync getDocumentMeta(documentId, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst key = this.makeKey(documentId, branch);\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) {\n\t\t\tthis.lruTracker.touch(key);\n\t\t\treturn cached;\n\t\t}\n\t\tconst meta = await this.rebuildLatest(documentId, branch, signal);\n\t\tthis.putDocumentMeta(documentId, branch, meta);\n\t\treturn meta;\n\t}\n\tasync rebuildAtRevision(documentId, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn this.rebuildFromOperations(documentId, branch, targetRevision, signal);\n\t}\n\tputDocumentMeta(documentId, branch, meta) {\n\t\tconst key = this.makeKey(documentId, branch);\n\t\tif (!this.cache.has(key) && this.cache.size >= this.config.maxDocuments) {\n\t\t\tconst evictKey = this.lruTracker.evict();\n\t\t\tif (evictKey) this.cache.delete(evictKey);\n\t\t}\n\t\tthis.cache.set(key, structuredClone(meta));\n\t\tthis.lruTracker.touch(key);\n\t}\n\tinvalidate(documentId, branch) {\n\t\tlet evicted = 0;\n\t\tif (branch === void 0) {\n\t\t\tfor (const key of this.cache.keys()) if (key.startsWith(`${documentId}:`)) {\n\t\t\t\tthis.cache.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else {\n\t\t\tconst key = this.makeKey(documentId, branch);\n\t\t\tif (this.cache.has(key)) {\n\t\t\t\tthis.cache.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted = 1;\n\t\t\t}\n\t\t}\n\t\treturn evicted;\n\t}\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.lruTracker.clear();\n\t}\n\tmakeKey(documentId, branch) {\n\t\treturn `${documentId}:${branch}`;\n\t}\n\tasync rebuildLatest(documentId, branch, signal) {\n\t\treturn this.rebuildFromOperations(documentId, branch, void 0, signal);\n\t}\n\tasync rebuildFromOperations(documentId, branch, targetRevision, signal) {\n\t\tconst docScopeOps = await this.operationStore.getSince(documentId, \"document\", branch, -1, void 0, void 0, signal);\n\t\tif (docScopeOps.results.length === 0) throw new DocumentNotFoundError(documentId);\n\t\tconst createOp = docScopeOps.results[0];\n\t\tif (isPurgeMarker(createOp)) return purgedMeta(createOp.action);\n\t\tif (createOp.action.type !== \"CREATE_DOCUMENT\") throw new Error(`Invalid document: first operation must be CREATE_DOCUMENT, found ${createOp.action.type}`);\n\t\tconst createAction = createOp.action;\n\t\tconst documentType = createAction.input.model;\n\t\tlet document = createDocumentFromAction(createAction);\n\t\tlet documentScopeRevision = 0;\n\t\tlet purged = false;\n\t\tfor (const op of docScopeOps.results) {\n\t\t\tif (targetRevision !== void 0 && op.index > targetRevision) break;\n\t\t\tdocumentScopeRevision = op.index;\n\t\t\tif (op.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\tconst upgradeAction = op.action;\n\t\t\t\tdocument = applyUpgradeDocumentAction$1(document, upgradeAction);\n\t\t\t} else if (op.action.type === \"DELETE_DOCUMENT\" || op.action.type === PURGE_DOCUMENT) {\n\t\t\t\tdocument = applyDeleteDocumentAction$1(document, op.action);\n\t\t\t\tpurged ||= op.action.type === PURGE_DOCUMENT;\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType,\n\t\t\tprotocolVersions: purged ? purgedProtocolVersions() : createAction.input.protocolVersions,\n\t\t\tdocumentScopeRevision: documentScopeRevision + 1\n\t\t};\n\t}\n};\n/** A lone marker has no CREATE_DOCUMENT; the marker describes the stream. */\nfunction purgedMeta(action) {\n\treturn {\n\t\tstate: createDocumentState({\n\t\t\tisDeleted: true,\n\t\t\tdeletedAtUtcIso: action.input.purgedAtUtcIso\n\t\t}),\n\t\tdocumentType: action.input.documentType,\n\t\tprotocolVersions: purgedProtocolVersions(),\n\t\tdocumentScopeRevision: 1\n\t};\n}\n//#endregion\n//#region src/catch-up/settled-watermark.ts\nconst MAX_PENDING_PROBES = 64;\n/** pg_sequence_last_value needs 10; pg_current_* replaced txid_* in 13. */\nfunction snapshotFunctionsFor(serverVersionNum) {\n\tif (serverVersionNum >= 13e4) return {\n\t\tsnapshot: \"pg_current_snapshot\",\n\t\tcurrentXid: \"pg_current_xact_id\",\n\t\txidIfAssigned: \"pg_current_xact_id_if_assigned\"\n\t};\n\tif (serverVersionNum >= 1e5) return {\n\t\tsnapshot: \"txid_current_snapshot\",\n\t\tcurrentXid: \"txid_current\",\n\t\txidIfAssigned: \"txid_current_if_assigned\"\n\t};\n\tthrow new Error(`PostgreSQL server_version_num ${serverVersionNum} is not supported: read-side catch-up needs 10 or later`);\n}\n/** Parses the `xmin:xmax:xip,...` text form of a snapshot. */\nfunction parseSnapshot(text) {\n\tconst parts = text.split(\":\");\n\tif (parts.length !== 3) throw new Error(`Malformed snapshot: ${text}`);\n\tconst [xmin, xmax, xip] = parts;\n\treturn {\n\t\txmin: BigInt(xmin),\n\t\txmax: BigInt(xmax),\n\t\txip: xip === \"\" ? [] : xip.split(\",\").map((xid) => BigInt(xid))\n\t};\n}\nasync function readSnapshotFunctions(db) {\n\tconst result = await sql`select current_setting('server_version_num') as version`.execute(db);\n\treturn snapshotFunctionsFor(Number(result.rows[0].version));\n}\n/** A probe settles once an xmin passes the xid it took after its head. */\nvar ProbeSettler = class {\n\tsettled = 0;\n\tlastHead = 0;\n\tcovered = 0;\n\tlastXip = [];\n\tpending = [];\n\tget settledThrough() {\n\t\treturn this.settled;\n\t}\n\tget head() {\n\t\treturn this.lastHead;\n\t}\n\t/** The highest head a settled or pending probe covers. */\n\tget probedHead() {\n\t\treturn this.covered;\n\t}\n\tobserve(head, xid, snapshot, nowUtcMs) {\n\t\tthis.lastHead = Math.max(this.lastHead, head);\n\t\tthis.lastXip = snapshot.xip;\n\t\tif (xid !== null && head > this.covered) {\n\t\t\tthis.covered = head;\n\t\t\tthis.pending.push({\n\t\t\t\thead,\n\t\t\t\txid,\n\t\t\t\ttakenAtUtcMs: nowUtcMs\n\t\t\t});\n\t\t\tif (this.pending.length > MAX_PENDING_PROBES) this.pending.shift();\n\t\t}\n\t\tconst stillPending = [];\n\t\tfor (const probe of this.pending) if (snapshot.xmin > probe.xid) this.settled = Math.max(this.settled, probe.head);\n\t\telse stillPending.push(probe);\n\t\tthis.pending = stillPending.filter((probe) => probe.head > this.settled);\n\t\treturn this.settled;\n\t}\n\t/** Xids an unsettled probe still waits on. */\n\twaitingOn() {\n\t\tif (this.pending.length === 0) return [];\n\t\tconst xid = this.pending[0].xid;\n\t\treturn this.lastXip.filter((open) => open < xid).map((open) => open.toString());\n\t}\n\tstalledSinceUtcMs() {\n\t\treturn this.pending[0]?.takenAtUtcMs;\n\t}\n};\nfunction operationIndexTableName(db) {\n\tconst from = db.selectFrom(\"operation_index_operations\").selectAll().toOperationNode().from?.froms[0];\n\tconst schema = from !== void 0 && TableNode.is(from) ? from.table.schema?.name : void 0;\n\tconst quote = (identifier) => `\"${identifier.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\treturn schema === void 0 ? quote(\"operation_index_operations\") : `${quote(schema)}.${quote(\"operation_index_operations\")}`;\n}\n/** Reads the head, takes and commits an xid, then reads a snapshot, in order. */\nfunction createKyselyWatermarkProbe(db) {\n\tlet resolved = null;\n\tconst resolve = async () => {\n\t\tconst fns = await readSnapshotFunctions(db);\n\t\tconst table = operationIndexTableName(db);\n\t\tconst sequence = (await sql`select pg_get_serial_sequence(${table}, 'ordinal') as sequence`.execute(db)).rows[0]?.sequence;\n\t\tif (!sequence) throw new Error(`No ordinal sequence found for ${table}`);\n\t\treturn {\n\t\t\tfns,\n\t\t\tsequence\n\t\t};\n\t};\n\treturn async (probedHead) => {\n\t\tresolved ??= resolve().catch((error) => {\n\t\t\tresolved = null;\n\t\t\tthrow error;\n\t\t});\n\t\tconst { fns, sequence } = await resolved;\n\t\tconst headRow = (await sql`select coalesce(pg_sequence_last_value(${sequence}::regclass), 0) as head, ${sql.raw(fns.xidIfAssigned)}() is null as outside_write`.execute(db)).rows[0];\n\t\tconst head = Number(headRow.head);\n\t\tlet xid = null;\n\t\tif (headRow.outside_write && head > probedHead) {\n\t\t\tconst xidResult = await sql`select ${sql.raw(fns.currentXid)}()::text as xid`.execute(db);\n\t\t\txid = BigInt(xidResult.rows[0].xid);\n\t\t}\n\t\tconst row = (await sql`select ${sql.raw(fns.snapshot)}()::text as snapshot, ${sql.raw(fns.xidIfAssigned)}() is null as outside_write`.execute(db)).rows[0];\n\t\treturn {\n\t\t\thead,\n\t\t\txid,\n\t\t\tsnapshot: parseSnapshot(row.snapshot),\n\t\t\toutsideWrite: headRow.outside_write && row.outside_write\n\t\t};\n\t};\n}\n/** Knows when an ordinal gap is final by asking which transactions are open. */\nvar SettledWatermark = class {\n\tprobe;\n\tlogger;\n\tnow;\n\tsettler = new ProbeSettler();\n\tlisteners = /* @__PURE__ */ new Set();\n\tcurrent;\n\tnext;\n\twarnedInsideWrite = false;\n\tconstructor(probe, logger, now = Date.now) {\n\t\tthis.probe = probe;\n\t\tthis.logger = logger;\n\t\tthis.now = now;\n\t}\n\tget settledThrough() {\n\t\treturn this.settler.settledThrough;\n\t}\n\trefresh(signal) {\n\t\tsignal?.throwIfAborted();\n\t\tif (this.next !== void 0) return this.next;\n\t\tif (this.current === void 0) return this.start();\n\t\tconst next = this.current.catch(() => this.settledThrough).then(() => {\n\t\t\tthis.next = void 0;\n\t\t\treturn this.start();\n\t\t});\n\t\tthis.next = next;\n\t\treturn next;\n\t}\n\tonAdvance(listener) {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\tstatus() {\n\t\tconst stalledSinceUtcMs = this.settler.head > this.settledThrough ? this.settler.stalledSinceUtcMs() : void 0;\n\t\treturn {\n\t\t\thead: this.settler.head,\n\t\t\tsettledThrough: this.settledThrough,\n\t\t\twaitingOn: this.settler.waitingOn(),\n\t\t\t...stalledSinceUtcMs !== void 0 ? { stalledSinceUtcMs } : {}\n\t\t};\n\t}\n\tstart() {\n\t\tconst run = this.probeOnce().finally(() => {\n\t\t\tif (this.current === run) this.current = void 0;\n\t\t});\n\t\tthis.current = run;\n\t\treturn run;\n\t}\n\tasync probeOnce() {\n\t\tconst reading = await this.probe(this.settler.probedHead);\n\t\tif (!reading.outsideWrite) {\n\t\t\tif (!this.warnedInsideWrite) {\n\t\t\t\tthis.warnedInsideWrite = true;\n\t\t\t\tthis.logger.warn(\"settled watermark probe ran inside another session's write transaction; discarded\");\n\t\t\t}\n\t\t\treturn this.settledThrough;\n\t\t}\n\t\tconst before = this.settledThrough;\n\t\tconst after = this.settler.observe(reading.head, reading.xid, reading.snapshot, this.now());\n\t\tif (after > before) for (const listener of this.listeners) try {\n\t\t\tlistener(after);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"settled watermark listener failed: @error\", error);\n\t\t}\n\t\treturn after;\n\t}\n};\n/** Sessions holding these xids open; empty without pg_stat_activity. */\nasync function describeWaitingSessions(db, xids) {\n\tif (xids.length === 0) return [];\n\tconst epochless = xids.map((xid) => (BigInt(xid) % 2n ** 32n).toString());\n\ttry {\n\t\treturn (await sql`select pid, application_name, state, xact_start, backend_xid::text as xid\n from pg_stat_activity\n where backend_xid::text in (${sql.join(epochless)})`.execute(db)).rows.map((row) => ({\n\t\t\tpid: Number(row.pid),\n\t\t\tapplicationName: row.application_name ?? \"\",\n\t\t\tstate: row.state ?? \"\",\n\t\t\txactStart: row.xact_start === null ? null : new Date(row.xact_start).toISOString(),\n\t\t\txid: row.xid\n\t\t}));\n\t} catch {\n\t\treturn [];\n\t}\n}\n//#endregion\n//#region src/storage/kysely/document-purges.ts\n/** Class key of every purge lock; the stream locks use the single-key space. */\nconst PURGE_NS = 1347571013;\n/** Ids share this many lock keys, so a job's lock count stays bounded. */\nconst PURGE_LOCK_BUCKETS = 1024;\nasync function acquirePurgeLocks(trx, ids, mode) {\n\tconst unique = [...new Set(ids)];\n\tif (unique.length === 0) return;\n\tconst lock = sql.raw(mode === \"shared\" ? \"pg_advisory_xact_lock_shared\" : \"pg_advisory_xact_lock\");\n\tawait sql`\n with keys as materialized (\n select distinct hashtext(id) & ${sql.lit(1023)} as key\n from unnest(${unique}::text[]) as t(id)\n order by key\n )\n select ${lock}(${sql.lit(PURGE_NS)}, key) from keys order by key\n `.execute(trx);\n}\n/** The ids among `ids` that have a tombstone, read in the handle's schema. */\nasync function findPurged(db, ids) {\n\tconst unique = [...new Set(ids)];\n\tif (unique.length === 0) return /* @__PURE__ */ new Set();\n\tconst rows = await db.selectFrom(\"document_purges\").select(\"documentId\").where(sql`\"documentId\" = any(${unique}::text[])`).execute();\n\treturn new Set(rows.map((row) => row.documentId));\n}\n/** Every tombstoned id, read in the handle's schema. */\nasync function listPurged(db) {\n\treturn (await db.selectFrom(\"document_purges\").select(\"documentId\").orderBy(\"documentId\").execute()).map((row) => row.documentId);\n}\n/** Bind slots per statement: 16-bit on the wire, read signed in-process. */\nconst MAX_BIND_PARAMETERS = 32767;\n/** Splits rows into runs that each bind at most MAX_BIND_PARAMETERS. */\nfunction chunkRows(rows) {\n\tif (rows.length === 0) return [];\n\tconst columnsPerRow = Math.max(1, Object.keys(rows[0]).length);\n\tconst perChunk = Math.max(1, Math.floor(MAX_BIND_PARAMETERS / columnsPerRow));\n\tif (rows.length <= perChunk) return [rows];\n\tconst chunks = [];\n\tfor (let i = 0; i < rows.length; i += perChunk) chunks.push(rows.slice(i, i + perChunk));\n\treturn chunks;\n}\n/** Per database: the function that assigns the transaction's xid. */\nconst xidFunctions = /* @__PURE__ */ new WeakMap();\nvar KyselyOperationIndexTxn = class {\n\tcollections = [];\n\tcollectionMemberships = [];\n\tcollectionRemovals = [];\n\tgroupReferences = [];\n\toperations = [];\n\tmembershipInvalidations = /* @__PURE__ */ new Set();\n\t/** Called by the commit as it writes each document_collections row. */\n\trecordMembershipInvalidation(documentId) {\n\t\tthis.membershipInvalidations.add(documentId);\n\t}\n\tgetMembershipInvalidations() {\n\t\treturn [...this.membershipInvalidations];\n\t}\n\tcreateCollection(collectionId) {\n\t\tthis.collections.push(collectionId);\n\t}\n\taddToCollection(collectionId, documentId) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"addToCollection must be called after write() - no operations in transaction\");\n\t\tthis.collectionMemberships.push({\n\t\t\tcollectionId,\n\t\t\tdocumentId,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\tremoveFromCollection(collectionId, documentId) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"removeFromCollection must be called after write() - no operations in transaction\");\n\t\tthis.collectionRemovals.push({\n\t\t\tcollectionId,\n\t\t\tdocumentId,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\trecordGroupReferences(documentId, groupIds) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"recordGroupReferences must be called after write() - no operations in transaction\");\n\t\tif (groupIds.length === 0) return;\n\t\tthis.groupReferences.push({\n\t\t\tdocumentId,\n\t\t\tgroupIds,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\twrite(operations) {\n\t\tthis.operations.push(...operations);\n\t}\n\tgetCollections() {\n\t\treturn this.collections;\n\t}\n\tgetGroupReferenceRecords() {\n\t\treturn this.groupReferences;\n\t}\n\tgetCollectionMembershipRecords() {\n\t\treturn this.collectionMemberships;\n\t}\n\tgetCollectionRemovals() {\n\t\treturn this.collectionRemovals;\n\t}\n\tgetOperations() {\n\t\treturn this.operations;\n\t}\n};\nvar KyselyOperationIndex = class KyselyOperationIndex {\n\tdb;\n\ttrx;\n\tliveIds;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\t/** `liveIds`: ids the transaction read untombstoned under its shared lock. */\n\twithTransaction(trx, liveIds) {\n\t\tconst instance = new KyselyOperationIndex(this.db);\n\t\tinstance.trx = trx;\n\t\tinstance.liveIds = liveIds;\n\t\treturn instance;\n\t}\n\tstart() {\n\t\treturn new KyselyOperationIndexTxn();\n\t}\n\tasync commit(txn, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst kyselyTxn = txn;\n\t\tif (this.trx) return this.executeCommit(this.trx, kyselyTxn);\n\t\tlet resultOrdinals = [];\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tresultOrdinals = await this.executeCommit(trx, kyselyTxn);\n\t\t});\n\t\treturn resultOrdinals;\n\t}\n\t/**\n\t* A policy-driven join: keeps the earliest join so a rediscovered reference\n\t* never shrinks a backfill window remotes already rely on, and reopens a\n\t* closed membership because a policy reference is not a removable one.\n\t*/\n\tasync joinKeepingEarliest(trx, kyselyTxn, documentId, collectionId, ordinal) {\n\t\tkyselyTxn.recordMembershipInvalidation(documentId);\n\t\tawait trx.insertInto(\"document_collections\").values({\n\t\t\tdocumentId,\n\t\t\tcollectionId,\n\t\t\tjoinedOrdinal: ordinal,\n\t\t\tleftOrdinal: null\n\t\t}).onConflict((oc) => oc.columns([\"documentId\", \"collectionId\"]).doUpdateSet({\n\t\t\tjoinedOrdinal: sql`LEAST(\"document_collections\".\"joinedOrdinal\", EXCLUDED.\"joinedOrdinal\")`,\n\t\t\tleftOrdinal: null\n\t\t})).execute();\n\t}\n\tasync executeCommit(trx, kyselyTxn) {\n\t\tconst collections = kyselyTxn.getCollections();\n\t\tconst memberships = kyselyTxn.getCollectionMembershipRecords();\n\t\tconst removals = kyselyTxn.getCollectionRemovals();\n\t\tconst groupReferences = kyselyTxn.getGroupReferenceRecords();\n\t\tconst operations = kyselyTxn.getOperations();\n\t\tif (collections.length > 0) {\n\t\t\tconst collectionRows = collections.map((collectionId) => ({\n\t\t\t\tdocumentId: collectionId,\n\t\t\t\tcollectionId,\n\t\t\t\tjoinedOrdinal: BigInt(0),\n\t\t\t\tleftOrdinal: null\n\t\t\t}));\n\t\t\tfor (const collectionId of collections) kyselyTxn.recordMembershipInvalidation(collectionId);\n\t\t\tfor (const chunk of chunkRows(collectionRows)) await trx.insertInto(\"document_collections\").values(chunk).onConflict((oc) => oc.doNothing()).execute();\n\t\t}\n\t\tlet operationOrdinals = [];\n\t\tif (operations.length > 0) {\n\t\t\tawait this.refusePurgedOperations(trx, operations);\n\t\t\tawait this.assignXid(trx);\n\t\t\tconst operationRows = operations.map((op) => ({\n\t\t\t\topId: op.id || \"\",\n\t\t\t\tdocumentId: op.documentId,\n\t\t\t\tdocumentType: op.documentType,\n\t\t\t\tscope: op.scope,\n\t\t\t\tbranch: op.branch,\n\t\t\t\ttimestampUtcMs: op.timestampUtcMs,\n\t\t\t\tindex: op.index,\n\t\t\t\tskip: op.skip,\n\t\t\t\thash: op.hash,\n\t\t\t\taction: op.action,\n\t\t\t\tdeniedReason: op.deniedReason ?? null,\n\t\t\t\tsourceRemote: op.sourceRemote\n\t\t\t}));\n\t\t\tfor (const chunk of chunkRows(operationRows)) {\n\t\t\t\tconst insertedOps = await trx.insertInto(\"operation_index_operations\").values(chunk).returning(\"ordinal\").execute();\n\t\t\t\toperationOrdinals = operationOrdinals.concat(insertedOps.map((row) => row.ordinal));\n\t\t\t}\n\t\t}\n\t\tif (memberships.length > 0) for (const m of memberships) {\n\t\t\tconst ordinal = operationOrdinals[m.operationIndex];\n\t\t\tkyselyTxn.recordMembershipInvalidation(m.documentId);\n\t\t\tawait trx.insertInto(\"document_collections\").values({\n\t\t\t\tdocumentId: m.documentId,\n\t\t\t\tcollectionId: m.collectionId,\n\t\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\t\tleftOrdinal: null\n\t\t\t}).onConflict((oc) => oc.columns([\"documentId\", \"collectionId\"]).doUpdateSet({\n\t\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\t\tleftOrdinal: null\n\t\t\t})).execute();\n\t\t\tconst references = await trx.selectFrom(\"group_references\").select(\"groupId\").where(\"documentId\", \"=\", m.documentId).execute();\n\t\t\tfor (const { groupId } of references) await this.joinKeepingEarliest(trx, kyselyTxn, groupId, m.collectionId, BigInt(ordinal));\n\t\t}\n\t\tif (removals.length > 0) for (const r of removals) {\n\t\t\tconst ordinal = operationOrdinals[r.operationIndex];\n\t\t\tkyselyTxn.recordMembershipInvalidation(r.documentId);\n\t\t\tawait trx.updateTable(\"document_collections\").set({ leftOrdinal: BigInt(ordinal) }).where(\"collectionId\", \"=\", r.collectionId).where(\"documentId\", \"=\", r.documentId).where(\"leftOrdinal\", \"is\", null).execute();\n\t\t}\n\t\tif (groupReferences.length > 0) for (const record of groupReferences) {\n\t\t\tconst ordinal = operationOrdinals[record.operationIndex];\n\t\t\tawait trx.insertInto(\"group_references\").values(record.groupIds.map((groupId) => ({\n\t\t\t\tdocumentId: record.documentId,\n\t\t\t\tgroupId\n\t\t\t}))).onConflict((oc) => oc.doNothing()).execute();\n\t\t\tconst rows = await trx.selectFrom(\"document_collections\").select(\"collectionId\").where(\"documentId\", \"=\", record.documentId).execute();\n\t\t\tfor (const groupId of record.groupIds) for (const { collectionId } of rows) await this.joinKeepingEarliest(trx, kyselyTxn, groupId, collectionId, BigInt(ordinal));\n\t\t}\n\t\treturn operationOrdinals;\n\t}\n\tasync getCollectionsInRange(after, through, among, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tif (through <= after || among?.length === 0) return [];\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").select(\"dc.collectionId\").distinct().where(\"oi.ordinal\", \">\", after).where(\"oi.ordinal\", \"<=\", through);\n\t\tif (among !== void 0) query = query.where(\"dc.collectionId\", \"in\", [...among]);\n\t\treturn (await query.execute()).map((row) => row.collectionId);\n\t}\n\tasync getOrdinalsInRange(after, through, limit, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tif (through <= after || limit <= 0) return [];\n\t\treturn (await this.queryExecutor.selectFrom(\"operation_index_operations\").select(\"ordinal\").where(\"ordinal\", \">\", after).where(\"ordinal\", \"<=\", through).orderBy(\"ordinal\", \"asc\").limit(limit).execute()).map((row) => Number(row.ordinal));\n\t}\n\tasync getByOrdinals(ordinals, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tif (ordinals.length === 0) return [];\n\t\tconst results = [];\n\t\tfor (let i = 0; i < ordinals.length; i += MAX_BIND_PARAMETERS) {\n\t\t\tconst chunk = ordinals.slice(i, i + MAX_BIND_PARAMETERS);\n\t\t\tconst rows = await this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"ordinal\", \"in\", chunk).orderBy(\"ordinal\", \"asc\").execute();\n\t\t\tfor (const row of rows) results.push(this.rowToOperationWithContext(row));\n\t\t}\n\t\tresults.sort((a, b) => a.context.ordinal - b.context.ordinal);\n\t\treturn results;\n\t}\n\tasync getStreamAfter(stream, after, signal, limit) {\n\t\tsignal?.throwIfAborted();\n\t\treturn (await this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"documentId\", \"=\", stream.documentId).where(\"branch\", \"=\", stream.branch).where(\"scope\", \"=\", stream.scope).where(\"ordinal\", \">\", after).orderBy(\"ordinal\", \"asc\").$if(limit !== void 0, (qb) => qb.limit(limit)).execute()).map((row) => this.rowToOperationWithContext(row));\n\t}\n\tasync getGroupReferencers(groupId, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn (await this.queryExecutor.selectFrom(\"group_references\").select(\"documentId\").where(\"groupId\", \"=\", groupId).orderBy(\"documentId\").execute()).map((row) => row.documentId);\n\t}\n\tasync getOrdinalsByOpIds(documentId, scope, branch, opIds, signal) {\n\t\tsignal?.throwIfAborted();\n\t\tif (opIds.length === 0) return /* @__PURE__ */ new Map();\n\t\tconst rows = await this.queryExecutor.selectFrom(\"operation_index_operations\").select(\"opId\").select((eb) => eb.fn.max(\"ordinal\").as(\"ordinal\")).where(\"documentId\", \"=\", documentId).where(\"branch\", \"=\", branch).where(\"scope\", \"=\", scope).where(\"opId\", \"in\", opIds).groupBy(\"opId\").execute();\n\t\treturn new Map(rows.map((row) => [row.opId, Number(row.ordinal)]));\n\t}\n\tasync find(collectionId, cursor, view, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst outerCursor = cursor ?? -1;\n\t\tconst limit = paging?.limit ?? 500;\n\t\tconst pagingCursorOrdinal = paging?.cursor !== void 0 ? Number.parseInt(paging.cursor, 10) : -1;\n\t\tconst buildBranch = (kind) => {\n\t\t\tlet qb = this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").selectAll(\"oi\").select([\"dc.documentId\", \"dc.collectionId\"]).where(\"dc.collectionId\", \"=\", collectionId).where(sql`(dc.\"leftOrdinal\" IS NULL OR oi.ordinal < dc.\"leftOrdinal\")`);\n\t\t\tif (kind === \"joiner\") qb = qb.where(\"dc.joinedOrdinal\", \">\", BigInt(outerCursor)).where(\"oi.ordinal\", \"<=\", outerCursor);\n\t\t\telse qb = qb.where(\"oi.ordinal\", \">\", outerCursor);\n\t\t\tqb = qb.where(\"oi.ordinal\", \">\", pagingCursorOrdinal);\n\t\t\tif (view?.branch) qb = qb.where(\"oi.branch\", \"=\", view.branch);\n\t\t\tif (view?.scopes && view.scopes.length > 0) qb = qb.where(\"oi.scope\", \"in\", view.scopes);\n\t\t\tif (view?.excludeSourceRemote) qb = qb.where(\"oi.sourceRemote\", \"!=\", view.excludeSourceRemote);\n\t\t\tif (view?.throughOrdinal !== void 0) qb = qb.where(\"oi.ordinal\", \"<=\", view.throughOrdinal).where(\"dc.joinedOrdinal\", \"<=\", BigInt(view.throughOrdinal));\n\t\t\treturn qb;\n\t\t};\n\t\tconst rows = await buildBranch(\"joiner\").unionAll(buildBranch(\"newOps\")).orderBy(\"ordinal\", \"asc\").limit(limit + 1).execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (rows.length > limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationIndexEntry(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.find(collectionId, cursor, view, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\tasync get(documentId, view, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst limit = paging?.limit ?? 500;\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"documentId\", \"=\", documentId).orderBy(\"ordinal\", \"asc\");\n\t\tif (view?.branch) query = query.where(\"branch\", \"=\", view.branch);\n\t\tif (view?.scopes && view.scopes.length > 0) query = query.where(\"scope\", \"in\", view.scopes);\n\t\tif (paging?.cursor) {\n\t\t\tconst cursorOrdinal = Number.parseInt(paging.cursor, 10);\n\t\t\tquery = query.where(\"ordinal\", \">\", cursorOrdinal);\n\t\t}\n\t\tquery = query.limit(limit + 1);\n\t\tconst rows = await query.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (rows.length > limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationIndexEntry(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.get(documentId, view, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\tasync getSinceOrdinal(ordinal, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst limit = paging?.limit ?? 500;\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"ordinal\", \">\", ordinal).orderBy(\"ordinal\", \"asc\");\n\t\tif (paging?.cursor) {\n\t\t\tconst cursorOrdinal = Number.parseInt(paging.cursor, 10);\n\t\t\tquery = query.where(\"ordinal\", \">\", cursorOrdinal);\n\t\t}\n\t\tquery = query.limit(limit + 1);\n\t\tconst rows = await query.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (rows.length > limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationWithContext(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.getSinceOrdinal(ordinal, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\t/** Backstop to the store's refusal: only a marker indexes a purged id. */\n\tasync refusePurgedOperations(trx, operations) {\n\t\tconst ids = new Set(operations.filter((operation) => !isPurgeMarker(operation)).map((operation) => operation.documentId).filter((id) => !this.liveIds?.has(id)));\n\t\tconst purged = await findPurged(trx, ids);\n\t\tfor (const id of ids) if (purged.has(id)) throw new DocumentPurgedError(id);\n\t}\n\t/** Takes the xid before the first ordinal, as the settled watermark needs. */\n\tasync assignXid(trx) {\n\t\tlet fn = xidFunctions.get(this.db);\n\t\tif (fn === void 0) {\n\t\t\tfn = readSnapshotFunctions(trx).then((fns) => fns.currentXid);\n\t\t\txidFunctions.set(this.db, fn);\n\t\t\tfn.catch(() => xidFunctions.delete(this.db));\n\t\t}\n\t\tconst name = await fn;\n\t\tawait sql`select ${sql.raw(name)}()`.execute(trx);\n\t}\n\trowToOperationWithContext(row) {\n\t\treturn {\n\t\t\toperation: {\n\t\t\t\tindex: row.index,\n\t\t\t\ttimestampUtcMs: row.timestampUtcMs,\n\t\t\t\thash: row.hash,\n\t\t\t\tskip: row.skip,\n\t\t\t\taction: row.action,\n\t\t\t\tdeniedReason: row.deniedReason ?? void 0,\n\t\t\t\tid: row.opId\n\t\t\t},\n\t\t\tcontext: {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tscope: row.scope,\n\t\t\t\tbranch: row.branch,\n\t\t\t\tordinal: row.ordinal\n\t\t\t}\n\t\t};\n\t}\n\trowToOperationIndexEntry(row) {\n\t\treturn {\n\t\t\tordinal: row.ordinal,\n\t\t\tdocumentId: row.documentId,\n\t\t\tdocumentType: row.documentType,\n\t\t\tbranch: row.branch,\n\t\t\tscope: row.scope,\n\t\t\tindex: row.index,\n\t\t\ttimestampUtcMs: row.timestampUtcMs,\n\t\t\thash: row.hash,\n\t\t\tskip: row.skip,\n\t\t\taction: row.action,\n\t\t\tdeniedReason: row.deniedReason ?? void 0,\n\t\t\tid: row.opId,\n\t\t\tsourceRemote: row.sourceRemote\n\t\t};\n\t}\n\tasync getLatestTimestampForCollection(collectionId, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn (await this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").select(\"oi.timestampUtcMs\").where(\"dc.collectionId\", \"=\", collectionId).where(sql`(dc.\"leftOrdinal\" IS NULL OR oi.ordinal < dc.\"leftOrdinal\")`).orderBy(\"oi.ordinal\", \"desc\").limit(1).executeTakeFirst())?.timestampUtcMs ?? null;\n\t}\n\tasync getCollectionsForDocuments(documentIds) {\n\t\tif (documentIds.length === 0) return {};\n\t\tconst rows = await this.queryExecutor.selectFrom(\"document_collections\").select([\"documentId\", \"collectionId\"]).where(\"documentId\", \"in\", documentIds).where(\"leftOrdinal\", \"is\", null).execute();\n\t\tconst result = {};\n\t\tfor (const row of rows) {\n\t\t\tif (!(row.documentId in result)) result[row.documentId] = [];\n\t\t\tresult[row.documentId].push(row.collectionId);\n\t\t}\n\t\treturn result;\n\t}\n};\n//#endregion\n//#region src/cache/buffer/ring-buffer.ts\n/**\n* RingBuffer is a generic circular buffer implementation that stores a fixed number\n* of items. When the buffer is full, new items overwrite the oldest items.\n*\n* This implementation maintains O(1) time complexity for push operations and provides\n* items in chronological order (oldest to newest) via getAll().\n*\n* @template T - The type of items stored in the buffer\n*/\nvar RingBuffer = class {\n\tbuffer;\n\thead = 0;\n\tsize = 0;\n\tcapacity;\n\tconstructor(capacity) {\n\t\tif (capacity <= 0) throw new Error(\"Ring buffer capacity must be greater than 0\");\n\t\tthis.capacity = capacity;\n\t\tthis.buffer = new Array(capacity);\n\t}\n\t/**\n\t* Adds an item to the buffer. If the buffer is full, overwrites the oldest item.\n\t*\n\t* @param item - The item to add\n\t*/\n\tpush(item) {\n\t\tconst index = (this.head + this.size) % this.capacity;\n\t\tif (this.size < this.capacity) {\n\t\t\tthis.buffer[index] = item;\n\t\t\tthis.size++;\n\t\t} else {\n\t\t\tthis.buffer[this.head] = item;\n\t\t\tthis.head = (this.head + 1) % this.capacity;\n\t\t}\n\t}\n\t/**\n\t* Returns all items in the buffer in chronological order (oldest to newest).\n\t*\n\t* @returns Array of items in insertion order\n\t*/\n\tgetAll() {\n\t\tif (this.size === 0) return [];\n\t\tconst result = [];\n\t\tfor (let i = 0; i < this.size; i++) {\n\t\t\tconst index = (this.head + i) % this.capacity;\n\t\t\tresult.push(this.buffer[index]);\n\t\t}\n\t\treturn result;\n\t}\n\t/**\n\t* Clears all items from the buffer.\n\t*/\n\tclear() {\n\t\tthis.buffer = new Array(this.capacity);\n\t\tthis.head = 0;\n\t\tthis.size = 0;\n\t}\n\t/**\n\t* Gets the current number of items in the buffer.\n\t*/\n\tget length() {\n\t\treturn this.size;\n\t}\n};\n//#endregion\n//#region src/cache/kysely-write-cache.ts\n/**\n* The last operation index a keyframe's document reflects for the scope. A\n* keyframe only exists for a scope that has operations, so a missing entry\n* means the stored row is corrupt.\n*/\nfunction keyframeRevision(keyframe, documentId, scope) {\n\tconst nextIndex = keyframe.document.header.revision[scope];\n\tif (typeof nextIndex !== \"number\") throw new Error(`Corrupt keyframe for document ${documentId} at revision ${keyframe.revision}: header carries no ${scope} revision`);\n\treturn nextIndex - 1;\n}\nfunction extractModuleVersion(doc) {\n\tconst v = doc.state.document.version;\n\treturn normalizeDocumentModelVersion(v);\n}\n/** The highest revision held, latest push winning a tie. */\nfunction highestRevision(snapshots) {\n\tlet newest = void 0;\n\tfor (const snapshot of snapshots) if (!newest || snapshot.revision >= newest.revision) newest = snapshot;\n\treturn newest;\n}\n/**\n* Copies a document far enough that the caller cannot write through it. Inside\n* this class, callers only ever replace whole fields on these four, so one\n* level each is enough.\n*/\nfunction copyDocument(document) {\n\treturn {\n\t\t...document,\n\t\theader: { ...document.header },\n\t\tstate: { ...document.state },\n\t\toperations: { ...document.operations }\n\t};\n}\nvar KyselyWriteCache = class KyselyWriteCache {\n\tstreams;\n\tlruTracker;\n\tkeyframeStore;\n\toperationStore;\n\tregistry;\n\tconfig;\n\treads = /* @__PURE__ */ new Map();\n\tconstructor(keyframeStore, operationStore, registry, config) {\n\t\tthis.keyframeStore = keyframeStore;\n\t\tthis.operationStore = operationStore;\n\t\tthis.registry = registry;\n\t\tthis.config = {\n\t\t\tmaxDocuments: config.maxDocuments,\n\t\t\tringBufferSize: config.ringBufferSize,\n\t\t\tkeyframeInterval: config.keyframeInterval\n\t\t};\n\t\tthis.streams = /* @__PURE__ */ new Map();\n\t\tthis.lruTracker = new LRUTracker();\n\t}\n\twithScopedStores(operationStore, keyframeStore) {\n\t\tconst scoped = new KyselyWriteCache(keyframeStore, operationStore, this.registry, this.config);\n\t\tscoped.streams = this.streams;\n\t\tscoped.lruTracker = this.lruTracker;\n\t\tscoped.reads = this.reads;\n\t\treturn scoped;\n\t}\n\t/**\n\t* Initializes the write cache.\n\t* Currently a no-op as keyframe store lifecycle is managed externally.\n\t*/\n\tasync startup() {\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Shuts down the write cache.\n\t* Currently a no-op as keyframe store lifecycle is managed externally.\n\t*/\n\tasync shutdown() {\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Retrieves document state at a specific revision from cache or rebuilds it.\n\t*\n\t* Note: this returns a _shallow_ copy of the document.\n\t*\n\t* Cache hit path: Returns cached snapshot if available (O(1))\n\t* Warm miss path: Rebuilds from cached base revision + incremental ops\n\t* Cold miss path: Rebuilds from keyframe or from scratch using all operations\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - The operation scope\n\t* @param branch - The operation branch\n\t* @param targetRevision - The target revision, or undefined for newest\n\t* @param signal - Optional abort signal to cancel the operation\n\t* @returns The document at the target revision\n\t* @throws {Error} \"Operation aborted\" if signal is aborted\n\t* @throws {ModuleNotFoundError} If document type not registered in registry\n\t* @throws {DocumentPurgedError} If the stream's only row is a purge marker\n\t* @throws {Error} \"Failed to rebuild document\" if operation store fails\n\t* @throws {Error} If reducer throws during operation application\n\t* @throws {Error} If document serialization fails\n\t*/\n\tasync getState(documentId, scope, branch, targetRevision, signal) {\n\t\tconst read = { evicted: false };\n\t\tlet pending = this.reads.get(documentId);\n\t\tif (!pending) {\n\t\t\tpending = /* @__PURE__ */ new Set();\n\t\t\tthis.reads.set(documentId, pending);\n\t\t}\n\t\tpending.add(read);\n\t\ttry {\n\t\t\treturn await this.readState(documentId, scope, branch, targetRevision, signal, read);\n\t\t} finally {\n\t\t\tpending.delete(read);\n\t\t\tif (pending.size === 0) this.reads.delete(documentId);\n\t\t}\n\t}\n\tasync readState(documentId, scope, branch, targetRevision, signal, read) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst streamKey = this.makeStreamKey(documentId, scope, branch);\n\t\tconst stream = this.streams.get(streamKey);\n\t\tif (stream) {\n\t\t\tconst snapshots = stream.ringBuffer.getAll();\n\t\t\tif (targetRevision === void 0) {\n\t\t\t\tconst newest = highestRevision(snapshots);\n\t\t\t\tif (newest?.position === \"head\") {\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn copyDocument(newest.document);\n\t\t\t\t}\n\t\t\t\tif (newest) {\n\t\t\t\t\tconst document = await this.warmMissRebuild(newest.document, newest.revision, documentId, scope, branch, void 0, signal);\n\t\t\t\t\tthis.storeUnlessEvicted(read, documentId, scope, branch, (document.header.revision[scope] ?? 0) - 1, document, \"head\");\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn document;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst exactMatch = snapshots.findLast((s) => s.revision === targetRevision);\n\t\t\t\tif (exactMatch) {\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn copyDocument(exactMatch.document);\n\t\t\t\t}\n\t\t\t\tconst newestOlder = this.findNearestOlderSnapshot(snapshots, targetRevision);\n\t\t\t\tif (newestOlder) {\n\t\t\t\t\tconst document = await this.warmMissRebuild(newestOlder.document, newestOlder.revision, documentId, scope, branch, targetRevision, signal);\n\t\t\t\t\tthis.storeUnlessEvicted(read, documentId, scope, branch, targetRevision, document, \"historical\");\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn document;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst document = await this.coldMissRebuild(documentId, scope, branch, targetRevision, signal);\n\t\tconst revision = targetRevision ?? (document.header.revision[scope] ?? 0) - 1;\n\t\tthis.storeUnlessEvicted(read, documentId, scope, branch, revision, document, targetRevision === void 0 ? \"head\" : \"historical\");\n\t\treturn document;\n\t}\n\t/**\n\t* Stores a document snapshot in the cache at a specific revision.\n\t*\n\t* The cached document is a shallow copy of the input with its operation history\n\t* truncated to the last operation per scope and its clipboard cleared. This keeps\n\t* memory use and copy costs constant regardless of operation count. Consumers of\n\t* getState() must not rely on the full operation history being present; the only\n\t* guaranteed invariant is that operations[scope].at(-1) reflects the latest\n\t* operation index for each scope.\n\t*\n\t* Updates LRU tracker and may evict least recently used stream if at capacity.\n\t* Asynchronously persists keyframes at configured intervals (fire-and-forget).\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - The operation scope\n\t* @param branch - The operation branch\n\t* @param revision - The revision number\n\t* @param document - The document to cache\n\t* @throws {Error} If document serialization fails\n\t*/\n\tputState(documentId, scope, branch, revision, document, position) {\n\t\tthis.store(documentId, scope, branch, revision, document, position);\n\t}\n\t/**\n\t* Stores the run's head and mints a keyframe for every interval the run\n\t* crossed on its way there. Only the head enters the ring buffer; the\n\t* earlier revisions are keyframe candidates and nothing more.\n\t*/\n\tputRun(documentId, scope, branch, run) {\n\t\tif (run.length === 0) return;\n\t\tfor (const entry of run.slice(0, -1)) this.persistKeyframe(documentId, scope, branch, entry.revision, entry.document);\n\t\tconst head = run[run.length - 1];\n\t\tthis.store(documentId, scope, branch, head.revision, head.document, \"head\");\n\t}\n\tstoreUnlessEvicted(read, documentId, scope, branch, revision, document, position) {\n\t\tif (!read.evicted) this.store(documentId, scope, branch, revision, document, position);\n\t}\n\tstore(documentId, scope, branch, revision, document, position) {\n\t\tconst streamKey = this.makeStreamKey(documentId, scope, branch);\n\t\tconst stream = this.getOrCreateStream(streamKey);\n\t\tconst snapshot = {\n\t\t\trevision,\n\t\t\tdocument: {\n\t\t\t\t...copyDocument(document),\n\t\t\t\toperations: Object.fromEntries(Object.entries(document.operations).map(([k, ops]) => [k, ops.length ? [ops.at(-1)] : []])),\n\t\t\t\tclipboard: []\n\t\t\t},\n\t\t\tposition\n\t\t};\n\t\tstream.ringBuffer.push(snapshot);\n\t\tthis.persistKeyframe(documentId, scope, branch, revision, document);\n\t}\n\t/** Persists the snapshot if this revision is one the interval falls on. */\n\tpersistKeyframe(documentId, scope, branch, revision, document) {\n\t\tif (!this.isKeyframeRevision(revision)) return;\n\t\tthis.keyframeStore.putKeyframe(documentId, scope, branch, revision, {\n\t\t\t...document,\n\t\t\toperations: {},\n\t\t\tclipboard: []\n\t\t}).catch((err) => {\n\t\t\tconsole.error(`Failed to persist keyframe ${documentId}@${revision}:`, err);\n\t\t});\n\t}\n\t/**\n\t* Invalidates cached document streams.\n\t*\n\t* Supports three invalidation scopes:\n\t* - Document-level: invalidate(documentId) - removes all streams for document\n\t* - Scope-level: invalidate(documentId, scope) - removes all branches for scope\n\t* - Stream-level: invalidate(documentId, scope, branch) - removes specific stream\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - Optional scope to narrow invalidation\n\t* @param branch - Optional branch to narrow invalidation (requires scope)\n\t* @returns The number of streams evicted\n\t*/\n\tinvalidate(documentId, scope, branch) {\n\t\tfor (const read of this.reads.get(documentId) ?? []) read.evicted = true;\n\t\tlet evicted = 0;\n\t\tif (scope === void 0 && branch === void 0) {\n\t\t\tfor (const [key] of this.streams.entries()) if (key.startsWith(`${documentId}:`)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else if (scope !== void 0 && branch === void 0) {\n\t\t\tfor (const [key] of this.streams.entries()) if (key.startsWith(`${documentId}:${scope}:`)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else if (scope !== void 0 && branch !== void 0) {\n\t\t\tconst key = this.makeStreamKey(documentId, scope, branch);\n\t\t\tif (this.streams.has(key)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted = 1;\n\t\t\t}\n\t\t}\n\t\treturn evicted;\n\t}\n\t/**\n\t* Clears the entire cache, removing all cached document streams.\n\t* Resets LRU tracking state. This operation always succeeds.\n\t*/\n\tclear() {\n\t\tfor (const pending of this.reads.values()) for (const read of pending) read.evicted = true;\n\t\tthis.streams.clear();\n\t\tthis.lruTracker.clear();\n\t}\n\t/**\n\t* Retrieves a specific stream for a document. Exposed on the implementation\n\t* for testing, but not on the interface.\n\t*\n\t* @internal\n\t*/\n\tgetStream(documentId, scope, branch) {\n\t\tconst key = this.makeStreamKey(documentId, scope, branch);\n\t\treturn this.streams.get(key);\n\t}\n\tasync findNearestKeyframe(documentId, scope, branch, targetRevision, signal) {\n\t\tif (targetRevision === Number.MAX_SAFE_INTEGER || targetRevision <= 0) return;\n\t\tconst keyframe = await this.keyframeStore.findNearestKeyframe(documentId, scope, branch, targetRevision, signal);\n\t\tif (!keyframe) return;\n\t\treturn {\n\t\t\trevision: Math.min(keyframeRevision(keyframe, documentId, scope), keyframe.revision),\n\t\t\tdocument: keyframe.document\n\t\t};\n\t}\n\t/**\n\t* Rebuilds a scope from a keyframe or from the whole operation history.\n\t*\n\t* The document scope is always rebuilt first, because it carries the type,\n\t* the upgrades and the deletion marker. Its version-changing upgrades are not\n\t* applied there though: an upgrade reducer must see the state the requested\n\t* scope has reached at that upgrade's boundary, so each one is held back and\n\t* applied when the replay below crosses the boundary that\n\t* resolveModuleVersionForOp derives from it. Upgrades whose boundary lies past\n\t* the last replayed operation are applied at the end. Creation-time 0->N seed\n\t* upgrades carry the initial state, so they still apply immediately.\n\t*/\n\tasync coldMissRebuild(documentId, scope, branch, targetRevision, signal, fromKeyframe = true) {\n\t\tconst effectiveTargetRevision = targetRevision || Number.MAX_SAFE_INTEGER;\n\t\tconst keyframe = fromKeyframe ? await this.findNearestKeyframe(documentId, scope, branch, effectiveTargetRevision, signal) : void 0;\n\t\tconst documentScopeBound = scope === \"document\" ? targetRevision : void 0;\n\t\tlet document;\n\t\tlet startRevision;\n\t\tlet documentType;\n\t\tconst validatedUpgrades = [];\n\t\tconst pendingUpgrades = [];\n\t\tlet lastDocumentScopeOperation;\n\t\tif (keyframe) {\n\t\t\tdocument = keyframe.document;\n\t\t\tstartRevision = keyframe.revision;\n\t\t\tdocumentType = keyframe.document.header.documentType;\n\t\t\tconst documentScopeResume = scope === \"document\" ? keyframe.revision : keyframeRevision(keyframe, documentId, \"document\");\n\t\t\tconst docScopeOpsAfterKeyframe = await this.operationStore.getSince(documentId, \"document\", branch, documentScopeResume, void 0, void 0, signal);\n\t\t\tfor (const operation of docScopeOpsAfterKeyframe.results) {\n\t\t\t\tif (documentScopeBound !== void 0 && operation.index > documentScopeBound) break;\n\t\t\t\tlastDocumentScopeOperation = operation;\n\t\t\t\tif (operation.error || isDenied(operation)) continue;\n\t\t\t\tif (operation.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\t\tconst upgradeAction = operation.action;\n\t\t\t\t\tconst fromVersion = upgradeAction.input.fromVersion;\n\t\t\t\t\tconst toVersion = upgradeAction.input.toVersion;\n\t\t\t\t\tif (fromVersion > 0 && fromVersion < toVersion) {\n\t\t\t\t\t\tlet upgradePath;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tupgradePath = this.registry.computeUpgradePath(documentType, fromVersion, toVersion);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tif (upgradeAction.input.initialState !== void 0) upgradePath = void 0;\n\t\t\t\t\t\t\telse throw new Error(`Failed to rebuild document ${documentId}: no upgrade manifest for ${documentType} v${fromVersion}→v${toVersion} and no initialState snapshot. ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalidatedUpgrades.push({\n\t\t\t\t\t\t\tfromVersion,\n\t\t\t\t\t\t\ttoVersion,\n\t\t\t\t\t\t\trevision: upgradeAction.input.revision,\n\t\t\t\t\t\t\ttimestampUtcMs: operation.timestampUtcMs\n\t\t\t\t\t\t});\n\t\t\t\t\t\tpendingUpgrades.push({\n\t\t\t\t\t\t\taction: upgradeAction,\n\t\t\t\t\t\t\tupgradePath,\n\t\t\t\t\t\t\tindex: operation.index,\n\t\t\t\t\t\t\tsubsequentDeletes: []\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t} else if (operation.action.type === \"DELETE_DOCUMENT\" || operation.action.type === PURGE_DOCUMENT) {\n\t\t\t\t\tapplyDeleteDocumentAction(document, operation.action);\n\t\t\t\t\tfor (const pending of pendingUpgrades) pending.subsequentDeletes.push(operation.action);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tstartRevision = -1;\n\t\t\tconst createOpResult = await this.operationStore.getSince(documentId, \"document\", branch, -1, void 0, {\n\t\t\t\tcursor: \"0\",\n\t\t\t\tlimit: 1\n\t\t\t}, signal);\n\t\t\tif (createOpResult.results.length === 0) throw new DocumentNotFoundError(documentId);\n\t\t\tconst createOp = createOpResult.results[0];\n\t\t\tif (isPurgeMarker(createOp)) throw new DocumentPurgedError(documentId);\n\t\t\tif (createOp.action.type !== \"CREATE_DOCUMENT\") throw new Error(`Failed to rebuild document ${documentId}: first operation in document scope must be CREATE_DOCUMENT, found ${createOp.action.type}`);\n\t\t\tconst documentCreateAction = createOp.action;\n\t\t\tdocumentType = documentCreateAction.input.model;\n\t\t\tif (!documentType) throw new Error(`Failed to rebuild document ${documentId}: CREATE_DOCUMENT action missing model in input`);\n\t\t\tdocument = createDocumentFromAction(documentCreateAction);\n\t\t\tlastDocumentScopeOperation = createOp;\n\t\t\tlet docModule = this.registry.getModule(documentType, extractModuleVersion(document));\n\t\t\tconst docScopeOps = await this.operationStore.getSince(documentId, \"document\", branch, 0, void 0, void 0, signal);\n\t\t\tfor (const operation of docScopeOps.results) {\n\t\t\t\tif (documentScopeBound !== void 0 && operation.index > documentScopeBound) break;\n\t\t\t\tlastDocumentScopeOperation = operation;\n\t\t\t\tif (operation.index === 0) continue;\n\t\t\t\tif (operation.error || isDenied(operation)) continue;\n\t\t\t\tif (operation.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\t\tconst upgradeAction = operation.action;\n\t\t\t\t\tconst fromVersion = upgradeAction.input.fromVersion;\n\t\t\t\t\tconst toVersion = upgradeAction.input.toVersion;\n\t\t\t\t\tif (fromVersion > 0 && fromVersion < toVersion) {\n\t\t\t\t\t\tlet upgradePath;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tupgradePath = this.registry.computeUpgradePath(documentType, fromVersion, toVersion);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tif (upgradeAction.input.initialState !== void 0) upgradePath = void 0;\n\t\t\t\t\t\t\telse throw new Error(`Failed to rebuild document ${documentId}: no upgrade manifest for ${documentType} v${fromVersion}→v${toVersion} and no initialState snapshot. ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalidatedUpgrades.push({\n\t\t\t\t\t\t\tfromVersion,\n\t\t\t\t\t\t\ttoVersion,\n\t\t\t\t\t\t\trevision: upgradeAction.input.revision,\n\t\t\t\t\t\t\ttimestampUtcMs: operation.timestampUtcMs\n\t\t\t\t\t\t});\n\t\t\t\t\t\tpendingUpgrades.push({\n\t\t\t\t\t\t\taction: upgradeAction,\n\t\t\t\t\t\t\tupgradePath,\n\t\t\t\t\t\t\tindex: operation.index,\n\t\t\t\t\t\t\tsubsequentDeletes: []\n\t\t\t\t\t\t});\n\t\t\t\t\t} else document = applyUpgradeDocumentAction(document, upgradeAction, void 0);\n\t\t\t\t\tdocModule = this.registry.getModule(documentType, normalizeDocumentModelVersion(toVersion));\n\t\t\t\t} else if (operation.action.type === \"DELETE_DOCUMENT\" || operation.action.type === PURGE_DOCUMENT) {\n\t\t\t\t\tapplyDeleteDocumentAction(document, operation.action);\n\t\t\t\t\tfor (const pending of pendingUpgrades) pending.subsequentDeletes.push(operation.action);\n\t\t\t\t} else {\n\t\t\t\t\tconst protocolVersion = baseReducerVersion(document.header);\n\t\t\t\t\tdocument = withProtocolVersions(docModule.reducer(document, operation.action, void 0, {\n\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\tprotocolVersion\n\t\t\t\t\t}), document.header.protocolVersions);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (scope === \"document\") {\n\t\t\tdocument = this.applyPendingUpgrades(document, pendingUpgrades, Number.MAX_SAFE_INTEGER);\n\t\t\tconst last = lastDocumentScopeOperation ?? await this.operationAt(documentId, \"document\", branch, startRevision, signal);\n\t\t\tdocument.operations = {\n\t\t\t\t...document.operations,\n\t\t\t\tdocument: last ? [last] : []\n\t\t\t};\n\t\t\treturn this.stampRevisions(document, documentId, scope, branch, targetRevision, signal);\n\t\t}\n\t\tif (keyframe) {\n\t\t\tconst resumeOperation = await this.operationAt(documentId, scope, branch, startRevision, signal);\n\t\t\tif (resumeOperation) document.operations = {\n\t\t\t\t...document.operations,\n\t\t\t\t[scope]: [resumeOperation]\n\t\t\t};\n\t\t}\n\t\tconst moduleCache = /* @__PURE__ */ new Map();\n\t\tconst getModuleCached = (version) => {\n\t\t\tconst key = version ?? 0;\n\t\t\tlet mod = moduleCache.get(key);\n\t\t\tif (!mod) {\n\t\t\t\tmod = this.registry.getModule(documentType, version);\n\t\t\t\tmoduleCache.set(key, mod);\n\t\t\t}\n\t\t\treturn mod;\n\t\t};\n\t\tconst finalVersion = validatedUpgrades.at(-1)?.toVersion ?? extractModuleVersion(document);\n\t\tlet cursor = void 0;\n\t\tconst pageSize = 100;\n\t\tlet hasMorePages;\n\t\tlet needsFullReplay = false;\n\t\tdo {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tconst paging = {\n\t\t\t\tcursor: cursor || \"0\",\n\t\t\t\tlimit: pageSize\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tconst result = await this.operationStore.getSince(documentId, scope, branch, startRevision, void 0, paging, signal);\n\t\t\t\tfor (const operation of result.results) {\n\t\t\t\t\tif (targetRevision !== void 0 && operation.index > targetRevision) break;\n\t\t\t\t\tif (keyframe && operation.skip > 0) {\n\t\t\t\t\t\tneedsFullReplay = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst moduleVersion = this.resolveModuleVersionForOp(operation.index, operation.timestampUtcMs, scope, validatedUpgrades, finalVersion);\n\t\t\t\t\tdocument = this.applyPendingUpgrades(document, pendingUpgrades, moduleVersion ?? Number.MAX_SAFE_INTEGER);\n\t\t\t\t\tif (isDenied(operation)) document = appendWithoutApplying(document, operation, scope);\n\t\t\t\t\telse {\n\t\t\t\t\t\tconst protocolVersion = baseReducerVersion(document.header);\n\t\t\t\t\t\tdocument = withProtocolVersions(getModuleCached(moduleVersion).reducer(document, operation.action, void 0, {\n\t\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\t\tprotocolVersion,\n\t\t\t\t\t\t\treplayOptions: { operation },\n\t\t\t\t\t\t\tskipIndexValidation: true\n\t\t\t\t\t\t}), document.header.protocolVersions);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst reachedTarget = targetRevision !== void 0 && result.results.some((op) => op.index >= targetRevision);\n\t\t\t\thasMorePages = Boolean(result.nextCursor) && !reachedTarget && !needsFullReplay;\n\t\t\t\tif (hasMorePages) cursor = result.nextCursor;\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(`Failed to rebuild document ${documentId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t}\n\t\t} while (hasMorePages);\n\t\tif (needsFullReplay) return this.coldMissRebuild(documentId, scope, branch, targetRevision, signal, false);\n\t\tdocument = this.applyTailPendingUpgrades(document, pendingUpgrades, scope, targetRevision);\n\t\tdocument = await this.stampRevisions(document, documentId, scope, branch, targetRevision, signal);\n\t\tif (pendingUpgrades.length > 0) {\n\t\t\tconst firstHeldBack = pendingUpgrades[0];\n\t\t\tconst stamped = document.header.revision[\"document\"] ?? 0;\n\t\t\tdocument.header.revision = {\n\t\t\t\t...document.header.revision,\n\t\t\t\tdocument: Math.min(stamped, firstHeldBack.index)\n\t\t\t};\n\t\t}\n\t\treturn document;\n\t}\n\t/**\n\t* Applies and removes every held-back upgrade whose target version is at or\n\t* below `throughVersion`, in the order the document scope recorded them.\n\t*/\n\tapplyPendingUpgrades(document, pendingUpgrades, throughVersion) {\n\t\twhile (pendingUpgrades.length > 0) {\n\t\t\tconst pending = pendingUpgrades[0];\n\t\t\tif (throughVersion < pending.action.input.toVersion) break;\n\t\t\tpendingUpgrades.shift();\n\t\t\tdocument = this.applyPendingUpgrade(document, pending);\n\t\t}\n\t\treturn document;\n\t}\n\t/**\n\t* Applies the remaining held-back upgrades after the requested scope's\n\t* replay has finished. A head read applies them all. A positional read\n\t* applies only those whose boundary for this scope lies at or before the\n\t* target position: applying a later one would label migrated state with a\n\t* pre-upgrade revision, and a keyframe stored from that poisons every\n\t* rebuild that resumes from it. Boundaries come from the upgrade's revision\n\t* snapshot; an upgrade without one records no position for this scope, and\n\t* the replay loop not having crossed it already places it past the target.\n\t*/\n\tapplyTailPendingUpgrades(document, pendingUpgrades, scope, targetRevision) {\n\t\twhile (pendingUpgrades.length > 0) {\n\t\t\tconst pending = pendingUpgrades[0];\n\t\t\tif (targetRevision !== void 0) {\n\t\t\t\tconst snapshot = pending.action.input.revision;\n\t\t\t\tif (snapshot === void 0) break;\n\t\t\t\tif ((snapshot[scope] ?? 0) > targetRevision) break;\n\t\t\t}\n\t\t\tpendingUpgrades.shift();\n\t\t\tdocument = this.applyPendingUpgrade(document, pending);\n\t\t}\n\t\treturn document;\n\t}\n\t/**\n\t* Applies one held-back upgrade, then re-applies the deletes the document\n\t* scope recorded after it so the hold-back cannot invert their order.\n\t*/\n\tapplyPendingUpgrade(document, pending) {\n\t\tdocument = applyUpgradeDocumentAction(document, pending.action, pending.upgradePath);\n\t\tfor (const deleteAction of pending.subsequentDeletes) document = applyDeleteDocumentAction(document, deleteAction);\n\t\treturn document;\n\t}\n\t/**\n\t* Copies the current document revisions onto the document. Overwrites the\n\t* requested scope revision with the target revision, if provided.\n\t*/\n\tasync stampRevisions(document, documentId, scope, branch, targetRevision, signal) {\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tdocument.header.revision = revisions.revision;\n\t\tif (targetRevision !== void 0) document.header.revision = {\n\t\t\t...document.header.revision,\n\t\t\t[scope]: targetRevision + 1\n\t\t};\n\t\tdocument.header.lastModifiedAtUtcIso = revisions.latestTimestamp;\n\t\treturn document;\n\t}\n\t/** The stored operation at `index`, or undefined if it is no longer there. */\n\tasync operationAt(documentId, scope, branch, index, signal) {\n\t\tif (index < 0) return;\n\t\tconst operation = (await this.operationStore.getSince(documentId, scope, branch, index - 1, void 0, {\n\t\t\tcursor: \"0\",\n\t\t\tlimit: 1\n\t\t}, signal)).results[0];\n\t\treturn operation && operation.index === index ? operation : void 0;\n\t}\n\t/**\n\t* Resolves which module version to use for a given operation in phase 2.\n\t*\n\t* Uses the validated-upgrade boundary rules from D7:\n\t* - If `input.revision` is present: op.index < revision[scope] → before the upgrade boundary\n\t* - Otherwise: timestamp fallback\n\t* - Falls back to final module version when neither is decidable\n\t*/\n\tresolveModuleVersionForOp(opIndex, opTimestamp, scope, validatedUpgrades, finalVersion) {\n\t\tif (validatedUpgrades.length === 0) return finalVersion;\n\t\tlet currentVersion = validatedUpgrades[0]?.fromVersion;\n\t\tfor (const upgrade of validatedUpgrades) {\n\t\t\tlet beforeUpgrade;\n\t\t\tif (upgrade.revision !== void 0) beforeUpgrade = opIndex < (upgrade.revision[scope] ?? 0);\n\t\t\telse beforeUpgrade = opTimestamp < upgrade.timestampUtcMs;\n\t\t\tif (beforeUpgrade) return currentVersion;\n\t\t\tcurrentVersion = upgrade.toVersion;\n\t\t}\n\t\treturn currentVersion;\n\t}\n\tasync warmMissRebuild(baseDocument, baseRevision, documentId, scope, branch, targetRevision, signal) {\n\t\tconst documentType = baseDocument.header.documentType;\n\t\tconst docScopeNextIndex = baseDocument.header.revision[\"document\"] ?? 0;\n\t\tif ((await this.operationStore.getSince(documentId, \"document\", branch, docScopeNextIndex - 1, void 0, void 0, signal)).results.length > 0) return this.coldMissRebuild(documentId, scope, branch, targetRevision, signal);\n\t\tconst module = this.registry.getModule(documentType, extractModuleVersion(baseDocument));\n\t\tlet document = copyDocument(baseDocument);\n\t\tlet needsFullReplay = false;\n\t\ttry {\n\t\t\tconst pagedResults = await this.operationStore.getSince(documentId, scope, branch, baseRevision, void 0, void 0, signal);\n\t\t\tfor (const operation of pagedResults.results) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\tif (targetRevision !== void 0 && operation.index > targetRevision) break;\n\t\t\t\tif (operation.skip > 0) {\n\t\t\t\t\tneedsFullReplay = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (isDenied(operation)) document = appendWithoutApplying(document, operation, scope);\n\t\t\t\telse {\n\t\t\t\t\tconst protocolVersion = baseReducerVersion(document.header);\n\t\t\t\t\tdocument = withProtocolVersions(module.reducer(document, operation.action, void 0, {\n\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\tprotocolVersion,\n\t\t\t\t\t\treplayOptions: { operation },\n\t\t\t\t\t\tskipIndexValidation: true\n\t\t\t\t\t}), document.header.protocolVersions);\n\t\t\t\t}\n\t\t\t\tif (targetRevision !== void 0 && operation.index === targetRevision) break;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthrow new Error(`Failed to rebuild document ${documentId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t}\n\t\tif (needsFullReplay) return this.coldMissRebuild(documentId, scope, branch, targetRevision, signal, false);\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tdocument.header.revision = revisions.revision;\n\t\tif (targetRevision !== void 0) document.header.revision = {\n\t\t\t...document.header.revision,\n\t\t\t[scope]: targetRevision + 1\n\t\t};\n\t\tdocument.header.lastModifiedAtUtcIso = revisions.latestTimestamp;\n\t\treturn document;\n\t}\n\tfindNearestOlderSnapshot(snapshots, targetRevision) {\n\t\tlet nearest = void 0;\n\t\tfor (const snapshot of snapshots) if (snapshot.revision < targetRevision) {\n\t\t\tif (!nearest || snapshot.revision > nearest.revision) nearest = snapshot;\n\t\t}\n\t\treturn nearest;\n\t}\n\tmakeStreamKey(documentId, scope, branch) {\n\t\treturn `${documentId}:${scope}:${branch}`;\n\t}\n\tgetOrCreateStream(key) {\n\t\tlet stream = this.streams.get(key);\n\t\tif (!stream) {\n\t\t\tif (this.streams.size >= this.config.maxDocuments) {\n\t\t\t\tconst evictKey = this.lruTracker.evict();\n\t\t\t\tif (evictKey) this.streams.delete(evictKey);\n\t\t\t}\n\t\t\tstream = {\n\t\t\t\tkey,\n\t\t\t\tringBuffer: new RingBuffer(this.config.ringBufferSize)\n\t\t\t};\n\t\t\tthis.streams.set(key, stream);\n\t\t}\n\t\tthis.lruTracker.touch(key);\n\t\treturn stream;\n\t}\n\tisKeyframeRevision(revision) {\n\t\treturn revision > 0 && revision % this.config.keyframeInterval === 0;\n\t}\n};\n//#endregion\n//#region src/events/event-bus.ts\nvar EventBus = class {\n\teventTypeToSubscribers = /* @__PURE__ */ new Map();\n\tsubscribe(type, subscriber) {\n\t\tlet list = this.eventTypeToSubscribers.get(type);\n\t\tif (!list) {\n\t\t\tlist = [];\n\t\t\tthis.eventTypeToSubscribers.set(type, list);\n\t\t}\n\t\tlist.push(subscriber);\n\t\tlet done = false;\n\t\treturn () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tconst arr = this.eventTypeToSubscribers.get(type);\n\t\t\tif (!arr) return;\n\t\t\tconst idx = arr.indexOf(subscriber);\n\t\t\tif (idx !== -1) arr.splice(idx, 1);\n\t\t\tif (arr.length === 0) this.eventTypeToSubscribers.delete(type);\n\t\t};\n\t}\n\tasync emit(type, data) {\n\t\tconst list = this.eventTypeToSubscribers.get(type);\n\t\tif (!list || list.length === 0) return;\n\t\tconst snapshot = list.slice();\n\t\tconst errors = [];\n\t\tfor (const fn of snapshot) try {\n\t\t\tawait Promise.resolve(fn(type, data));\n\t\t} catch (err) {\n\t\t\terrors.push(err);\n\t\t}\n\t\tif (errors.length > 0) throw new EventBusAggregateError(errors);\n\t}\n};\n//#endregion\n//#region src/registry/implementation.ts\n/**\n* In-memory implementation of the IDocumentModelRegistry interface.\n* Manages document model modules with version-aware storage and upgrade manifest support.\n*/\nvar DocumentModelRegistry = class {\n\tmodules = [];\n\tmanifests = [];\n\tregisterModules(...modules) {\n\t\treturn modules.map((module) => {\n\t\t\ttry {\n\t\t\t\tconst documentType = module.documentModel.global.id;\n\t\t\t\tconst version = module.version ?? 1;\n\t\t\t\tfor (let i = 0; i < this.modules.length; i++) {\n\t\t\t\t\tconst existing = this.modules[i];\n\t\t\t\t\tconst existingType = existing.documentModel.global.id;\n\t\t\t\t\tconst existingVersion = existing.version ?? 1;\n\t\t\t\t\tif (existingType === documentType && existingVersion === version) throw new DuplicateModuleError(documentType, version);\n\t\t\t\t}\n\t\t\t\tthis.modules.push(module);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\titem: module\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\titem: module,\n\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\tunregisterModules(...documentTypes) {\n\t\tlet allFound = true;\n\t\tfor (const documentType of documentTypes) {\n\t\t\tif (!this.modules.some((m) => m.documentModel.global.id === documentType)) allFound = false;\n\t\t\tthis.modules = this.modules.filter((m) => m.documentModel.global.id !== documentType);\n\t\t}\n\t\treturn allFound;\n\t}\n\tgetModule(documentType, version) {\n\t\tlet latestModule;\n\t\tlet latestVersion = -1;\n\t\tfor (let i = 0; i < this.modules.length; i++) {\n\t\t\tconst module = this.modules[i];\n\t\t\tconst moduleType = module.documentModel.global.id;\n\t\t\tconst moduleVersion = module.version ?? 1;\n\t\t\tif (moduleType === documentType) {\n\t\t\t\tif (version !== void 0 && moduleVersion === version) return module;\n\t\t\t\tif (moduleVersion > latestVersion) {\n\t\t\t\t\tlatestModule = module;\n\t\t\t\t\tlatestVersion = moduleVersion;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (version === void 0 && latestModule !== void 0) return latestModule;\n\t\tthrow new ModuleNotFoundError(documentType, version);\n\t}\n\tgetAllModules() {\n\t\treturn [...this.modules];\n\t}\n\tclear() {\n\t\tthis.modules = [];\n\t\tthis.manifests = [];\n\t}\n\tgetSupportedVersions(documentType) {\n\t\tconst versions = [];\n\t\tfor (const module of this.modules) if (module.documentModel.global.id === documentType) versions.push(module.version ?? 1);\n\t\tif (versions.length === 0) throw new ModuleNotFoundError(documentType);\n\t\treturn versions.sort((a, b) => a - b);\n\t}\n\tgetLatestVersion(documentType) {\n\t\tlet latest = -1;\n\t\tlet found = false;\n\t\tfor (const module of this.modules) if (module.documentModel.global.id === documentType) {\n\t\t\tfound = true;\n\t\t\tconst version = module.version ?? 1;\n\t\t\tif (version > latest) latest = version;\n\t\t}\n\t\tif (!found) throw new ModuleNotFoundError(documentType);\n\t\treturn latest;\n\t}\n\tregisterUpgradeManifests(...manifestsToRegister) {\n\t\treturn manifestsToRegister.map((manifestToRegister) => {\n\t\t\ttry {\n\t\t\t\tif (!manifestToRegister.documentType) throw new Error(\"Upgrade manifest is missing a documentType\");\n\t\t\t\tfor (const registeredManifest of this.manifests) if (registeredManifest.documentType === manifestToRegister.documentType) throw new DuplicateManifestError(manifestToRegister.documentType);\n\t\t\t\tthis.manifests.push(manifestToRegister);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\titem: manifestToRegister\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\titem: manifestToRegister,\n\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\tunregisterUpgradeManifests(...documentTypes) {\n\t\tlet allFound = true;\n\t\tfor (const documentType of documentTypes) {\n\t\t\tif (!this.manifests.some((m) => m.documentType === documentType)) allFound = false;\n\t\t\tthis.manifests = this.manifests.filter((m) => m.documentType !== documentType);\n\t\t}\n\t\treturn allFound;\n\t}\n\tgetUpgradeManifest(documentType) {\n\t\tfor (let i = 0; i < this.manifests.length; i++) if (this.manifests[i].documentType === documentType) return this.manifests[i];\n\t\tthrow new ManifestNotFoundError(documentType);\n\t}\n\tcomputeUpgradePath(documentType, fromVersion, toVersion) {\n\t\tif (fromVersion === toVersion) return [];\n\t\tif (toVersion < fromVersion) throw new DowngradeNotSupportedError$1(documentType, fromVersion, toVersion);\n\t\tconst manifest = this.getUpgradeManifest(documentType);\n\t\tconst path = [];\n\t\tfor (let v = fromVersion + 1; v <= toVersion; v++) {\n\t\t\tconst key = `v${v}`;\n\t\t\tif (!(key in manifest.upgrades)) throw new MissingUpgradeTransitionError(documentType, v - 1, v);\n\t\t\tconst transition = manifest.upgrades[key];\n\t\t\tpath.push(transition);\n\t\t}\n\t\treturn path;\n\t}\n\tgetUpgradeReducer(documentType, fromVersion, toVersion) {\n\t\tif (toVersion !== fromVersion + 1) throw new InvalidUpgradeStepError(documentType, fromVersion, toVersion);\n\t\tconst manifest = this.getUpgradeManifest(documentType);\n\t\tconst key = `v${toVersion}`;\n\t\tif (!(key in manifest.upgrades)) throw new MissingUpgradeTransitionError(documentType, fromVersion, toVersion);\n\t\treturn manifest.upgrades[key].upgradeReducer;\n\t}\n};\n//#endregion\n//#region src/storage/kysely/keyframe-store.ts\nvar KyselyKeyframeStore = class KyselyKeyframeStore {\n\tdb;\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyKeyframeStore(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tasync putKeyframe(documentId, scope, branch, revision, document, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst write = async (trx) => {\n\t\t\tawait acquirePurgeLocks(trx, [documentId], \"shared\");\n\t\t\tif ((await findPurged(trx, [documentId])).has(documentId)) return;\n\t\t\tawait trx.insertInto(\"Keyframe\").values({\n\t\t\t\tdocumentId,\n\t\t\t\tdocumentType: document.header.documentType,\n\t\t\t\tscope,\n\t\t\t\tbranch,\n\t\t\t\trevision,\n\t\t\t\tdocument\n\t\t\t}).onConflict((oc) => oc.columns([\n\t\t\t\t\"documentId\",\n\t\t\t\t\"scope\",\n\t\t\t\t\"branch\",\n\t\t\t\t\"revision\"\n\t\t\t]).doUpdateSet({ document })).execute();\n\t\t};\n\t\tif (this.trx) {\n\t\t\tawait write(this.trx);\n\t\t\treturn;\n\t\t}\n\t\tawait this.db.transaction().execute(write);\n\t}\n\tasync findNearestKeyframe(documentId, scope, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst row = await this.queryExecutor.selectFrom(\"Keyframe\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"revision\", \"<=\", targetRevision).orderBy(\"revision\", \"desc\").limit(1).executeTakeFirst();\n\t\tif (!row) return;\n\t\treturn {\n\t\t\trevision: row.revision,\n\t\t\tdocument: row.document\n\t\t};\n\t}\n\tasync listKeyframes(documentId, scope, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.selectFrom(\"Keyframe\").selectAll().where(\"documentId\", \"=\", documentId).orderBy(\"revision\", \"asc\");\n\t\tif (scope !== void 0) query = query.where(\"scope\", \"=\", scope);\n\t\tif (branch !== void 0) query = query.where(\"branch\", \"=\", branch);\n\t\treturn (await query.execute()).map((row) => ({\n\t\t\tscope: row.scope,\n\t\t\tbranch: row.branch,\n\t\t\trevision: row.revision,\n\t\t\tdocument: row.document\n\t\t}));\n\t}\n\tasync deleteKeyframes(documentId, scope, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.deleteFrom(\"Keyframe\").where(\"documentId\", \"=\", documentId);\n\t\tif (scope !== void 0 && branch !== void 0) query = query.where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch);\n\t\telse if (scope !== void 0) query = query.where(\"scope\", \"=\", scope);\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result.numDeletedRows || 0n);\n\t}\n};\n//#endregion\n//#region src/storage/kysely/pagination.ts\nconst DEFAULT_LIMIT = 100;\nfunction paginateRows(rows, paging, cursorOf, toItem, refetch) {\n\tlet hasMore = false;\n\tlet items = rows;\n\tif (paging?.limit && rows.length > paging.limit) {\n\t\thasMore = true;\n\t\titems = rows.slice(0, paging.limit);\n\t}\n\tconst nextCursor = hasMore && items.length > 0 ? cursorOf(items[items.length - 1]).toString() : void 0;\n\tconst cursor = paging?.cursor || \"0\";\n\tconst limit = paging?.limit || DEFAULT_LIMIT;\n\treturn {\n\t\tresults: items.map(toItem),\n\t\toptions: {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t},\n\t\tnextCursor,\n\t\tnext: hasMore ? () => refetch(nextCursor, limit) : void 0\n\t};\n}\n//#endregion\n//#region src/storage/txn.ts\nvar AtomicTransaction = class {\n\tdocumentId;\n\tdocumentType;\n\tscope;\n\tbranch;\n\tbaseRevision;\n\toperations = [];\n\tconstructor(documentId, documentType, scope, branch, baseRevision) {\n\t\tthis.documentId = documentId;\n\t\tthis.documentType = documentType;\n\t\tthis.scope = scope;\n\t\tthis.branch = branch;\n\t\tthis.baseRevision = baseRevision;\n\t}\n\taddOperations(...operations) {\n\t\tfor (const op of operations) this.operations.push({\n\t\t\tjobId: v4(),\n\t\t\topId: op.id,\n\t\t\tprevOpId: \"\",\n\t\t\tdocumentId: this.documentId,\n\t\t\tdocumentType: this.documentType,\n\t\t\tscope: this.scope,\n\t\t\tbranch: this.branch,\n\t\t\ttimestampUtcMs: new Date(op.timestampUtcMs),\n\t\t\tindex: op.index,\n\t\t\taction: JSON.stringify(op.action),\n\t\t\tskip: op.skip,\n\t\t\terror: op.error || null,\n\t\t\tdeniedReason: op.deniedReason || null,\n\t\t\thash: op.hash\n\t\t});\n\t}\n\tgetOperations() {\n\t\treturn this.operations;\n\t}\n};\n//#endregion\n//#region src/storage/kysely/store.ts\nvar _UniqueConstraintContext = class extends Error {\n\tdocumentId;\n\tscope;\n\tbranch;\n\trevision;\n\tstagedOps;\n\tconstructor(documentId, scope, branch, revision, stagedOps) {\n\t\tsuper(\"unique constraint\");\n\t\tthis.documentId = documentId;\n\t\tthis.scope = scope;\n\t\tthis.branch = branch;\n\t\tthis.revision = revision;\n\t\tthis.stagedOps = stagedOps;\n\t\tthis.name = \"UniqueConstraintContext\";\n\t}\n};\nvar KyselyOperationStore = class KyselyOperationStore {\n\tdb;\n\ttrx;\n\tliveIds;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\t/** `liveIds`: ids the transaction read untombstoned under its shared lock. */\n\twithTransaction(trx, liveIds) {\n\t\tconst instance = new KyselyOperationStore(this.db);\n\t\tinstance.trx = trx;\n\t\tinstance.liveIds = liveIds;\n\t\treturn instance;\n\t}\n\tasync apply(documentId, documentType, scope, branch, revision, fn, signal, condition) {\n\t\tif (this.trx) {\n\t\t\tlet executeResult = null;\n\t\t\tlet uniqueCtx = null;\n\t\t\ttry {\n\t\t\t\texecuteResult = await this.executeApply(this.trx, documentId, documentType, scope, branch, revision, fn, signal, condition);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof _UniqueConstraintContext) uniqueCtx = error;\n\t\t\t\telse throw error;\n\t\t\t}\n\t\t\tif (uniqueCtx !== null) return this.resolveUniqueConstraint(uniqueCtx);\n\t\t\treturn executeResult;\n\t\t} else {\n\t\t\tlet transactionResult = null;\n\t\t\tlet uniqueCtx = null;\n\t\t\ttry {\n\t\t\t\ttransactionResult = await this.db.transaction().execute(async (trx) => {\n\t\t\t\t\treturn this.executeApply(trx, documentId, documentType, scope, branch, revision, fn, signal, condition);\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof _UniqueConstraintContext) uniqueCtx = error;\n\t\t\t\telse throw error;\n\t\t\t}\n\t\t\tif (uniqueCtx !== null) return this.resolveUniqueConstraint(uniqueCtx);\n\t\t\treturn transactionResult;\n\t\t}\n\t}\n\tasync resolveUniqueConstraint(ctx) {\n\t\tlet replayOps = null;\n\t\ttry {\n\t\t\treplayOps = await this.findIdempotentReplay(this.db, ctx.documentId, ctx.scope, ctx.branch, ctx.revision, ctx.stagedOps);\n\t\t} catch {}\n\t\tif (replayOps !== null) return replayOps;\n\t\tconst op = ctx.stagedOps[0];\n\t\tthrow new DuplicateOperationError(`${op.opId} at index ${op.index} with skip ${op.skip}`);\n\t}\n\tasync executeApply(trx, documentId, documentType, scope, branch, revision, fn, signal, condition) {\n\t\tthrowIfAborted(signal);\n\t\tconst atomicTxn = new AtomicTransaction(documentId, documentType, scope, branch, revision);\n\t\tawait fn(atomicTxn);\n\t\tconst operations = atomicTxn.getOperations();\n\t\tif (operations.length === 0) return [];\n\t\tconst purgedHead = this.liveIds?.has(documentId) ? void 0 : await this.refusePurgedAppend(trx, documentId, operations);\n\t\tif (purgedHead !== void 0) return purgedHead;\n\t\tif (condition) await this.acquireStreamLocks(trx, documentId, scope, branch, condition);\n\t\tconst latestOp = await trx.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).orderBy(\"index\", \"desc\").limit(1).executeTakeFirst();\n\t\tconst currentRevision = latestOp ? latestOp.index : -1;\n\t\tif (currentRevision !== revision - 1) {\n\t\t\tlet replayOps = null;\n\t\t\ttry {\n\t\t\t\treplayOps = await this.findIdempotentReplay(trx, documentId, scope, branch, revision, operations);\n\t\t\t} catch {}\n\t\t\tif (replayOps !== null) return replayOps;\n\t\t\tif (revision === 0 && this.isCreate(operations)) throw new DocumentAlreadyExistsError(documentId, scope, currentRevision);\n\t\t\tthrow new RevisionMismatchError(currentRevision + 1, revision);\n\t\t}\n\t\tlet prevOpId = latestOp?.opId || \"\";\n\t\tfor (const op of operations) {\n\t\t\top.prevOpId = prevOpId;\n\t\t\tprevOpId = op.opId;\n\t\t}\n\t\tlet insertedCount = operations.length;\n\t\ttry {\n\t\t\tif (condition && condition.streams.length > 0) insertedCount = await this.insertGuarded(trx, operations, condition);\n\t\t\telse await trx.insertInto(\"Operation\").values(operations).execute();\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message.includes(\"unique constraint\")) throw new _UniqueConstraintContext(documentId, scope, branch, revision, operations);\n\t\t\tthrow error;\n\t\t}\n\t\tif (insertedCount !== operations.length) throw new AppendConditionFailedError(condition);\n\t\treturn operations.map((op) => ({\n\t\t\tindex: op.index,\n\t\t\ttimestampUtcMs: op.timestampUtcMs.toISOString(),\n\t\t\thash: op.hash,\n\t\t\tskip: op.skip,\n\t\t\terror: op.error || void 0,\n\t\t\tdeniedReason: op.deniedReason || void 0,\n\t\t\tid: op.opId,\n\t\t\taction: JSON.parse(op.action)\n\t\t}));\n\t}\n\t/**\n\t* Locks the written stream and every read-set stream, in sorted key order\n\t* so that overlapping concurrent appends serialize rather than deadlock.\n\t* The locks are still taken one row at a time, so the query preserves that\n\t* order. It must stay separate from the guarded insert, which would\n\t* otherwise read a snapshot taken before the locks were held.\n\t*/\n\tasync acquireStreamLocks(trx, documentId, scope, branch, condition) {\n\t\tconst keys = /* @__PURE__ */ new Set([`${documentId}:${scope}:${branch}`]);\n\t\tfor (const stream of condition.streams) keys.add(`${stream.documentId}:${stream.scope}:${stream.branch}`);\n\t\tconst sortedKeys = sql.join([...keys].sort());\n\t\tawait sql`\n with ordered as materialized (\n select key\n from unnest(array[${sortedKeys}]::text[]) with ordinality as t(key, ord)\n order by ord\n )\n select pg_advisory_xact_lock(hashtext(key)) from ordered\n `.execute(trx);\n\t}\n\t/**\n\t* Inserts the staged operations with the condition compiled in as a WHERE\n\t* NOT EXISTS guard, making the check and the append one statement. Returns\n\t* the rows inserted; zero means the guard failed and nothing was written.\n\t*/\n\tasync insertGuarded(trx, operations, condition) {\n\t\tconst branches = operations.map((op) => trx.selectNoFrom([\n\t\t\tsql`${op.jobId}::text`.as(\"jobId\"),\n\t\t\tsql`${op.opId}::text`.as(\"opId\"),\n\t\t\tsql`${op.prevOpId}::text`.as(\"prevOpId\"),\n\t\t\tsql`${op.documentId}::text`.as(\"documentId\"),\n\t\t\tsql`${op.documentType}::text`.as(\"documentType\"),\n\t\t\tsql`${op.scope}::text`.as(\"scope\"),\n\t\t\tsql`${op.branch}::text`.as(\"branch\"),\n\t\t\tsql`${op.timestampUtcMs}::timestamptz`.as(\"timestampUtcMs\"),\n\t\t\tsql`${op.index}::integer`.as(\"index\"),\n\t\t\tsql`${op.action}::jsonb`.as(\"action\"),\n\t\t\tsql`${op.skip}::integer`.as(\"skip\"),\n\t\t\tsql`${op.error ?? null}::text`.as(\"error\"),\n\t\t\tsql`${op.deniedReason ?? null}::text`.as(\"deniedReason\"),\n\t\t\tsql`${op.hash}::text`.as(\"hash\")\n\t\t]).where((eb) => eb.not(eb.exists(eb.selectFrom(\"Operation\").select(\"Operation.id\").where((web) => web.or(condition.streams.map((s) => web.and([\n\t\t\tweb(\"Operation.documentId\", \"=\", s.documentId),\n\t\t\tweb(\"Operation.scope\", \"=\", s.scope),\n\t\t\tweb(\"Operation.branch\", \"=\", s.branch),\n\t\t\tweb(\"Operation.index\", \">\", s.revision)\n\t\t]))))))));\n\t\tlet expression = branches[0];\n\t\tfor (let i = 1; i < branches.length; i++) expression = expression.unionAll(branches[i]);\n\t\treturn (await trx.insertInto(\"Operation\").columns([\n\t\t\t\"jobId\",\n\t\t\t\"opId\",\n\t\t\t\"prevOpId\",\n\t\t\t\"documentId\",\n\t\t\t\"documentType\",\n\t\t\t\"scope\",\n\t\t\t\"branch\",\n\t\t\t\"timestampUtcMs\",\n\t\t\t\"index\",\n\t\t\t\"action\",\n\t\t\t\"skip\",\n\t\t\t\"error\",\n\t\t\t\"deniedReason\",\n\t\t\t\"hash\"\n\t\t]).expression(expression).returning(\"id\").execute()).length;\n\t}\n\tasync findIdempotentReplay(executor, documentId, scope, branch, revision, stagedOps) {\n\t\tconst minIndex = revision;\n\t\tconst maxIndex = revision + stagedOps.length - 1;\n\t\tconst storedRows = await executor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"index\", \">=\", minIndex).where(\"index\", \"<=\", maxIndex).orderBy(\"index\", \"asc\").execute();\n\t\tif (storedRows.length !== stagedOps.length) return null;\n\t\tfor (let i = 0; i < stagedOps.length; i++) {\n\t\t\tconst staged = stagedOps[i];\n\t\t\tconst stored = storedRows[i];\n\t\t\tif (stored.opId !== staged.opId || stored.index !== staged.index || stored.skip !== staged.skip) return null;\n\t\t}\n\t\treturn storedRows.map((row) => this.rowToOperation(row));\n\t}\n\t/** A purged stream refuses appends; a marker gets the stored one back. */\n\tasync refusePurgedAppend(trx, documentId, operations) {\n\t\tif (!(await findPurged(trx, [documentId])).has(documentId)) return;\n\t\tif (!operations.every((operation) => this.isMarker(operation))) throw new DocumentPurgedError(documentId);\n\t\treturn (await trx.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(sql`action->>'type' = ${PURGE_DOCUMENT}`).orderBy(\"index\", \"asc\").execute()).map((row) => this.rowToOperation(row));\n\t}\n\tisMarker(operation) {\n\t\treturn this.actionType(operation) === PURGE_DOCUMENT;\n\t}\n\tactionType(operation) {\n\t\tlet action = operation.action;\n\t\tif (typeof action === \"string\") try {\n\t\t\taction = JSON.parse(action);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (typeof action === \"object\" && action !== null && \"type\" in action && typeof action.type === \"string\") return action.type;\n\t}\n\t/** True when the staged write creates a document rather than appending to one. */\n\tisCreate(operations) {\n\t\tfor (const operation of operations) {\n\t\t\tlet action = operation.action;\n\t\t\tif (typeof action === \"string\") try {\n\t\t\t\taction = JSON.parse(action);\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (typeof action === \"object\" && action !== null && \"type\" in action && typeof action.type === \"string\" && action.type === \"CREATE_DOCUMENT\") return true;\n\t\t}\n\t\treturn false;\n\t}\n\t/**\n\t* The paging cursor here encodes the index to resume from (one past the\n\t* last row returned), not the last row's own index. This keeps \"0\" an\n\t* unambiguous start-of-stream sentinel even when a page ends at index 0\n\t* (e.g. `limit: 1` on a fresh stream), which would otherwise make\n\t* `nextCursor` equal the start cursor and loop a caller that walks pages\n\t* forever.\n\t*/\n\tasync getSince(documentId, scope, branch, revision, filter, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"index\", \">\", revision).orderBy(\"index\", \"asc\");\n\t\tif (filter) {\n\t\t\tif (filter.actionTypes && filter.actionTypes.length > 0) {\n\t\t\t\tconst actionTypesArray = filter.actionTypes.map((t) => `'${t.replace(/'/g, \"''\")}'`).join(\",\");\n\t\t\t\tquery = query.where(sql`action->>'type' = ANY(ARRAY[${sql.raw(actionTypesArray)}]::text[])`);\n\t\t\t}\n\t\t\tif (filter.timestampFrom) query = query.where(\"timestampUtcMs\", \">=\", new Date(filter.timestampFrom));\n\t\t\tif (filter.timestampTo) query = query.where(\"timestampUtcMs\", \"<=\", new Date(filter.timestampTo));\n\t\t\tif (filter.sinceRevision !== void 0) query = query.where(\"index\", \">=\", filter.sinceRevision);\n\t\t}\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (Number.isFinite(cursorValue) && cursorValue > 0) query = query.where(\"index\", \">=\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.index + 1, (row) => this.rowToOperation(row), (cursor, limit) => this.getSince(documentId, scope, branch, revision, filter, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getSinceId(id, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"id\", \">\", id).orderBy(\"id\", \"asc\");\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (cursorValue > 0) query = query.where(\"id\", \">\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.id, (row) => this.rowToOperationWithContext(row), (cursor, limit) => this.getSinceId(id, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\t/**\n\t* The paging cursor here encodes the index to resume from (one past the\n\t* last row returned), not the last row's own index, for the same reason as\n\t* `getSince`: a page ending at index 0 must not produce a cursor that is\n\t* indistinguishable from the start-of-stream sentinel.\n\t*/\n\tasync getConflicting(documentId, scope, branch, minTimestamp, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"timestampUtcMs\", \">=\", new Date(minTimestamp)).orderBy(\"index\", \"asc\");\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (Number.isFinite(cursorValue) && cursorValue > 0) query = query.where(\"index\", \">=\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.index + 1, (row) => this.rowToOperation(row), (cursor, limit) => this.getConflicting(documentId, scope, branch, minTimestamp, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getRevisions(documentId, branch, signal) {\n\t\tthrowIfAborted(signal);\n\t\tconst scopeRevisions = await this.queryExecutor.selectFrom(\"Operation\").select(\"scope\").select((eb) => eb.fn.max(\"index\").as(\"index\")).where(\"documentId\", \"=\", documentId).where(\"branch\", \"=\", branch).groupBy(\"scope\").execute();\n\t\tconst latest = await this.queryExecutor.selectFrom(\"Operation\").select((eb) => eb.fn.max(\"timestampUtcMs\").as(\"latestTimestamp\")).where(\"documentId\", \"=\", documentId).where(\"branch\", \"=\", branch).executeTakeFirst();\n\t\tconst revision = {};\n\t\tfor (const row of scopeRevisions) revision[row.scope] = row.index + 1;\n\t\treturn {\n\t\t\trevision,\n\t\t\tlatestTimestamp: latest?.latestTimestamp ? new Date(latest.latestTimestamp).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString()\n\t\t};\n\t}\n\tasync getStreamLatestTimestamp(documentId, scope, branch, signal) {\n\t\tconst latest = await this.queryExecutor.selectFrom(\"Operation\").select((eb) => eb.fn.max(\"timestampUtcMs\").as(\"latestTimestamp\")).where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).executeTakeFirst();\n\t\treturn latest?.latestTimestamp ? new Date(latest.latestTimestamp).toISOString() : void 0;\n\t}\n\tasync findOperationIds(documentId, scope, branch, opIds, signal) {\n\t\tthrowIfAborted(signal);\n\t\tif (opIds.length === 0) return /* @__PURE__ */ new Set();\n\t\tconst rows = await this.queryExecutor.selectFrom(\"Operation\").select(\"opId\").distinct().where(\"opId\", \"in\", opIds).where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).execute();\n\t\treturn new Set(rows.map((row) => row.opId));\n\t}\n\tasync getOperationsByIds(documentId, scope, branch, opIds, signal) {\n\t\tthrowIfAborted(signal);\n\t\tif (opIds.length === 0) return [];\n\t\tconst rows = await this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"opId\", \"in\", opIds).where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).orderBy(\"index\", \"asc\").execute();\n\t\tconst latest = /* @__PURE__ */ new Map();\n\t\tfor (const row of rows) latest.set(row.opId, this.rowToOperation(row));\n\t\treturn [...latest.values()];\n\t}\n\trowToOperation(row) {\n\t\treturn {\n\t\t\tindex: row.index,\n\t\t\ttimestampUtcMs: row.timestampUtcMs.toISOString(),\n\t\t\thash: row.hash,\n\t\t\tskip: row.skip,\n\t\t\terror: row.error || void 0,\n\t\t\tdeniedReason: row.deniedReason || void 0,\n\t\t\tid: row.opId,\n\t\t\taction: row.action\n\t\t};\n\t}\n\trowToOperationWithContext(row) {\n\t\treturn {\n\t\t\toperation: this.rowToOperation(row),\n\t\t\tcontext: {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tscope: row.scope,\n\t\t\t\tbranch: row.branch,\n\t\t\t\tordinal: row.id\n\t\t\t}\n\t\t};\n\t}\n};\n//#endregion\n//#region src/storage/pool-instrumentation.ts\n/**\n* Wraps an existing pg.Pool with acquire-wait timing and an event\n* subscription surface. The pool is mutated in place: pool.connect()\n* is replaced with a timing wrapper so all callers (Kysely included)\n* pick up the instrumentation transparently.\n*/\nfunction instrumentPgPool(pool, name) {\n\tconst listeners = /* @__PURE__ */ new Set();\n\tconst originalConnect = pool.connect.bind(pool);\n\tconst wrappedConnect = async () => {\n\t\tconst start = performance.now();\n\t\tconst client = await originalConnect();\n\t\tconst durationMs = performance.now() - start;\n\t\tfor (const listener of listeners) try {\n\t\t\tlistener(durationMs);\n\t\t} catch {}\n\t\treturn client;\n\t};\n\tpool.connect = wrappedConnect;\n\treturn {\n\t\tname,\n\t\tgetStats() {\n\t\t\treturn {\n\t\t\t\tsize: pool.totalCount,\n\t\t\t\tidle: pool.idleCount,\n\t\t\t\twaiting: pool.waitingCount\n\t\t\t};\n\t\t},\n\t\tonAcquire(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t}\n\t};\n}\nfunction createForwardingPoolInstrumentation(name) {\n\tconst listeners = /* @__PURE__ */ new Set();\n\tlet stats = {\n\t\tsize: 0,\n\t\tidle: 0,\n\t\twaiting: 0\n\t};\n\treturn {\n\t\tname,\n\t\tgetStats() {\n\t\t\treturn stats;\n\t\t},\n\t\tonAcquire(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tpushSamples(durations) {\n\t\t\tfor (const durationMs of durations) for (const listener of listeners) try {\n\t\t\t\tlistener(durationMs);\n\t\t\t} catch {}\n\t\t},\n\t\tupdateStats(next) {\n\t\t\tstats = next;\n\t\t}\n\t};\n}\n//#endregion\n//#region src/storage/migrations/001_create_operation_table.ts\nvar _001_create_operation_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$25 });\nasync function up$25(db) {\n\tawait db.schema.createTable(\"Operation\").addColumn(\"id\", \"serial\", (col) => col.primaryKey()).addColumn(\"jobId\", \"text\", (col) => col.notNull()).addColumn(\"opId\", \"text\", (col) => col.notNull()).addColumn(\"prevOpId\", \"text\", (col) => col.notNull()).addColumn(\"writeTimestampUtcMs\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"timestampUtcMs\", \"timestamptz\", (col) => col.notNull()).addColumn(\"index\", \"integer\", (col) => col.notNull()).addColumn(\"action\", \"jsonb\", (col) => col.notNull()).addColumn(\"skip\", \"integer\", (col) => col.notNull()).addColumn(\"error\", \"text\").addColumn(\"hash\", \"text\", (col) => col.notNull()).addUniqueConstraint(\"unique_revision\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"index\"\n\t]).addUniqueConstraint(\"unique_operation_instance\", [\n\t\t\"opId\",\n\t\t\"index\",\n\t\t\"skip\"\n\t]).execute();\n\tawait db.schema.createIndex(\"streamOperations\").on(\"Operation\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"id\"\n\t]).execute();\n\tawait db.schema.createIndex(\"branchlessStreamOperations\").on(\"Operation\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"id\"\n\t]).execute();\n}\n//#endregion\n//#region src/storage/migrations/002_create_keyframe_table.ts\nvar _002_create_keyframe_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$24 });\nasync function up$24(db) {\n\tawait db.schema.createTable(\"Keyframe\").addColumn(\"id\", \"serial\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"revision\", \"integer\", (col) => col.notNull()).addColumn(\"document\", \"jsonb\", (col) => col.notNull()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_keyframe\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"revision\"\n\t]).execute();\n\tawait db.schema.createIndex(\"keyframe_lookup\").on(\"Keyframe\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"revision\"\n\t]).execute();\n}\n//#endregion\n//#region src/storage/migrations/003_create_document_table.ts\nvar _003_create_document_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$23 });\nasync function up$23(db) {\n\tawait db.schema.createTable(\"Document\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/004_create_document_relationship_table.ts\nvar _004_create_document_relationship_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$22 });\nasync function up$22(db) {\n\tawait db.schema.createTable(\"DocumentRelationship\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"sourceId\", \"text\", (col) => col.notNull().references(\"Document.id\").onDelete(\"cascade\")).addColumn(\"targetId\", \"text\", (col) => col.notNull().references(\"Document.id\").onDelete(\"cascade\")).addColumn(\"relationshipType\", \"text\", (col) => col.notNull()).addColumn(\"metadata\", \"jsonb\").addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_source_target_type\", [\n\t\t\"sourceId\",\n\t\t\"targetId\",\n\t\t\"relationshipType\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_relationship_source\").on(\"DocumentRelationship\").column(\"sourceId\").execute();\n\tawait db.schema.createIndex(\"idx_relationship_target\").on(\"DocumentRelationship\").column(\"targetId\").execute();\n\tawait db.schema.createIndex(\"idx_relationship_type\").on(\"DocumentRelationship\").column(\"relationshipType\").execute();\n}\n//#endregion\n//#region src/storage/migrations/005_create_indexer_state_table.ts\nvar _005_create_indexer_state_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$21 });\nasync function up$21(db) {\n\tawait db.schema.createTable(\"IndexerState\").addColumn(\"id\", \"integer\", (col) => col.primaryKey().generatedAlwaysAsIdentity()).addColumn(\"lastOperationId\", \"integer\", (col) => col.notNull()).addColumn(\"lastOperationTimestamp\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/006_create_document_snapshot_table.ts\nvar _006_create_document_snapshot_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$20 });\nasync function up$20(db) {\n\tawait db.schema.createTable(\"DocumentSnapshot\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"slug\", \"text\").addColumn(\"name\", \"text\").addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"content\", \"jsonb\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"lastOperationIndex\", \"integer\", (col) => col.notNull()).addColumn(\"lastOperationHash\", \"text\", (col) => col.notNull()).addColumn(\"lastUpdatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"snapshotVersion\", \"integer\", (col) => col.notNull().defaultTo(1)).addColumn(\"identifiers\", \"jsonb\").addColumn(\"metadata\", \"jsonb\").addColumn(\"isDeleted\", \"boolean\", (col) => col.notNull().defaultTo(false)).addColumn(\"deletedAt\", \"timestamptz\").addUniqueConstraint(\"unique_doc_scope_branch\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_slug_scope_branch\").on(\"DocumentSnapshot\").columns([\n\t\t\"slug\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_doctype_scope_branch\").on(\"DocumentSnapshot\").columns([\n\t\t\"documentType\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_last_updated\").on(\"DocumentSnapshot\").column(\"lastUpdatedAt\").execute();\n\tawait db.schema.createIndex(\"idx_is_deleted\").on(\"DocumentSnapshot\").column(\"isDeleted\").execute();\n}\n//#endregion\n//#region src/storage/migrations/007_create_slug_mapping_table.ts\nvar _007_create_slug_mapping_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$19 });\nasync function up$19(db) {\n\tawait db.schema.createTable(\"SlugMapping\").addColumn(\"slug\", \"text\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_docid_scope_branch\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_slug_documentid\").on(\"SlugMapping\").column(\"documentId\").execute();\n}\n//#endregion\n//#region src/storage/migrations/008_create_view_state_table.ts\nvar _008_create_view_state_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$18 });\nasync function up$18(db) {\n\tawait db.schema.createTable(\"ViewState\").addColumn(\"readModelId\", \"text\", (col) => col.primaryKey()).addColumn(\"lastOrdinal\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"lastOperationTimestamp\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/009_create_operation_index_tables.ts\nvar _009_create_operation_index_tables_exports = /* @__PURE__ */ __exportAll({ up: () => up$17 });\nasync function up$17(db) {\n\tawait db.schema.createTable(\"document_collections\").addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"collectionId\", \"text\", (col) => col.notNull()).addColumn(\"joinedOrdinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"leftOrdinal\", \"bigint\").addPrimaryKeyConstraint(\"document_collections_pkey\", [\"documentId\", \"collectionId\"]).execute();\n\tawait db.schema.createIndex(\"idx_document_collections_collectionId\").on(\"document_collections\").column(\"collectionId\").execute();\n\tawait db.schema.createIndex(\"idx_doc_collections_collection_range\").on(\"document_collections\").columns([\"collectionId\", \"joinedOrdinal\"]).execute();\n\tawait db.schema.createTable(\"operation_index_operations\").addColumn(\"ordinal\", \"serial\", (col) => col.primaryKey()).addColumn(\"opId\", \"text\", (col) => col.notNull()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"timestampUtcMs\", \"text\", (col) => col.notNull()).addColumn(\"writeTimestampUtcMs\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"index\", \"integer\", (col) => col.notNull()).addColumn(\"skip\", \"integer\", (col) => col.notNull()).addColumn(\"hash\", \"text\", (col) => col.notNull()).addColumn(\"action\", \"jsonb\", (col) => col.notNull()).execute();\n\tawait db.schema.createIndex(\"idx_operation_index_operations_document\").on(\"operation_index_operations\").columns([\n\t\t\"documentId\",\n\t\t\"branch\",\n\t\t\"scope\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_operation_index_operations_ordinal\").on(\"operation_index_operations\").column(\"ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/010_create_sync_tables.ts\nvar _010_create_sync_tables_exports = /* @__PURE__ */ __exportAll({ up: () => up$16 });\nasync function up$16(db) {\n\tawait db.schema.createTable(\"sync_remotes\").addColumn(\"name\", \"text\", (col) => col.primaryKey()).addColumn(\"collection_id\", \"text\", (col) => col.notNull()).addColumn(\"channel_type\", \"text\", (col) => col.notNull()).addColumn(\"channel_id\", \"text\", (col) => col.notNull().defaultTo(\"\")).addColumn(\"remote_name\", \"text\", (col) => col.notNull().defaultTo(\"\")).addColumn(\"channel_parameters\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'{}'::jsonb`)).addColumn(\"filter_document_ids\", \"jsonb\").addColumn(\"filter_scopes\", \"jsonb\").addColumn(\"filter_branch\", \"text\", (col) => col.notNull().defaultTo(\"main\")).addColumn(\"push_state\", \"text\", (col) => col.notNull().defaultTo(\"idle\")).addColumn(\"push_last_success_utc_ms\", \"text\").addColumn(\"push_last_failure_utc_ms\", \"text\").addColumn(\"push_failure_count\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"pull_state\", \"text\", (col) => col.notNull().defaultTo(\"idle\")).addColumn(\"pull_last_success_utc_ms\", \"text\").addColumn(\"pull_last_failure_utc_ms\", \"text\").addColumn(\"pull_failure_count\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"created_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_remotes_collection\").on(\"sync_remotes\").column(\"collection_id\").execute();\n\tawait db.schema.createTable(\"sync_cursors\").addColumn(\"remote_name\", \"text\", (col) => col.primaryKey().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"cursor_ordinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"last_synced_at_utc_ms\", \"text\").addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_cursors_ordinal\").on(\"sync_cursors\").column(\"cursor_ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/011_add_cursor_type_column.ts\nvar _011_add_cursor_type_column_exports = /* @__PURE__ */ __exportAll({ up: () => up$15 });\nasync function up$15(db) {\n\tawait db.deleteFrom(\"sync_cursors\").where(\"remote_name\", \"like\", \"outbox::%\").execute();\n\tawait db.deleteFrom(\"sync_remotes\").where(\"name\", \"like\", \"outbox::%\").execute();\n\tawait db.schema.dropTable(\"sync_cursors\").execute();\n\tawait db.schema.createTable(\"sync_cursors\").addColumn(\"remote_name\", \"text\", (col) => col.notNull()).addColumn(\"cursor_type\", \"text\", (col) => col.notNull().defaultTo(\"inbox\")).addColumn(\"cursor_ordinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"last_synced_at_utc_ms\", \"text\").addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addPrimaryKeyConstraint(\"sync_cursors_pk\", [\"remote_name\", \"cursor_type\"]).execute();\n\tawait db.schema.createIndex(\"idx_sync_cursors_ordinal\").on(\"sync_cursors\").column(\"cursor_ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/012_add_source_remote_column.ts\nvar _012_add_source_remote_column_exports = /* @__PURE__ */ __exportAll({ up: () => up$14 });\nasync function up$14(db) {\n\tawait db.schema.alterTable(\"operation_index_operations\").addColumn(\"sourceRemote\", \"text\", (col) => col.notNull().defaultTo(\"\")).execute();\n}\n//#endregion\n//#region src/storage/migrations/013_create_sync_dead_letters_table.ts\nvar _013_create_sync_dead_letters_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$13 });\nasync function up$13(db) {\n\tawait db.schema.createTable(\"sync_dead_letters\").addColumn(\"ordinal\", \"serial\", (col) => col.primaryKey()).addColumn(\"id\", \"text\", (col) => col.unique().notNull()).addColumn(\"job_id\", \"text\", (col) => col.notNull()).addColumn(\"job_dependencies\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"remote_name\", \"text\", (col) => col.notNull().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"document_id\", \"text\", (col) => col.notNull()).addColumn(\"scopes\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"operations\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"error_source\", \"text\", (col) => col.notNull()).addColumn(\"error_message\", \"text\", (col) => col.notNull()).addColumn(\"created_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_dead_letters_remote\").on(\"sync_dead_letters\").column(\"remote_name\").execute();\n}\n//#endregion\n//#region src/storage/migrations/014_create_processor_cursor_table.ts\nvar _014_create_processor_cursor_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$12 });\nasync function up$12(db) {\n\tawait db.schema.createTable(\"ProcessorCursor\").addColumn(\"processorId\", \"text\", (col) => col.primaryKey()).addColumn(\"factoryId\", \"text\", (col) => col.notNull()).addColumn(\"driveId\", \"text\", (col) => col.notNull()).addColumn(\"processorIndex\", \"integer\", (col) => col.notNull()).addColumn(\"lastOrdinal\", \"integer\", (col) => col.notNull().defaultTo(sql`0`)).addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(sql`'active'`)).addColumn(\"lastError\", \"text\").addColumn(\"lastErrorTimestamp\", \"timestamptz\").addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/015_add_operation_denied_reason.ts\nvar _015_add_operation_denied_reason_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$11,\n\tup: () => up$11\n});\n/**\n* Records why authorization refused an operation. Separate from `error` so a\n* denial is distinguishable from a reducer failure without matching on a\n* message. Null for every operation written before decisions were enforced.\n*/\nasync function up$11(db) {\n\tawait db.schema.alterTable(\"Operation\").addColumn(\"deniedReason\", \"text\").execute();\n\tawait db.schema.alterTable(\"operation_index_operations\").addColumn(\"deniedReason\", \"text\").execute();\n}\nasync function down$11(db) {\n\tawait db.schema.alterTable(\"operation_index_operations\").dropColumn(\"deniedReason\").execute();\n\tawait db.schema.alterTable(\"Operation\").dropColumn(\"deniedReason\").execute();\n}\n//#endregion\n//#region src/storage/migrations/016_add_dead_letter_error_type.ts\nvar _016_add_dead_letter_error_type_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$10,\n\tup: () => up$10\n});\n/**\n* The classification a dead letter falls into, stored because it decides whether\n* the document stays quarantined and the in-memory error is gone after a restart.\n* Defaulted rather than nullable, so a pre-existing row rehydrates.\n*/\nasync function up$10(db) {\n\tawait db.schema.alterTable(\"sync_dead_letters\").addColumn(\"error_type\", \"text\", (col) => col.notNull().defaultTo(\"UNCLASSIFIED\")).execute();\n}\nasync function down$10(db) {\n\tawait db.schema.alterTable(\"sync_dead_letters\").dropColumn(\"error_type\").execute();\n}\n//#endregion\n//#region src/storage/migrations/017_create_group_references.ts\nvar _017_create_group_references_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$9,\n\tup: () => up$9\n});\n/**\n* One row per (document, group) reference ever discovered from an auth\n* operation's input. Rows are never updated or deleted: auth evaluation is\n* positional, so a grant that named a group at any position keeps that\n* group's stream in the document's read-set even after a later operation\n* removes the reference. Read by documentId for the groups a document\n* requires (sync), and by groupId for the documents a group change affects\n* (re-evaluation).\n*/\nasync function up$9(db) {\n\tawait db.schema.createTable(\"group_references\").addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"groupId\", \"text\", (col) => col.notNull()).addPrimaryKeyConstraint(\"group_references_pkey\", [\"documentId\", \"groupId\"]).execute();\n\tawait db.schema.createIndex(\"idx_group_references_groupId\").on(\"group_references\").column(\"groupId\").execute();\n}\nasync function down$9(db) {\n\tawait db.schema.dropTable(\"group_references\").execute();\n}\n//#endregion\n//#region src/storage/migrations/018_add_sync_remote_bound_address.ts\nvar _018_add_sync_remote_bound_address_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$8,\n\tup: () => up$8\n});\n/**\n* The address a sync channel is bound to, so a channel created by one subject\n* cannot be polled by another.\n*\n* Nullable rather than defaulted: null is a channel nobody has claimed, which is\n* what every pre-existing row is and what an anonymously created channel stays\n* until its first authenticated poll adopts it. A default would claim them all\n* for one address.\n*/\nasync function up$8(db) {\n\tawait db.schema.alterTable(\"sync_remotes\").addColumn(\"bound_address\", \"text\").execute();\n}\nasync function down$8(db) {\n\tawait db.schema.alterTable(\"sync_remotes\").dropColumn(\"bound_address\").execute();\n}\n//#endregion\n//#region src/storage/migrations/019_require_action_id.ts\nvar _019_require_action_id_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$7,\n\tup: () => up$7\n});\n/**\n* Makes an operation whose action carries no id physically unstorable.\n*\n* The id is not decoration: `deriveOperationId` hashes it into the operation id\n* and replay dedupes incoming operations by it, so an action without one\n* collapses every id-less operation on a document/scope/branch onto a single\n* derived operation id. The API rejects such an action now, and this is the\n* last line of defense behind it.\n*\n* Both tables are constrained because sync reads operations from the index\n* rather than the operation table, so poison reaching only the index would\n* still be served to a replica.\n*\n* Pre-existing rows are backfilled rather than left behind a NOT VALID\n* constraint: a row the index and the operation table disagree about is worse\n* than a missing id, because dedup keys off the value each side serves. The\n* backfill therefore mints one id per operation and writes that same id to both\n* tables, joined on the identity they share. Rewriting the action is safe: the\n* operation hash is taken over the resulting state, not over the action, and a\n* signature is verified from the params carried in the signature tuple, which\n* do not include the action id.\n*\n* The empty string is rejected alongside null. It derives the same colliding\n* operation id as an absent id, so admitting it would leave the hole open.\n*/\nasync function up$7(db) {\n\tawait db.updateTable(\"Operation\").set({ action: sql`jsonb_set(action, '{id}', to_jsonb(gen_random_uuid()::text))` }).where(sql`jsonb_typeof(action) = 'object' and coalesce(action->>'id', '') = ''`).execute();\n\tawait db.updateTable(\"operation_index_operations as oio\").from(\"Operation as op\").set({ action: sql`jsonb_set(oio.action, '{id}', to_jsonb(op.action->>'id'))` }).whereRef(\"oio.opId\", \"=\", \"op.opId\").whereRef(\"oio.index\", \"=\", \"op.index\").whereRef(\"oio.skip\", \"=\", \"op.skip\").where(sql`jsonb_typeof(oio.action) = 'object' and coalesce(oio.action->>'id', '') = ''`).where(sql`coalesce(op.action->>'id', '') <> ''`).execute();\n\tawait db.updateTable(\"operation_index_operations\").set({ action: sql`jsonb_set(action, '{id}', to_jsonb(gen_random_uuid()::text))` }).where(sql`jsonb_typeof(action) = 'object' and coalesce(action->>'id', '') = ''`).execute();\n\tawait db.schema.alterTable(\"Operation\").addCheckConstraint(\"action_must_have_id\", sql`action->>'id' is not null and action->>'id' <> ''`).execute();\n\tawait db.schema.alterTable(\"operation_index_operations\").addCheckConstraint(\"action_must_have_id\", sql`action->>'id' is not null and action->>'id' <> ''`).execute();\n}\n/**\n* Only the constraints are dropped. The backfilled ids stay: they are the ids\n* their operations are now known by, and reverting them would reintroduce the\n* collision the migration removed.\n*/\nasync function down$7(db) {\n\tawait db.schema.alterTable(\"operation_index_operations\").dropConstraint(\"action_must_have_id\").execute();\n\tawait db.schema.alterTable(\"Operation\").dropConstraint(\"action_must_have_id\").execute();\n}\n//#endregion\n//#region src/storage/migrations/020_add_snapshot_operation_ordinal.ts\nvar _020_add_snapshot_operation_ordinal_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$6,\n\tup: () => up$6\n});\n/** Orders header row writes across scopes; `lastOperationIndex` is per scope. */\nasync function up$6(db) {\n\tawait db.schema.alterTable(\"DocumentSnapshot\").addColumn(\"lastOperationOrdinal\", \"integer\", (col) => col.notNull().defaultTo(0)).execute();\n}\nasync function down$6(db) {\n\tawait db.schema.alterTable(\"DocumentSnapshot\").dropColumn(\"lastOperationOrdinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/021_add_sync_remote_peer.ts\nvar _021_add_sync_remote_peer_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$5,\n\tup: () => up$5\n});\n/**\n* The peer's manifest as canonical JSON, and when it was heard. Both null: not\n* yet heard. A time with no manifest: a silent peer, which gets the baselines.\n*/\nasync function up$5(db) {\n\tawait db.schema.alterTable(\"sync_remotes\").addColumn(\"peer_manifest\", \"text\").addColumn(\"peer_manifest_at_utc_ms\", \"bigint\").execute();\n}\nasync function down$5(db) {\n\tawait db.schema.alterTable(\"sync_remotes\").dropColumn(\"peer_manifest\").dropColumn(\"peer_manifest_at_utc_ms\").execute();\n}\n//#endregion\n//#region src/storage/migrations/022_create_sync_holds.ts\nvar _022_create_sync_holds_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$4,\n\tup: () => up$4\n});\n/** Documents held back from a remote whose peer cannot run their versions. */\nasync function up$4(db) {\n\tawait db.schema.createTable(\"sync_holds\").addColumn(\"remote_name\", \"text\", (col) => col.notNull().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"document_id\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"protocol\", \"text\", (col) => col.notNull()).addColumn(\"version\", \"integer\", (col) => col.notNull()).addColumn(\"held_at_utc_ms\", \"bigint\", (col) => col.notNull()).addPrimaryKeyConstraint(\"sync_holds_pkey\", [\n\t\t\"remote_name\",\n\t\t\"document_id\",\n\t\t\"branch\"\n\t]).execute();\n}\nasync function down$4(db) {\n\tawait db.schema.dropTable(\"sync_holds\").execute();\n}\n//#endregion\n//#region src/storage/migrations/023_index_created_protocol_versions.ts\nvar _023_index_created_protocol_versions_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$3,\n\tup: () => up$3\n});\n/**\n* One entry per document created with protocolVersions, keyed by a hash so an\n* oversized header cannot make its creation unstorable. Startup reads the\n* distinct values without visiting every document.\n*/\nasync function up$3(db) {\n\tawait db.schema.createIndex(\"idx_operation_created_protocol_versions\").on(\"Operation\").expression(sql`md5((action->'input'->'protocolVersions')::text)`).where(sql`scope = 'document' and \"index\" = 0 and (action->'input'->'protocolVersions') is not null`).execute();\n}\nasync function down$3(db) {\n\tawait db.schema.dropIndex(\"idx_operation_created_protocol_versions\").execute();\n}\n//#endregion\n//#region src/storage/migrations/024_create_document_purges.ts\nvar _024_create_document_purges_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$2,\n\tup: () => up$2\n});\n/** One row per purged document: the tombstone. Written once, never deleted. */\nasync function up$2(db) {\n\tawait db.schema.createTable(\"document_purges\").addColumn(\"documentId\", \"text\", (col) => col.primaryKey()).addColumn(\"ordinal\", \"bigint\", (col) => col.notNull()).addColumn(\"removedRows\", \"jsonb\", (col) => col.notNull()).addColumn(\"purgedAtUtc\", \"timestamptz\", (col) => col.notNull()).addColumn(\"requestId\", \"text\", (col) => col.notNull()).execute();\n}\nasync function down$2(db) {\n\tawait db.schema.dropTable(\"document_purges\").execute();\n}\n//#endregion\n//#region src/storage/migrations/025_create_sync_received_markers.ts\nvar _025_create_sync_received_markers_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down$1,\n\tup: () => up$1\n});\n/** Received purge markers awaiting their outcome; removed with their remote. */\nasync function up$1(db) {\n\tawait db.schema.createTable(\"sync_received_markers\").addColumn(\"remote_name\", \"text\", (col) => col.notNull()).addColumn(\"marker_id\", \"text\", (col) => col.notNull()).addColumn(\"document_id\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"operation\", \"jsonb\", (col) => col.notNull()).addColumn(\"received_at_utc_ms\", \"bigint\", (col) => col.notNull()).addPrimaryKeyConstraint(\"sync_received_markers_pkey\", [\"remote_name\", \"marker_id\"]).execute();\n}\nasync function down$1(db) {\n\tawait db.schema.dropTable(\"sync_received_markers\").execute();\n}\n//#endregion\n//#region src/storage/migrations/026_create_sync_purge_refusals.ts\nvar _026_create_sync_purge_refusals_exports = /* @__PURE__ */ __exportAll({\n\tdown: () => down,\n\tup: () => up\n});\n/** A remote's refusal of a purge marker; payload-free, kept like the tombstone. */\nasync function up(db) {\n\tawait db.schema.createTable(\"sync_purge_refusals\").addColumn(\"remote_name\", \"text\", (col) => col.notNull()).addColumn(\"document_id\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"refused_at_utc_ms\", \"bigint\", (col) => col.notNull()).addPrimaryKeyConstraint(\"sync_purge_refusals_pkey\", [\n\t\t\"remote_name\",\n\t\t\"document_id\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_sync_purge_refusals_document\").on(\"sync_purge_refusals\").column(\"document_id\").execute();\n}\nasync function down(db) {\n\tawait db.schema.dropTable(\"sync_purge_refusals\").execute();\n}\n//#endregion\n//#region src/storage/migrations/migrator.ts\nconst REACTOR_SCHEMA = \"reactor\";\nconst migrations = {\n\t\"001_create_operation_table\": _001_create_operation_table_exports,\n\t\"002_create_keyframe_table\": _002_create_keyframe_table_exports,\n\t\"003_create_document_table\": _003_create_document_table_exports,\n\t\"004_create_document_relationship_table\": _004_create_document_relationship_table_exports,\n\t\"005_create_indexer_state_table\": _005_create_indexer_state_table_exports,\n\t\"006_create_document_snapshot_table\": _006_create_document_snapshot_table_exports,\n\t\"007_create_slug_mapping_table\": _007_create_slug_mapping_table_exports,\n\t\"008_create_view_state_table\": _008_create_view_state_table_exports,\n\t\"009_create_operation_index_tables\": _009_create_operation_index_tables_exports,\n\t\"010_create_sync_tables\": _010_create_sync_tables_exports,\n\t\"011_add_cursor_type_column\": _011_add_cursor_type_column_exports,\n\t\"012_add_source_remote_column\": _012_add_source_remote_column_exports,\n\t\"013_create_sync_dead_letters_table\": _013_create_sync_dead_letters_table_exports,\n\t\"014_create_processor_cursor_table\": _014_create_processor_cursor_table_exports,\n\t\"015_add_operation_denied_reason\": _015_add_operation_denied_reason_exports,\n\t\"016_add_dead_letter_error_type\": _016_add_dead_letter_error_type_exports,\n\t\"017_create_group_references\": _017_create_group_references_exports,\n\t\"018_add_sync_remote_bound_address\": _018_add_sync_remote_bound_address_exports,\n\t\"019_require_action_id\": _019_require_action_id_exports,\n\t\"020_add_snapshot_operation_ordinal\": _020_add_snapshot_operation_ordinal_exports,\n\t\"021_add_sync_remote_peer\": _021_add_sync_remote_peer_exports,\n\t\"022_create_sync_holds\": _022_create_sync_holds_exports,\n\t\"023_index_created_protocol_versions\": _023_index_created_protocol_versions_exports,\n\t\"024_create_document_purges\": _024_create_document_purges_exports,\n\t\"025_create_sync_received_markers\": _025_create_sync_received_markers_exports,\n\t\"026_create_sync_purge_refusals\": _026_create_sync_purge_refusals_exports\n};\nvar ProgrammaticMigrationProvider = class {\n\tgetMigrations() {\n\t\treturn Promise.resolve(migrations);\n\t}\n};\n/**\n* Applies every pending migration, or every one up to and including `upTo`.\n*\n* The bound exists so a test can reach the schema a data migration is written\n* against, populate it, and then migrate across the migration under test.\n*/\nasync function runMigrations(db, schema = REACTOR_SCHEMA, upTo) {\n\ttry {\n\t\tawait sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(schema)}`.execute(db);\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tmigrationsExecuted: [],\n\t\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Failed to create schema\")\n\t\t};\n\t}\n\tconst migrator = new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema\n\t});\n\tlet error;\n\tlet results;\n\ttry {\n\t\tconst result = upTo ? await migrator.migrateTo(upTo) : await migrator.migrateToLatest();\n\t\terror = result.error;\n\t\tresults = result.results;\n\t} catch (e) {\n\t\terror = e;\n\t\tresults = [];\n\t}\n\tconst migrationsExecuted = results?.map((result) => result.migrationName) ?? [];\n\tif (error) return {\n\t\tsuccess: false,\n\t\tmigrationsExecuted,\n\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Unknown migration error\")\n\t};\n\treturn {\n\t\tsuccess: true,\n\t\tmigrationsExecuted\n\t};\n}\nasync function getMigrationStatus(db, schema = REACTOR_SCHEMA) {\n\treturn await new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema\n\t}).getMigrations();\n}\n//#endregion\n//#region src/executor/worker/error-info.ts\nconst MAX_STACK_LENGTH = 8192;\nconst MAX_CAUSE_DEPTH = 8;\nfunction toErrorInfo(err, depth = 0) {\n\tif (depth > MAX_CAUSE_DEPTH) return {\n\t\tname: \"Error\",\n\t\tmessage: \"cause chain truncated\"\n\t};\n\tif (err instanceof Error) {\n\t\tconst info = {\n\t\t\tname: err.name || \"Error\",\n\t\t\tmessage: err.message\n\t\t};\n\t\tif (typeof err.stack === \"string\") info.stack = err.stack.length > MAX_STACK_LENGTH ? err.stack.slice(0, MAX_STACK_LENGTH) : err.stack;\n\t\tif (err.cause !== void 0) info.cause = toErrorInfo(err.cause, depth + 1);\n\t\tconst documentId = err.documentId;\n\t\tif (typeof documentId === \"string\") info.documentId = documentId;\n\t\tconst { documentType, requestedVersion } = err;\n\t\tif (typeof documentType === \"string\") info.documentType = documentType;\n\t\tif (typeof requestedVersion === \"number\") info.requestedVersion = requestedVersion;\n\t\treturn info;\n\t}\n\tif (typeof err === \"string\") return {\n\t\tname: \"Error\",\n\t\tmessage: err\n\t};\n\tif (err && typeof err === \"object\") {\n\t\tconst record = err;\n\t\treturn {\n\t\t\tname: typeof record.name === \"string\" ? record.name : \"Error\",\n\t\t\tmessage: typeof record.message === \"string\" ? record.message : safeStringify(err)\n\t\t};\n\t}\n\treturn {\n\t\tname: \"Error\",\n\t\tmessage: safeStringify(err)\n\t};\n}\nfunction safeStringify(value) {\n\tif (value === null || value === void 0) return String(value);\n\tif (typeof value === \"string\") return value;\n\tif (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\ttry {\n\t\treturn JSON.stringify(value);\n\t} catch {\n\t\treturn \"[unserializable]\";\n\t}\n}\nfunction fromErrorInfo(info) {\n\tconst err = new Error(info.message);\n\tObject.defineProperty(err, \"name\", {\n\t\tvalue: info.name,\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n\tif (info.stack !== void 0) err.stack = info.stack;\n\tif (info.documentId !== void 0) Object.defineProperty(err, \"documentId\", {\n\t\tvalue: info.documentId,\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n\tfor (const key of [\"documentType\", \"requestedVersion\"]) if (info[key] !== void 0) Object.defineProperty(err, key, {\n\t\tvalue: info[key],\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n\tif (info.cause !== void 0) Object.defineProperty(err, \"cause\", {\n\t\tvalue: fromErrorInfo(info.cause),\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n\treturn err;\n}\n//#endregion\n//#region src/executor/worker/sanitize.ts\nconst MAX_DEPTH = 8;\nfunction errorToInfo(err) {\n\treturn toErrorInfo(err);\n}\nfunction sanitizeArg(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {\n\tif (depth > MAX_DEPTH) return \"[Truncated]\";\n\tif (value === null || value === void 0) return null;\n\tif (typeof value === \"boolean\") return value;\n\tif (typeof value === \"number\") return value;\n\tif (typeof value === \"string\") return value;\n\tif (typeof value === \"bigint\") return value.toString();\n\tif (typeof value === \"function\" || typeof value === \"symbol\") return null;\n\tif (value instanceof Error) return toErrorInfo(value);\n\tif (value instanceof Date) return value.toISOString();\n\tif (value instanceof Map) {\n\t\tconst obj = {};\n\t\tfor (const [k, v] of value.entries()) obj[String(k)] = sanitizeArg(v, depth + 1, seen);\n\t\treturn obj;\n\t}\n\tif (value instanceof Set) {\n\t\tconst arr = [];\n\t\tfor (const v of value.values()) arr.push(sanitizeArg(v, depth + 1, seen));\n\t\treturn arr;\n\t}\n\tif (Array.isArray(value)) {\n\t\tif (seen.has(value)) return \"[Circular]\";\n\t\tseen.add(value);\n\t\tconst result = value.map((v) => sanitizeArg(v, depth + 1, seen));\n\t\tseen.delete(value);\n\t\treturn result;\n\t}\n\tif (typeof value === \"object\") {\n\t\tconst proto = Object.getPrototypeOf(value);\n\t\tif (proto !== Object.prototype && proto !== null) return { __nonClonable: value.constructor?.name || \"Unknown\" };\n\t\tif (seen.has(value)) return \"[Circular]\";\n\t\tseen.add(value);\n\t\tconst result = {};\n\t\tfor (const [k, v] of Object.entries(value)) result[k] = sanitizeArg(v, depth + 1, seen);\n\t\tseen.delete(value);\n\t\treturn result;\n\t}\n\treturn null;\n}\n//#endregion\n//#region src/executor/worker/forwarding-logger.ts\nfunction createForwardingLogger(post, level = \"info\", tags = []) {\n\tfunction safePost(msg) {\n\t\ttry {\n\t\t\tpost(msg);\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\tprocess.stderr.write(`[forwarding-logger] postMessage failed: ${msg.level} ${msg.message}\\n`);\n\t\t\t} catch {}\n\t\t}\n\t}\n\tfunction emit(wireLevel, message, args) {\n\t\tconst sanitizedArgs = args.map((a) => sanitizeArg(a));\n\t\tsafePost({\n\t\t\ttype: \"log\",\n\t\t\tlevel: wireLevel,\n\t\t\tmessage,\n\t\t\targs: tags.length > 0 ? [sanitizeArg({ tags }), ...sanitizedArgs] : sanitizedArgs,\n\t\t\ttimestamp: Date.now()\n\t\t});\n\t}\n\treturn {\n\t\tlevel,\n\t\tverbose: (message, ...args) => emit(\"debug\", message, args),\n\t\tdebug: (message, ...args) => emit(\"debug\", message, args),\n\t\tinfo: (message, ...args) => emit(\"info\", message, args),\n\t\twarn: (message, ...args) => emit(\"warn\", message, args),\n\t\terror: (message, ...args) => emit(\"error\", message, args),\n\t\terrorHandler: ((...data) => {\n\t\t\tconst first = data[0];\n\t\t\temit(\"error\", typeof first === \"string\" ? first : \"\", data.slice(1));\n\t\t}),\n\t\tchild: (childTags) => createForwardingLogger(post, level, [...tags, ...childTags])\n\t};\n}\n//#endregion\n//#region src/executor/worker/load-spec.ts\n/** Imports `spec.module` and calls the export with `spec.initArgs`, or returns it if not a function. */\nasync function defaultLoadFactory(spec) {\n\tconst ref = spec.module;\n\tconst exported = (await (\"filePath\" in ref ? import(new URL(`file://${ref.filePath}`).href) : import(ref.packageName)))[ref.exportName];\n\tif (typeof exported === \"function\") return exported(spec.initArgs);\n\treturn exported;\n}\n/** Loads the document model module a manifest entry's spec names. */\nasync function loadDocumentModelSpec(spec) {\n\treturn await defaultLoadFactory(spec);\n}\n//#endregion\nexport { relationshipTarget as $, CollectionMembershipCache as A, matchesScope as At, TouchedStreams as B, ProbeSettler as C, RelationshipNotFoundError as Ct, parseSnapshot as D, UpgradePreconditionFailedError as Dt, describeWaitingSessions as E, UnsupportedStoredProtocolError as Et, ModuleNotFoundError as F, createConsistencyToken as G, applyUpgradeDocumentAction$1 as H, DOCUMENT_SCOPE_ACTIONS as I, createOperation as J, createDocumentFromAction as K, FencedWriteCache as L, DuplicateModuleError as M, throwIfAborted as Mt, InvalidModuleError as N, yieldToMain as Nt, snapshotFunctionsFor as O, EventBusAggregateError as Ot, ModelNotWorkerImportableError as P, __exportAll as Pt, refusalError as Q, GATED_DOCUMENT_ACTIONS as R, listPurged as S, PurgeTooLargeError as St, createKyselyWatermarkProbe as T, UnsupportedProtocolVersionError as Tt, buildErrorResult as U, applyDeleteDocumentAction$1 as V, buildSuccessResult as W, isGenesisOperation as X, getNextIndexForScope as Y, jobWriteIds as Z, KyselyOperationIndex as _, DocumentPurgedError as _t, sanitizeArg as a, AppendConditionFailedError as at, acquirePurgeLocks as b, InvalidOperationTimestampError as bt, getMigrationStatus as c, DuplicateOperationError as ct, instrumentPgPool as d, AuthEnforcementDisabledError as dt, submittedActionIds as et, KyselyOperationStore as f, AuthTimestampNotMonotonicError as ft, KyselyWriteCache as g, DocumentNotFoundError as gt, EventBus as h, DocumentNotDeletedError as ht, errorToInfo as i, APPEND_CONDITION_FAILED_PREFIX as it, DuplicateManifestError as j, parsePagingOptions as jt, DocumentMetaCache as k, ReactorEventTypes as kt, runMigrations as l, OptimisticLockError as lt, DocumentModelRegistry as m, DocumentDeletedError as mt, loadDocumentModelSpec as n, targetDocumentId as nt, fromErrorInfo as o, DocumentAlreadyExistsError as ot, KyselyKeyframeStore as p, AuthorizationDeniedError as pt, createEmptyConsistencyToken as q, createForwardingLogger as r, updateDocumentRevision as rt, REACTOR_SCHEMA as s, DocumentExistence as st, defaultLoadFactory as t, summarizeSubmittedActions as tt, createForwardingPoolInstrumentation as u, RevisionMismatchError as ut, PURGE_LOCK_BUCKETS as v, ExcessiveReshuffleError as vt, SettledWatermark as w, ReservedActionError as wt, findPurged as x, InvalidSignatureError as xt, PURGE_NS as y, GroupInUseError as yt, PurgeFence as z };\n\n//# sourceMappingURL=load-spec-f2ppXyKZ.js.map","import type { Operation } from \"@powerhousedao/shared/document-model\";\nimport type { AtomicTxn } from \"@powerhousedao/reactor\";\nimport type { StoredOperation } from \"./types.js\";\n\nexport class HypercoreAtomicTransaction implements AtomicTxn {\n private operations: StoredOperation[] = [];\n\n constructor(\n private documentId: string,\n private documentType: string,\n private scope: string,\n private branch: string,\n ) {}\n\n addOperations(...operations: Operation[]): void {\n for (const op of operations) {\n this.operations.push({\n ...op,\n documentId: this.documentId,\n documentType: this.documentType,\n scope: this.scope,\n branch: this.branch,\n });\n }\n }\n\n getOperations(): StoredOperation[] {\n return this.operations;\n }\n}\n","import type { StoredOperation } from \"./types.js\";\n\nconst PAD_WIDTH = 10;\n\nexport const RANGE_UPPER_BOUND = \"9\".repeat(PAD_WIDTH) + \"~\";\n\nexport function pad(n: number): string {\n return n.toString().padStart(PAD_WIDTH, \"0\");\n}\n\nexport function operationKey(\n documentId: string,\n scope: string,\n branch: string,\n index: number,\n): string {\n return `op/${documentId}/${scope}/${branch}/${pad(index)}`;\n}\n\nexport function operationPrefix(\n documentId: string,\n scope: string,\n branch: string,\n): string {\n return `op/${documentId}/${scope}/${branch}/`;\n}\n\nexport function ordinalKey(ordinal: number): string {\n return `ord/${pad(ordinal)}`;\n}\n\nexport function ordinalPrefix(): string {\n return \"ord/\";\n}\n\nexport function duplicateKey(\n opId: string,\n index: number,\n skip: number,\n): string {\n return `dup/${opId}/${pad(index)}/${pad(skip)}`;\n}\n\nexport function headKey(\n documentId: string,\n scope: string,\n branch: string,\n): string {\n return `_meta/head/${documentId}/${scope}/${branch}`;\n}\n\nexport function headPrefix(documentId: string): string {\n return `_meta/head/${documentId}/`;\n}\n\nexport const ORDINAL_COUNTER_KEY = \"_meta/ordinal\";\n\nexport type ParsedOperationKey = {\n documentId: string;\n scope: string;\n branch: string;\n index: number;\n};\n\nexport function parseOperationKey(key: string): ParsedOperationKey {\n const parts = key.split(\"/\");\n return {\n documentId: parts[1],\n scope: parts[2],\n branch: parts[3],\n index: parseInt(parts[4], 10),\n };\n}\n\nexport type OrdinalEntry = {\n documentId: string;\n documentType: string;\n scope: string;\n branch: string;\n index: number;\n operation: StoredOperation;\n};\n\nexport type HeadEntryValue = {\n index: number;\n latestTimestampUtcMs: string;\n};\n","import {\n isPurgeMarker,\n type Operation,\n type OperationWithContext,\n} from \"@powerhousedao/shared/document-model\";\nimport type {\n AppendCondition,\n AtomicTxn,\n DocumentRevisions,\n IOperationStore,\n OperationFilter,\n PagedResults,\n PagingOptions,\n} from \"@powerhousedao/reactor\";\nimport {\n AppendConditionFailedError,\n DocumentAlreadyExistsError,\n DocumentPurgedError,\n DuplicateOperationError,\n RevisionMismatchError,\n} from \"@powerhousedao/reactor\";\nimport type Hyperbee from \"hyperbee\";\nimport { HypercoreAtomicTransaction } from \"./hypercore-atomic-transaction.js\";\nimport {\n ORDINAL_COUNTER_KEY,\n RANGE_UPPER_BOUND,\n duplicateKey,\n headKey,\n headPrefix,\n operationKey,\n operationPrefix,\n ordinalKey,\n ordinalPrefix,\n pad,\n} from \"./key-encoding.js\";\nimport type { HeadEntryValue, OrdinalEntry } from \"./key-encoding.js\";\nimport type { StoredOperation } from \"./types.js\";\n\nexport class HypercoreOperationStore implements IOperationStore {\n private applyLock: Promise<void> = Promise.resolve();\n\n constructor(private bee: Hyperbee) {}\n\n async apply(\n documentId: string,\n documentType: string,\n scope: string,\n branch: string,\n revision: number,\n fn: (txn: AtomicTxn) => void | Promise<void>,\n signal?: AbortSignal,\n condition?: AppendCondition,\n ): Promise<Operation[]> {\n const prevLock = this.applyLock;\n let releaseLock: () => void;\n this.applyLock = new Promise<void>((resolve) => {\n releaseLock = resolve;\n });\n\n await prevLock;\n\n try {\n // Single writer on applyLock: nothing can append between check and write.\n if (condition) {\n await this.assertConditionHolds(condition, signal);\n }\n\n return await this.executeApply(\n documentId,\n documentType,\n scope,\n branch,\n revision,\n fn,\n signal,\n );\n } finally {\n releaseLock!();\n }\n }\n\n /** Throws if any read-set stream has grown past its recorded revision. */\n private async assertConditionHolds(\n condition: AppendCondition,\n signal?: AbortSignal,\n ): Promise<void> {\n for (const stream of condition.streams) {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const entry = await this.bee.get(\n headKey(stream.documentId, stream.scope, stream.branch),\n );\n const head = entry ? (entry.value as HeadEntryValue).index : -1;\n\n if (head > stream.revision) {\n throw new AppendConditionFailedError(condition);\n }\n }\n }\n\n private async executeApply(\n documentId: string,\n documentType: string,\n scope: string,\n branch: string,\n revision: number,\n fn: (txn: AtomicTxn) => void | Promise<void>,\n signal?: AbortSignal,\n ): Promise<Operation[]> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const hKey = headKey(documentId, scope, branch);\n const headEntry = await this.bee.get(hKey);\n const currentRevision = headEntry\n ? (headEntry.value as HeadEntryValue).index\n : -1;\n\n const atomicTxn = new HypercoreAtomicTransaction(\n documentId,\n documentType,\n scope,\n branch,\n );\n await fn(atomicTxn);\n\n const operations = atomicTxn.getOperations();\n\n // No delete path here: a stream purged elsewhere ends in its marker.\n const marker = await this.purgeMarkerAtHead(documentId);\n if (marker !== undefined && operations.length > 0) {\n if (!operations.every((op) => isPurgeMarker(op))) {\n throw new DocumentPurgedError(documentId);\n }\n return [marker];\n }\n\n if (currentRevision !== revision - 1) {\n if (revision === 0 && this.isCreate(operations)) {\n throw new DocumentAlreadyExistsError(\n documentId,\n scope,\n currentRevision,\n );\n }\n\n throw new RevisionMismatchError(currentRevision + 1, revision);\n }\n\n if (operations.length === 0) {\n return [];\n }\n\n for (const op of operations) {\n const dupKey = duplicateKey(op.id, op.index, op.skip);\n const existing = await this.bee.get(dupKey);\n if (existing) {\n throw new DuplicateOperationError(\n `${op.id} at index ${op.index} with skip ${op.skip}`,\n );\n }\n }\n\n const ordinalEntry = await this.bee.get(ORDINAL_COUNTER_KEY);\n let nextOrdinal: number = ordinalEntry ? (ordinalEntry.value as number) : 0;\n\n const batch = this.bee.batch();\n\n for (const op of operations) {\n const opKey = operationKey(documentId, scope, branch, op.index);\n const serialized = this.serializeOperation(op);\n await batch.put(opKey, serialized);\n\n const ordEntry: OrdinalEntry = {\n documentId,\n documentType,\n scope,\n branch,\n index: op.index,\n operation: serialized,\n };\n await batch.put(ordinalKey(nextOrdinal), ordEntry);\n\n await batch.put(duplicateKey(op.id, op.index, op.skip), \"\");\n\n nextOrdinal++;\n }\n\n const lastOp = operations[operations.length - 1];\n const headValue: HeadEntryValue = {\n index: lastOp.index,\n latestTimestampUtcMs: lastOp.timestampUtcMs,\n };\n await batch.put(hKey, headValue);\n await batch.put(ORDINAL_COUNTER_KEY, nextOrdinal);\n\n await batch.flush();\n\n return operations.map((op) => this.toOperation(op));\n }\n\n /** A purge marker is written to document/main whichever branch it erases. */\n private async purgeMarkerAtHead(\n documentId: string,\n ): Promise<Operation | undefined> {\n const branch = \"main\";\n const head = await this.bee.get(headKey(documentId, \"document\", branch));\n if (!head) {\n return undefined;\n }\n const index = (head.value as HeadEntryValue).index;\n const entry = await this.bee.get(\n operationKey(documentId, \"document\", branch, index),\n );\n const stored = entry?.value as StoredOperation | undefined;\n return stored && isPurgeMarker(stored)\n ? this.toOperation(stored)\n : undefined;\n }\n\n private isCreate(operations: StoredOperation[]): boolean {\n return operations.some((op) => op.action.type === \"CREATE_DOCUMENT\");\n }\n\n /**\n * The paging cursor encodes the index to resume from (one past the last\n * row returned), not the last row's own index; \"\" or \"0\" (or anything\n * unparsable) means the start of the stream. This keeps \"0\" an unambiguous\n * start-of-stream sentinel even when a page ends at index 0, which would\n * otherwise make `nextCursor` equal the start cursor and loop a caller that\n * walks pages forever. Mirrors the encoding in the Kysely store.\n */\n async getSince(\n documentId: string,\n scope: string,\n branch: string,\n revision: number,\n filter?: OperationFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Operation>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = operationPrefix(documentId, scope, branch);\n const startIndex = revision + 1;\n const parsedCursor = paging?.cursor\n ? Number.parseInt(paging.cursor, 10)\n : NaN;\n const cursorIndex =\n Number.isFinite(parsedCursor) && parsedCursor > 0\n ? parsedCursor\n : startIndex;\n const effectiveStart = Math.max(startIndex, cursorIndex);\n\n const gt = prefix + pad(effectiveStart - 1);\n const lt = prefix + RANGE_UPPER_BOUND;\n const limit = paging?.limit ? paging.limit + 1 : undefined;\n\n const items: Operation[] = [];\n const stream = this.bee.createReadStream({ gt, lt, limit });\n\n for await (const entry of stream) {\n const stored = entry.value as StoredOperation;\n\n if (filter) {\n if (\n filter.actionTypes &&\n filter.actionTypes.length > 0 &&\n !filter.actionTypes.includes((stored.action as { type: string }).type)\n ) {\n continue;\n }\n if (\n filter.timestampFrom &&\n stored.timestampUtcMs < filter.timestampFrom\n ) {\n continue;\n }\n if (filter.timestampTo && stored.timestampUtcMs > filter.timestampTo) {\n continue;\n }\n if (\n filter.sinceRevision !== undefined &&\n stored.index < filter.sinceRevision\n ) {\n continue;\n }\n }\n\n items.push(this.toOperation(stored));\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? (resultItems[resultItems.length - 1].index + 1).toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getSince(\n documentId,\n scope,\n branch,\n revision,\n filter,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n /**\n * The paging cursor encodes the ordinal to resume from (one past the last\n * ordinal returned), not the last ordinal itself; \"\" or \"0\" (or anything\n * unparsable) means the start of the stream. Unlike the Kysely store's\n * `getSinceId` (whose auto-increment id starts at 1), this store's ordinal\n * counter starts at 0, so 0 is a real, valid ordinal and the same\n * ambiguous-cursor hazard as `getSince`/`getConflicting` applies here too.\n */\n async getSinceId(\n id: number,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<OperationWithContext>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const startId = id + 1;\n const parsedCursor = paging?.cursor\n ? Number.parseInt(paging.cursor, 10)\n : NaN;\n const cursorId =\n Number.isFinite(parsedCursor) && parsedCursor > 0\n ? parsedCursor\n : startId;\n const effectiveStart = Math.max(startId, cursorId);\n\n const gt = ordinalPrefix() + pad(effectiveStart - 1);\n const lt = ordinalPrefix() + RANGE_UPPER_BOUND;\n const limit = paging?.limit ? paging.limit + 1 : undefined;\n\n const items: OperationWithContext[] = [];\n const stream = this.bee.createReadStream({ gt, lt, limit });\n\n for await (const entry of stream) {\n const ordEntry = entry.value as OrdinalEntry;\n const ordinal = parseInt(entry.key.split(\"/\")[1], 10);\n\n items.push({\n operation: this.toOperation(ordEntry.operation),\n context: {\n documentId: ordEntry.documentId,\n documentType: ordEntry.documentType,\n scope: ordEntry.scope,\n branch: ordEntry.branch,\n ordinal,\n },\n });\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? (resultItems[resultItems.length - 1].context.ordinal + 1).toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getSinceId(\n id,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n /**\n * The paging cursor here encodes the index to resume from (one past the\n * last row returned), not the last row's own index, for the same reason as\n * `getSince`: a page ending at index 0 must not produce a cursor that is\n * indistinguishable from the start-of-stream sentinel.\n */\n async getConflicting(\n documentId: string,\n scope: string,\n branch: string,\n minTimestamp: string,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Operation>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = operationPrefix(documentId, scope, branch);\n const parsedCursor = paging?.cursor\n ? Number.parseInt(paging.cursor, 10)\n : NaN;\n const cursorIndex =\n Number.isFinite(parsedCursor) && parsedCursor > 0 ? parsedCursor : -1;\n\n const gte = cursorIndex >= 0 ? prefix + pad(cursorIndex) : prefix;\n const lt = prefix + RANGE_UPPER_BOUND;\n\n const stream = this.bee.createReadStream({ gte, lt });\n\n // One row past the page is all this needs: it proves a next page exists\n // and is dropped again below. The limit cannot be pushed down into\n // createReadStream, because minTimestamp is applied per entry as it is\n // read -- a raw range limit would stop short while matching operations\n // still lay further along the range.\n const readLimit = paging?.limit ? paging.limit + 1 : undefined;\n\n const items: Operation[] = [];\n\n for await (const entry of stream) {\n const stored = entry.value as StoredOperation;\n if (stored.timestampUtcMs >= minTimestamp) {\n items.push(this.toOperation(stored));\n // Every operation of a document shares one key prefix, so without\n // this the range walk drains the whole document to hand back a\n // single page. Breaking closes the stream: for-await calls the\n // iterator's return() on the way out.\n if (readLimit !== undefined && items.length >= readLimit) break;\n }\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? (resultItems[resultItems.length - 1].index + 1).toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getConflicting(\n documentId,\n scope,\n branch,\n minTimestamp,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n async getRevisions(\n documentId: string,\n branch: string,\n signal?: AbortSignal,\n ): Promise<DocumentRevisions> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = headPrefix(documentId);\n const stream = this.bee.createReadStream({\n gte: prefix,\n lt: prefix + \"~\",\n });\n\n const revision: Record<string, number> = {};\n let latestTimestamp = new Date(0).toISOString();\n\n for await (const entry of stream) {\n const parts = entry.key.split(\"/\");\n const entryScope = parts[3];\n const entryBranch = parts[4];\n\n if (entryBranch !== branch) {\n continue;\n }\n\n const headValue = entry.value as HeadEntryValue;\n revision[entryScope] = headValue.index + 1;\n\n if (headValue.latestTimestampUtcMs > latestTimestamp) {\n latestTimestamp = headValue.latestTimestampUtcMs;\n }\n }\n\n return { revision, latestTimestamp };\n }\n\n /**\n * A real maximum over the rows, not the head record's `latestTimestampUtcMs`:\n * that holds the last-indexed timestamp, which a re-append can leave behind a\n * later one, so it would under-report and admit a backdated auth write.\n */\n async getStreamLatestTimestamp(\n documentId: string,\n scope: string,\n branch: string,\n signal?: AbortSignal,\n ): Promise<string | undefined> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const stored = await this.getSince(\n documentId,\n scope,\n branch,\n -1,\n undefined,\n undefined,\n signal,\n );\n\n let latest: string | undefined;\n for (const operation of stored.results) {\n if (latest === undefined || operation.timestampUtcMs > latest) {\n latest = operation.timestampUtcMs;\n }\n }\n\n return latest;\n }\n\n async findOperationIds(\n documentId: string,\n scope: string,\n branch: string,\n opIds: string[],\n signal?: AbortSignal,\n ): Promise<Set<string>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const found = new Set<string>();\n if (opIds.length === 0) {\n return found;\n }\n\n const wanted = new Set(opIds);\n const stored = await this.getSince(\n documentId,\n scope,\n branch,\n -1,\n undefined,\n undefined,\n signal,\n );\n for (const operation of stored.results) {\n if (wanted.has(operation.id)) {\n found.add(operation.id);\n }\n }\n\n return found;\n }\n\n async getOperationsByIds(\n documentId: string,\n scope: string,\n branch: string,\n opIds: string[],\n signal?: AbortSignal,\n ): Promise<Operation[]> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n if (opIds.length === 0) {\n return [];\n }\n\n const wanted = new Set(opIds);\n const stored = await this.getSince(\n documentId,\n scope,\n branch,\n -1,\n undefined,\n undefined,\n signal,\n );\n const latest = new Map<string, Operation>();\n for (const operation of stored.results) {\n if (wanted.has(operation.id)) {\n latest.set(operation.id, operation);\n }\n }\n return [...latest.values()];\n }\n\n private serializeOperation(op: StoredOperation): StoredOperation {\n return {\n id: op.id,\n index: op.index,\n skip: op.skip,\n timestampUtcMs: op.timestampUtcMs,\n hash: op.hash,\n error: op.error,\n deniedReason: op.deniedReason,\n action: op.action,\n documentId: op.documentId,\n documentType: op.documentType,\n scope: op.scope,\n branch: op.branch,\n };\n }\n\n private toOperation(stored: StoredOperation): Operation {\n return {\n id: stored.id,\n index: stored.index,\n skip: stored.skip,\n timestampUtcMs: stored.timestampUtcMs,\n hash: stored.hash,\n error: stored.error || undefined,\n deniedReason: stored.deniedReason || undefined,\n action: stored.action,\n };\n }\n}\n","import Corestore from \"corestore\";\nimport Hyperbee from \"hyperbee\";\n\nexport class StorageManager {\n private store: Corestore;\n private bee: Hyperbee | undefined;\n\n constructor(storagePath: string) {\n this.store = new Corestore(storagePath);\n }\n\n async open(): Promise<void> {\n await this.store.ready();\n const core = this.store.get({ name: \"operations\" });\n this.bee = new Hyperbee(core, {\n keyEncoding: \"utf-8\",\n valueEncoding: \"json\",\n });\n await this.bee.ready();\n }\n\n async close(): Promise<void> {\n if (this.bee) {\n await this.bee.close();\n }\n await this.store.close();\n }\n\n getBee(): Hyperbee {\n if (!this.bee) {\n throw new Error(\"StorageManager not opened. Call open() first.\");\n }\n return this.bee;\n }\n}\n"],"mappings":";;;;;;;AAmQA,IAAI,wBAAwB,MAAM,8BAA8B,MAAM;CACrE;;;;;;;CAOA,YAAY,YAAY,SAAS;EAChC,MAAM,WAAW,YAAY,WAAW,WAAW;EACnD,KAAK,OAAO;EACZ,KAAK,aAAa;EAClB,MAAM,kBAAkB,MAAM,qBAAqB;CACpD;;CAEA,OAAO,QAAQ,OAAO;EACrB,OAAO,MAAM,QAAQ,KAAK,MAAM,MAAM,SAAS,2BAA2B,MAA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