@moyodb/sdk 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/assets/browser-worker-p7uX85l-.js +4 -0
- package/dist/assets/browser-worker-p7uX85l-.js.map +1 -0
- package/dist/assets/shared-worker-BALTqEUe.js +2 -0
- package/dist/assets/shared-worker-BALTqEUe.js.map +1 -0
- package/dist/chunks/{indexing-B0duqlUs.js → indexing-DdpU69Fd.js} +302 -69
- package/dist/chunks/{indexing-B0duqlUs.js.map → indexing-DdpU69Fd.js.map} +1 -1
- package/dist/codec.d.ts.map +1 -1
- package/dist/compression.d.ts.map +1 -1
- package/dist/engine/README.md +2 -2
- package/dist/engine/moyodb_engine.d.ts +2 -2
- package/dist/engine/moyodb_engine.js +22 -22
- package/dist/engine/moyodb_engine_bg.wasm +0 -0
- package/dist/engine/moyodb_engine_bg.wasm.d.ts +2 -2
- package/dist/engine/package.json +1 -1
- package/dist/engine/snippets/{moyodb-engine-1d53039816cbc2f7 → moyodb-engine-1f8134232168280b}/js/opfs_shim.js +8 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/indexing.d.ts +7 -0
- package/dist/indexing.d.ts.map +1 -1
- package/dist/moyodb-sdk.js +1329 -931
- package/dist/moyodb-sdk.js.map +1 -1
- package/dist/node-engine.js +382 -47
- package/dist/node-engine.js.map +1 -1
- package/dist/node.js +332 -44
- package/dist/node.js.map +1 -1
- package/dist/registry.d.ts.map +1 -1
- package/dist/subscriptions.d.ts.map +1 -1
- package/dist/worker-client.d.ts.map +1 -1
- package/dist/worker-server.d.ts.map +1 -1
- package/dist/worker.d.ts +10 -3
- package/dist/worker.d.ts.map +1 -1
- package/package.json +2 -1
- package/dist/assets/browser-worker-Bj2ErRvC.js +0 -4
- package/dist/assets/browser-worker-Bj2ErRvC.js.map +0 -1
- package/dist/assets/shared-worker-CMeTcusa.js +0 -2
- package/dist/assets/shared-worker-CMeTcusa.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-worker-p7uX85l-.js","names":[],"sources":["../../src/internal.ts","../../src/worker-protocol.ts","../../src/worker-server.ts","../../src/codec.ts","../../src/snappy.ts","../../src/compression.ts","../../src/errors.ts","../../src/indexing.ts","../../src/worker.ts","../../src/browser-worker.ts"],"sourcesContent":["export function isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object';\n}\n\nexport function compareStringsByCodeUnit(left: string, right: string): number {\n if (left < right) {\n return -1;\n }\n return left > right ? 1 : 0;\n}\n\n/**\n * Delays above 2^31-1 do not fit in the platform timer word. Node fires them\n * after 1ms; other runtimes can wrap them to zero. Clamp instead of aborting.\n */\nexport const MAX_TIMER_DELAY_MS = 2_147_483_647;\n\nexport function clampTimerDelayMs(delayMs: number): number {\n if (!Number.isFinite(delayMs) || delayMs <= 0) {\n return 0;\n }\n return delayMs > MAX_TIMER_DELAY_MS ? MAX_TIMER_DELAY_MS : delayMs;\n}\n\nexport function withTimeout<T>(promise: Promise<T>, timeoutMs: number, fallback: T): Promise<T> {\n return new Promise((resolve) => {\n const timeout = setTimeout(() => resolve(fallback), clampTimerDelayMs(timeoutMs));\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n () => {\n clearTimeout(timeout);\n resolve(fallback);\n }\n );\n });\n}\n","import type { IndexScanPage, WorkerApi, WorkerScanPage } from './worker-api';\nimport type { BatchOp } from './types';\nimport { isRecord } from './internal';\n\nexport const WORKER_PROTOCOL_VERSION = 1;\nexport const WORKER_PROTOCOL_READY = 'moyodb:worker-protocol:ready';\nexport const WORKER_PROTOCOL_REQUEST = 'moyodb:worker-protocol:request';\nexport const WORKER_PROTOCOL_RESPONSE = 'moyodb:worker-protocol:response';\nexport const WORKER_PROTOCOL_REQUEST_BATCH = 'moyodb:worker-protocol:request-batch';\nexport const WORKER_PROTOCOL_RESPONSE_BATCH = 'moyodb:worker-protocol:response-batch';\nexport const MAX_WORKER_BATCH_MESSAGES = 128;\nexport const MAX_WORKER_BATCH_BYTES = 1024 * 1024;\n\nexport const WORKER_COMMANDS = [\n 'open',\n 'close',\n 'destroy',\n 'deleteDB',\n 'begin',\n 'commit',\n 'rollback',\n 'autocommit',\n 'createStore',\n 'dropStore',\n 'clearStore',\n 'get',\n 'getMany',\n 'has',\n 'put',\n 'putMany',\n 'delete',\n 'deleteMany',\n 'applyBatch',\n 'scan',\n 'scanPage',\n 'closeCursor',\n 'getByIndex',\n 'scanByIndex',\n 'scanByIndexPage',\n 'getIndexes',\n 'reconcileIndexes',\n 'listStores',\n 'getVersion',\n 'changesSince',\n 'setSchemaVersion',\n 'exportSnapshot',\n 'importSnapshot',\n 'reset',\n 'compact',\n 'rebuild',\n 'stats',\n 'storageInfo',\n 'requestPersistence',\n 'setFailpoint'\n] as const;\n\nexport type WorkerCommand = (typeof WORKER_COMMANDS)[number];\n\ntype WorkerMethod<M extends WorkerCommand> = WorkerApi[M] extends (...args: infer Args) => Promise<infer Result>\n ? { args: Args; result: Result }\n : never;\n\nexport type WorkerCommandArgs<M extends WorkerCommand> = WorkerMethod<M>['args'];\nexport type WorkerCommandResult<M extends WorkerCommand> = WorkerMethod<M>['result'];\n/** Arguments of an autocommit command without the leading transaction id. */\nexport type AutocommitArgs<M extends AutocommitCommand> =\n WorkerCommandArgs<M> extends [number, ...infer Rest] ? Rest : never;\n\nexport const AUTOCOMMIT_COMMANDS = [\n 'get',\n 'getMany',\n 'has',\n 'put',\n 'putMany',\n 'delete',\n 'deleteMany',\n 'applyBatch',\n 'scan',\n 'getByIndex',\n 'scanByIndex',\n 'createStore',\n 'dropStore',\n 'clearStore'\n] as const;\n\n/**\n * Commands supported in one autocommit request. The worker replies after\n * commit (readwrite) or rollback (readonly).\n */\nexport type AutocommitCommand = (typeof AUTOCOMMIT_COMMANDS)[number];\n\nconst AUTOCOMMIT_COMMAND_SET = new Set<string>(AUTOCOMMIT_COMMANDS);\n\nexport function isAutocommitCommand(value: unknown): value is AutocommitCommand {\n return typeof value === 'string' && AUTOCOMMIT_COMMAND_SET.has(value);\n}\n\nexport type PackedBatchOpKey = {\n kind: 'put' | 'delete';\n key: Uint8Array;\n};\n\ntype PreparedWorkerCommandArgs<M extends WorkerCommand> = WorkerCommandArgs<M> | unknown[];\n\nconst PACKED_BINARY_LIST_V1 = 'moyodb:packed-binary-list:v1';\nconst PACKED_NULLABLE_BINARY_LIST_V1 = 'moyodb:packed-nullable-binary-list:v1';\nconst PACKED_SCAN_ROWS_V1 = 'moyodb:packed-scan-rows:v1';\nconst PACKED_ENGINE_SCAN_ROWS_V1 = 'moyodb:packed-engine-scan-rows:v1';\nconst PACKED_BATCH_OPS_V1 = 'moyodb:packed-batch-ops:v1';\n// Engine getMany format: u32 count | count x u32 length | concatenated values.\n// Integers are little-endian; u32::MAX marks a missing value. No repacking is needed.\nconst PACKED_OPTIONAL_VALUES_V1 = 'moyodb:packed-optional-values:v1';\nconst BATCH_OP_DELETE = 0;\nconst BATCH_OP_PUT = 1;\nconst U32_MAX = 0xffff_ffff;\nconst MAX_PACKED_RESPONSE_BYTES = 16 * 1024 * 1024;\nconst EMPTY_TRANSFERABLES: Transferable[] = [];\n\ninterface PackedBinaryListV1 {\n __moyodbPacked: typeof PACKED_BINARY_LIST_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedNullableBinaryListV1 {\n __moyodbPacked: typeof PACKED_NULLABLE_BINARY_LIST_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedScanRowsV1 {\n __moyodbPacked: typeof PACKED_SCAN_ROWS_V1;\n bytes: Uint8Array;\n}\nexport interface PackedEngineScanRowsV1 {\n __moyodbPacked: typeof PACKED_ENGINE_SCAN_ROWS_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedBatchOpsV1 {\n __moyodbPacked: typeof PACKED_BATCH_OPS_V1;\n bytes: Uint8Array;\n}\n\nexport interface PackedOptionalValuesV1 {\n __moyodbPacked: typeof PACKED_OPTIONAL_VALUES_V1;\n bytes: Uint8Array;\n}\n\ninterface PackedBytes {\n __moyodbPacked: string;\n bytes: Uint8Array;\n}\n\ninterface PackedIndexScanPage {\n rows: PackedScanRowsV1 | IndexScanPage['rows'];\n cursor: Uint8Array | null;\n}\n\nexport type WorkerProtocolReadyMessage = {\n type: typeof WORKER_PROTOCOL_READY;\n version: typeof WORKER_PROTOCOL_VERSION;\n /** Enables batching; omitted by peers that use single messages. */\n batching?: 1;\n};\n\nexport type WorkerProtocolRequestMessage = {\n [M in WorkerCommand]: {\n type: typeof WORKER_PROTOCOL_REQUEST;\n version: typeof WORKER_PROTOCOL_VERSION;\n id: number;\n command: M;\n args: PreparedWorkerCommandArgs<M>;\n };\n}[WorkerCommand];\n\nexport interface WorkerProtocolRequestBatchMessage {\n type: typeof WORKER_PROTOCOL_REQUEST_BATCH;\n version: typeof WORKER_PROTOCOL_VERSION;\n requests: WorkerProtocolRequestMessage[];\n}\n\nexport interface SerializedWorkerError {\n name: string;\n code?: string;\n message: string;\n stack?: string;\n}\n\nexport type WorkerProtocolSuccessMessage = {\n [M in WorkerCommand]: {\n type: typeof WORKER_PROTOCOL_RESPONSE;\n version: typeof WORKER_PROTOCOL_VERSION;\n id: number;\n ok: true;\n result: WorkerCommandResult<M>;\n };\n}[WorkerCommand];\n\nexport interface WorkerProtocolErrorMessage {\n type: typeof WORKER_PROTOCOL_RESPONSE;\n version: typeof WORKER_PROTOCOL_VERSION;\n id: number;\n ok: false;\n error: SerializedWorkerError;\n}\n\nexport type WorkerProtocolResponseMessage = WorkerProtocolSuccessMessage | WorkerProtocolErrorMessage;\n\nexport interface WorkerProtocolResponseBatchMessage {\n type: typeof WORKER_PROTOCOL_RESPONSE_BATCH;\n version: typeof WORKER_PROTOCOL_VERSION;\n responses: WorkerProtocolResponseMessage[];\n}\n\nconst WORKER_COMMAND_SET = new Set<string>(WORKER_COMMANDS);\n\nexport function isWorkerCommand(value: unknown): value is WorkerCommand {\n return typeof value === 'string' && WORKER_COMMAND_SET.has(value);\n}\n\nexport function isWorkerProtocolReadyMessage(value: unknown): value is WorkerProtocolReadyMessage {\n return (\n isWorkerProtocolReadyEnvelope(value) &&\n value.version === WORKER_PROTOCOL_VERSION &&\n (value.batching === undefined || value.batching === 1)\n );\n}\n\nexport function isWorkerProtocolReadyEnvelope(\n value: unknown\n): value is { type: typeof WORKER_PROTOCOL_READY; version?: unknown; batching?: unknown } {\n return isRecord(value) && value.type === WORKER_PROTOCOL_READY;\n}\n\nexport function isWorkerProtocolResponseMessage(value: unknown): value is WorkerProtocolResponseMessage {\n return (\n isRecord(value) &&\n value.type === WORKER_PROTOCOL_RESPONSE &&\n value.version === WORKER_PROTOCOL_VERSION &&\n typeof value.id === 'number' &&\n Number.isSafeInteger(value.id) &&\n typeof value.ok === 'boolean'\n );\n}\n\nexport function isWorkerProtocolRequestMessage(value: unknown): value is WorkerProtocolRequestMessage {\n return (\n isRecord(value) &&\n value.type === WORKER_PROTOCOL_REQUEST &&\n value.version === WORKER_PROTOCOL_VERSION &&\n typeof value.id === 'number' &&\n Number.isSafeInteger(value.id) &&\n typeof value.command === 'string' &&\n Array.isArray(value.args)\n );\n}\n\nexport function isWorkerProtocolRequestBatchMessage(value: unknown): value is WorkerProtocolRequestBatchMessage {\n return isWorkerProtocolBatch(value, WORKER_PROTOCOL_REQUEST_BATCH, 'requests');\n}\n\nexport function isWorkerProtocolResponseBatchMessage(value: unknown): value is WorkerProtocolResponseBatchMessage {\n if (!isWorkerProtocolBatch(value, WORKER_PROTOCOL_RESPONSE_BATCH, 'responses')) {\n return false;\n }\n for (const response of (value as WorkerProtocolResponseBatchMessage).responses) {\n if (!isWorkerProtocolResponseMessage(response)) return false;\n }\n return true;\n}\n\nfunction isWorkerProtocolBatch(value: unknown, type: string, items: string): boolean {\n return (\n isRecord(value) &&\n value.type === type &&\n value.version === WORKER_PROTOCOL_VERSION &&\n Array.isArray(value[items]) &&\n value[items].length > 0 &&\n value[items].length <= MAX_WORKER_BATCH_MESSAGES\n );\n}\n\nexport function isWorkerProtocolEnvelope(value: unknown): value is { type: string; id?: unknown } {\n return (\n isRecord(value) &&\n (value.type === WORKER_PROTOCOL_REQUEST ||\n value.type === WORKER_PROTOCOL_RESPONSE ||\n value.type === WORKER_PROTOCOL_REQUEST_BATCH ||\n value.type === WORKER_PROTOCOL_RESPONSE_BATCH ||\n value.type === WORKER_PROTOCOL_READY)\n );\n}\n\nexport function serializeWorkerError(error: unknown): SerializedWorkerError {\n if (isRecord(error)) {\n const code = stringOrUndefined(error.code);\n const name = stringOrUndefined(error.name) ?? code ?? 'Error';\n return {\n name,\n code,\n message: stringOrUndefined(error.message) ?? 'Unknown error',\n stack: stringOrUndefined(error.stack)\n };\n }\n return {\n name: 'Error',\n message: String(error)\n };\n}\n\nexport function deserializeWorkerError(error: unknown): Error {\n if (\n !isRecord(error) ||\n typeof error.name !== 'string' ||\n typeof error.message !== 'string' ||\n (error.code !== undefined && typeof error.code !== 'string') ||\n (error.stack !== undefined && typeof error.stack !== 'string')\n ) {\n throw workerProtocolError('WorkerProtocolError', 'invalid serialized worker error');\n }\n const deserialized = new Error(error.message);\n deserialized.name = error.name || error.code || 'Error';\n if (error.stack) {\n deserialized.stack = error.stack;\n }\n if (error.code) {\n defineErrorCode(deserialized, error.code);\n }\n return deserialized;\n}\n\nexport function workerProtocolError(name: string, message: string, code = name): Error {\n const error = new Error(message);\n error.name = name;\n defineErrorCode(error, code);\n return error;\n}\n\nfunction defineErrorCode(error: Error, code: string): void {\n Object.defineProperty(error, 'code', {\n value: code,\n enumerable: true,\n configurable: true\n });\n}\n\nexport function prepareWorkerCommandPayload<M extends WorkerCommand>(\n command: M,\n args: WorkerCommandArgs<M>\n): { args: PreparedWorkerCommandArgs<M>; transfer: Transferable[] } {\n if (command === 'autocommit') {\n const [mode, inner, innerArgs] = args as WorkerCommandArgs<'autocommit'>;\n if (isAutocommitCommand(inner) && Array.isArray(innerArgs)) {\n // The normal packer expects a transaction ID. Use a placeholder, then remove it.\n const prepared = prepareWorkerCommandPayload(inner, [0, ...innerArgs] as never);\n return {\n args: [mode, inner, (prepared.args as unknown[]).slice(1)],\n transfer: prepared.transfer\n };\n }\n }\n\n if (\n command === 'get' ||\n command === 'has' ||\n command === 'delete' ||\n command === 'getByIndex' ||\n command === 'put'\n ) {\n const keyIndex = command === 'getByIndex' ? 3 : 2;\n let copiedArgs: unknown[] | null = null;\n let transfer: Transferable[] | null = null;\n for (let index = keyIndex; index <= (command === 'put' ? 3 : keyIndex); index += 1) {\n const value = args[index];\n if (\n value instanceof Uint8Array &&\n value.buffer instanceof ArrayBuffer &&\n (value.byteOffset !== 0 || value.byteLength !== value.buffer.byteLength)\n ) {\n const owned = copyToOwnedUint8Array(value);\n copiedArgs ??= [...args];\n copiedArgs[index] = owned;\n (transfer ??= []).push(owned.buffer);\n }\n }\n if (copiedArgs !== null) {\n return { args: copiedArgs, transfer: transfer ?? EMPTY_TRANSFERABLES };\n }\n }\n\n if (command === 'importSnapshot') {\n const data = args[0];\n if (data instanceof Uint8Array) {\n const owned = copyToOwnedUint8Array(data);\n return {\n args: [owned] as WorkerCommandArgs<M>,\n transfer: [owned.buffer]\n };\n }\n }\n\n if (command === 'getMany' || command === 'deleteMany') {\n const [txId, store, keys] = args as WorkerCommandArgs<'getMany'> | WorkerCommandArgs<'deleteMany'>;\n if (Array.isArray(keys) && keys.length > 0) {\n const packed = packBinaryList(keys);\n return {\n args: [txId, store, packed],\n transfer: [packed.bytes.buffer]\n };\n }\n }\n\n if (command === 'putMany') {\n const [txId, store, entries, options] = args as WorkerCommandArgs<'putMany'>;\n if (Array.isArray(entries) && entries.length > 0) {\n const packed = packBinaryPairs(entries);\n return {\n args: [txId, store, packed, options],\n transfer: [packed.bytes.buffer]\n };\n }\n }\n\n if (command === 'applyBatch') {\n const [txId, store, ops] = args as WorkerCommandArgs<'applyBatch'>;\n if (Array.isArray(ops) && ops.length > 0) {\n const packed = packBatchOps(ops);\n return {\n args: [txId, store, packed],\n transfer: [packed.bytes.buffer]\n };\n }\n }\n\n return { args, transfer: EMPTY_TRANSFERABLES };\n}\n\nexport function decodeWorkerCommandPayload<M extends WorkerCommand>(\n command: M,\n args: PreparedWorkerCommandArgs<M>\n): WorkerCommandArgs<M> {\n if (command === 'autocommit') {\n const [mode, inner, innerArgs] = args as WorkerCommandArgs<'autocommit'>;\n if (isAutocommitCommand(inner) && Array.isArray(innerArgs)) {\n const decoded = decodeWorkerCommandPayload(inner, [0, ...innerArgs]) as unknown[];\n return [mode, inner, decoded.slice(1)] as WorkerCommandArgs<M>;\n }\n }\n\n if (command === 'getMany' || command === 'deleteMany') {\n const [txId, store, keys] = args as WorkerCommandArgs<'getMany'> | WorkerCommandArgs<'deleteMany'>;\n if (!Array.isArray(keys)) {\n if (!isPackedPayload(keys, PACKED_BINARY_LIST_V1)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed binary-list argument');\n }\n return [txId, store, unpackBinaryList(keys)] as WorkerCommandArgs<M>;\n }\n }\n\n if (command === 'putMany') {\n const [txId, store, entries, options] = args as WorkerCommandArgs<'putMany'>;\n if (!Array.isArray(entries)) {\n if (!isPackedPayload(entries, PACKED_BINARY_LIST_V1)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed putMany argument');\n }\n return [txId, store, unpackPutManyPayload(entries, false), options] as WorkerCommandArgs<M>;\n }\n }\n\n if (command === 'applyBatch') {\n const [txId, store, ops] = args as WorkerCommandArgs<'applyBatch'>;\n if (!Array.isArray(ops)) {\n if (!isPackedPayload(ops, PACKED_BATCH_OPS_V1)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed batch argument');\n }\n return [txId, store, unpackBatchPayload(ops, false)] as WorkerCommandArgs<M>;\n }\n }\n\n return args;\n}\n\nexport function packedBinaryListBytes(value: unknown): Uint8Array | null {\n return isPackedPayload(value, PACKED_BINARY_LIST_V1) ? value.bytes : null;\n}\n\nexport function packedBatchOpsBytes(value: unknown): Uint8Array | null {\n return isPackedPayload(value, PACKED_BATCH_OPS_V1) ? value.bytes : null;\n}\n\nexport function unpackPackedBinaryList(bytes: Uint8Array): Uint8Array[] {\n return unpackBinaryList({ __moyodbPacked: PACKED_BINARY_LIST_V1, bytes });\n}\n\nexport function unpackPackedBinaryPairs(bytes: Uint8Array): Array<[Uint8Array, Uint8Array]> {\n return unpackPutManyPayload({ __moyodbPacked: PACKED_BINARY_LIST_V1, bytes }, false);\n}\n\nexport function unpackPackedBinaryPairKeys(bytes: Uint8Array): Uint8Array[] {\n return unpackPutManyPayload({ __moyodbPacked: PACKED_BINARY_LIST_V1, bytes }, true);\n}\n\nexport function unpackPackedBatchOps(bytes: Uint8Array): Array<BatchOp> {\n return unpackBatchPayload({ __moyodbPacked: PACKED_BATCH_OPS_V1, bytes }, false);\n}\n\nexport function unpackPackedBatchOpKeys(bytes: Uint8Array): PackedBatchOpKey[] {\n return unpackBatchPayload({ __moyodbPacked: PACKED_BATCH_OPS_V1, bytes }, true);\n}\n\nexport function packedOptionalValues(bytes: Uint8Array): PackedOptionalValuesV1 {\n return { __moyodbPacked: PACKED_OPTIONAL_VALUES_V1, bytes };\n}\n\nexport function unpackPackedOptionalValues(bytes: Uint8Array): Array<Uint8Array | null> {\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed optional-values payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 4, 'packed optional-values metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed optional-values header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed optional-values metadata exceeds payload length');\n }\n const items = new Array<Uint8Array | null>(count);\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const byteLength = view.getUint32(4 + index * 4, true);\n if (byteLength === U32_MAX) {\n items[index] = null;\n continue;\n }\n const end = readOffset + byteLength;\n if (end > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed optional-values item exceeds payload length');\n }\n items[index] = bytes.subarray(readOffset, end);\n readOffset = end;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed optional-values payload has trailing bytes');\n }\n return items;\n}\n\nexport function prepareWorkerResponsePayload<M extends WorkerCommand>(\n command: M,\n result: WorkerCommandResult<M>\n): { result: unknown; transfer: Transferable[] } {\n if (\n (command === 'scan' || command === 'scanByIndex') &&\n (isPackedEngineScanRows(result) || isPackedPayload(result, PACKED_SCAN_ROWS_V1))\n ) {\n return { result, transfer: collectDirectBinaryTransferable(result.bytes) };\n }\n if (command === 'scanPage') {\n const page = result as WorkerScanPage;\n if (isRecord(page) && (isPackedEngineScanRows(page.rows) || isPackedPayload(page.rows, PACKED_SCAN_ROWS_V1))) {\n return { result: page, transfer: collectDirectBinaryTransferable(page.rows.bytes) };\n }\n if (isRecord(page) && Array.isArray(page.rows)) {\n const packed = packScanRows(page.rows);\n return {\n result: { ...page, rows: packed ?? page.rows },\n transfer: packed ? [packed.bytes.buffer] : collectTransferablesForValue(page.rows)\n };\n }\n }\n if (command === 'getMany' && isPackedPayload(result, PACKED_OPTIONAL_VALUES_V1)) {\n return {\n result,\n transfer: collectDirectBinaryTransferable(result.bytes)\n };\n }\n\n if (command === 'scanByIndexPage') {\n const page = result as WorkerCommandResult<'scanByIndexPage'>;\n if (isRecord(page) && isPackedPayload(page.rows, PACKED_SCAN_ROWS_V1)) {\n return { result: page, transfer: collectTransferablesForValue(page) };\n }\n if (isRecord(page) && Array.isArray(page.rows)) {\n const packed = page.rows.length > 0 ? packScanRows(page.rows) : null;\n const response: PackedIndexScanPage = { rows: packed ?? page.rows, cursor: page.cursor };\n const transfer = packed ? [packed.bytes.buffer] : collectTransferablesForValue(page.rows);\n const cursorBuffer = directBinaryTransferable(page.cursor);\n return {\n result: response,\n transfer: cursorBuffer === null ? transfer : [...transfer, cursorBuffer]\n };\n }\n }\n\n if (command === 'getMany') {\n const values = result as WorkerCommandResult<'getMany'>;\n if (Array.isArray(values) && values.length > 0) {\n const packed = packNullableBinaryList(values);\n if (packed) {\n return {\n result: packed,\n transfer: [packed.bytes.buffer]\n };\n }\n }\n return {\n result,\n transfer: collectTransferablesForValue(result)\n };\n }\n\n if (command === 'scan' || command === 'scanByIndex') {\n const rows = result as WorkerCommandResult<'scan'>;\n if (Array.isArray(rows) && rows.length > 0) {\n const packed = packScanRows(rows);\n if (packed) {\n return {\n result: packed,\n transfer: [packed.bytes.buffer]\n };\n }\n }\n return {\n result,\n transfer: collectTransferablesForValue(result)\n };\n }\n\n if (command === 'get' || command === 'getByIndex' || command === 'exportSnapshot') {\n return {\n result,\n transfer: collectDirectBinaryTransferable(result)\n };\n }\n\n if (command === 'changesSince') {\n return {\n result,\n transfer: collectChangeFeedTransferables(result)\n };\n }\n\n // Remaining result types contain no binary payloads, so they need no buffer walk.\n return {\n result,\n transfer: []\n };\n}\n\nexport function decodeWorkerResponsePayload<M extends WorkerCommand>(\n command: M,\n result: unknown\n): WorkerCommandResult<M> {\n if (command === 'scanPage') {\n if (\n !isRecord(result) ||\n typeof result.done !== 'boolean' ||\n typeof result.bytes !== 'number' ||\n !Number.isSafeInteger(result.bytes) ||\n result.bytes < 4 ||\n (result.cursorId !== undefined &&\n (typeof result.cursorId !== 'number' ||\n !Number.isSafeInteger(result.cursorId) ||\n result.cursorId <= 0)) ||\n (result.done ? result.cursorId !== undefined : result.cursorId === undefined)\n ) {\n throw workerProtocolError('WorkerProtocolError', 'invalid scan page response');\n }\n const rows = isPackedEngineScanRows(result.rows)\n ? unpackPackedScanRows(result.rows.bytes)\n : isPackedPayload(result.rows, PACKED_SCAN_ROWS_V1)\n ? unpackScanRows(result.rows)\n : result.rows;\n if (!Array.isArray(rows)) throw workerProtocolError('WorkerProtocolError', 'invalid scan page rows');\n let bytes = 4;\n for (const row of rows) {\n if (!isRecord(row) || !(row.key instanceof Uint8Array) || !(row.value instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid scan page row');\n }\n bytes += 8 + row.key.byteLength + row.value.byteLength;\n }\n if (bytes !== result.bytes) throw workerProtocolError('WorkerProtocolError', 'scan page byte count mismatch');\n return { rows, cursorId: result.cursorId, done: result.done, bytes: result.bytes } as WorkerCommandResult<M>;\n }\n if ((command === 'scan' || command === 'scanByIndex') && isPackedEngineScanRows(result)) {\n return unpackPackedScanRows(result.bytes) as WorkerCommandResult<M>;\n }\n if (command === 'getMany' && isPackedPayload(result, PACKED_NULLABLE_BINARY_LIST_V1)) {\n return unpackNullableBinaryList(result);\n }\n\n if (command === 'getMany' && isPackedPayload(result, PACKED_OPTIONAL_VALUES_V1)) {\n return unpackPackedOptionalValues(result.bytes) as WorkerCommandResult<M>;\n }\n\n if (command === 'getMany' && !Array.isArray(result)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed getMany response');\n }\n\n if (command === 'scanByIndexPage') {\n if (\n !isRecord(result) ||\n (!Array.isArray(result.rows) && !isPackedPayload(result.rows, PACKED_SCAN_ROWS_V1)) ||\n (result.cursor !== null && !(result.cursor instanceof Uint8Array))\n ) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed index scan page response');\n }\n const rows = isPackedPayload(result.rows, PACKED_SCAN_ROWS_V1) ? unpackScanRows(result.rows) : result.rows;\n return { rows, cursor: result.cursor } as WorkerCommandResult<M>;\n }\n\n if ((command === 'scan' || command === 'scanByIndex') && isPackedPayload(result, PACKED_SCAN_ROWS_V1)) {\n return unpackScanRows(result);\n }\n\n if ((command === 'scan' || command === 'scanByIndex') && !Array.isArray(result)) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed scan response');\n }\n\n return result;\n}\nexport function packedScanRows(bytes: Uint8Array): PackedEngineScanRowsV1 {\n return { __moyodbPacked: PACKED_ENGINE_SCAN_ROWS_V1, bytes };\n}\nfunction isPackedEngineScanRows(value: unknown): value is PackedEngineScanRowsV1 {\n return isRecord(value) && value.__moyodbPacked === PACKED_ENGINE_SCAN_ROWS_V1 && value.bytes instanceof Uint8Array;\n}\nexport function unpackPackedScanRows(bytes: Uint8Array): Array<{ key: Uint8Array; value: Uint8Array }> {\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid engine scan packet');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n if (count > (bytes.byteLength - 4) / 8) {\n throw workerProtocolError('WorkerProtocolError', 'engine scan row count exceeds packet length');\n }\n const rows = new Array<{ key: Uint8Array; value: Uint8Array }>(count);\n let offset = 4;\n for (let index = 0; index < count; index += 1) {\n if (offset + 8 > bytes.byteLength)\n throw workerProtocolError('WorkerProtocolError', 'truncated engine scan row');\n const keyLength = view.getUint32(offset, true);\n const valueLength = view.getUint32(offset + 4, true);\n const keyStart = offset + 8;\n const valueStart = keyStart + keyLength;\n const end = valueStart + valueLength;\n if (end > bytes.byteLength)\n throw workerProtocolError('WorkerProtocolError', 'engine scan row exceeds packet length');\n rows[index] = { key: bytes.subarray(keyStart, valueStart), value: bytes.subarray(valueStart, end) };\n offset = end;\n }\n if (offset !== bytes.byteLength)\n throw workerProtocolError('WorkerProtocolError', 'engine scan packet has trailing bytes');\n return rows;\n}\n\nexport function collectTransferablesForValue(value: unknown): Transferable[] {\n const direct = directBinaryTransferable(value);\n if (direct !== null) {\n return [direct];\n }\n if (value === null || value === undefined || typeof value !== 'object') {\n return EMPTY_TRANSFERABLES;\n }\n\n const buffers = new Set<ArrayBuffer>();\n const seen = new WeakSet<object>();\n collectTransferableBuffers(value, buffers, seen);\n return buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers);\n}\n\n/**\n * Capture the message before batching can observe later mutations. Listed\n * transferables move into the snapshot; other ArrayBuffers are cloned.\n * SharedArrayBuffers remain shared. byteLength is a batch-size estimate.\n */\nexport function captureWorkerPayload<T>(\n value: T,\n transfer: Transferable[]\n): { value: T; transfer: Transferable[]; byteLength: number } {\n const captured =\n transfer.length > 0\n ? structuredClone(value, { transfer: transfer.length === 1 ? transfer : Array.from(new Set(transfer)) })\n : structuredClone(value);\n const buffers = new Set<ArrayBuffer>();\n const seen = new WeakSet<object>();\n let byteLength = 0;\n const visit = (item: unknown): void => {\n if (typeof item === 'string') {\n byteLength += 8 + item.length * 2;\n return;\n }\n if (item === null || typeof item !== 'object') {\n byteLength += 8;\n return;\n }\n if (seen.has(item)) return;\n seen.add(item);\n byteLength += 8;\n if (item instanceof ArrayBuffer) {\n buffers.add(item);\n byteLength += item.byteLength;\n } else if (typeof SharedArrayBuffer !== 'undefined' && item instanceof SharedArrayBuffer) {\n byteLength += item.byteLength;\n } else if (ArrayBuffer.isView(item)) {\n visit(item.buffer);\n } else if (Array.isArray(item)) {\n for (const child of item) visit(child);\n } else if (item instanceof Map) {\n for (const [key, child] of item) {\n visit(key);\n visit(child);\n }\n } else if (item instanceof Set) {\n for (const child of item) visit(child);\n } else {\n const record = item as Record<string, unknown>;\n for (const key in record) {\n if (Object.prototype.hasOwnProperty.call(record, key)) {\n byteLength += 8 + key.length * 2;\n visit(record[key]);\n }\n }\n }\n };\n visit(captured);\n return {\n value: captured,\n transfer: buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers),\n byteLength\n };\n}\n\nfunction collectDirectBinaryTransferable(value: unknown): Transferable[] {\n const direct = directBinaryTransferable(value);\n return direct === null ? EMPTY_TRANSFERABLES : [direct];\n}\n\nfunction directBinaryTransferable(value: unknown): ArrayBuffer | null {\n if (value instanceof ArrayBuffer) {\n return value;\n }\n if (ArrayBuffer.isView(value)) {\n const buffer = value.buffer;\n if (buffer instanceof ArrayBuffer && value.byteOffset === 0 && value.byteLength === buffer.byteLength) {\n return buffer;\n }\n }\n return null;\n}\n\nfunction collectChangeFeedTransferables(value: unknown): Transferable[] {\n if (!isRecord(value) || !Array.isArray(value.changes) || value.changes.length === 0) {\n return EMPTY_TRANSFERABLES;\n }\n\n let buffers: Set<ArrayBuffer> | null = null;\n for (const change of value.changes) {\n if (!isRecord(change)) {\n continue;\n }\n const key = directBinaryTransferable(change.key);\n if (key !== null) {\n buffers ??= new Set<ArrayBuffer>();\n buffers.add(key);\n }\n const changedValue = directBinaryTransferable(change.value);\n if (changedValue !== null) {\n buffers ??= new Set<ArrayBuffer>();\n buffers.add(changedValue);\n }\n }\n return buffers === null || buffers.size === 0 ? EMPTY_TRANSFERABLES : Array.from(buffers);\n}\n\nfunction collectTransferableBuffers(value: unknown, buffers: Set<ArrayBuffer>, seen: WeakSet<object>): void {\n if (value === null || value === undefined) {\n return;\n }\n if (value instanceof ArrayBuffer) {\n buffers.add(value);\n return;\n }\n if (ArrayBuffer.isView(value)) {\n const buffer = value.buffer;\n if (buffer instanceof ArrayBuffer && value.byteOffset === 0 && value.byteLength === buffer.byteLength) {\n buffers.add(buffer);\n }\n return;\n }\n if (typeof value !== 'object') {\n return;\n }\n const object = value;\n if (seen.has(object)) {\n return;\n }\n seen.add(object);\n if (Array.isArray(value)) {\n for (const item of value) {\n collectTransferableBuffers(item, buffers, seen);\n }\n return;\n }\n const record = value as Record<string, unknown>;\n for (const key in record) {\n if (Object.prototype.hasOwnProperty.call(record, key)) {\n collectTransferableBuffers(record[key], buffers, seen);\n }\n }\n}\n\nfunction packBinaryPairs(entries: Array<[Uint8Array, Uint8Array]>): PackedBinaryListV1 {\n const entryCount = entries.length;\n const count = checkedU32(entryCount * 2, 'packed putMany item count');\n const metadataBytes = checkedByteCount(count, 4, 'packed putMany metadata');\n let payloadBytes = 0;\n for (let index = 0; index < entryCount; index += 1) {\n const entry = entries[index];\n const key = entry[0];\n const value = entry[1];\n if (!(key instanceof Uint8Array) || !(value instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'putMany entry key/value is not a Uint8Array');\n }\n const keyLength = checkedU32(key.byteLength, 'putMany key length');\n const valueLength = checkedU32(value.byteLength, 'putMany value length');\n payloadBytes += keyLength + valueLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload exceeds 32-bit payload limit');\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed putMany header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed putMany total');\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < entryCount; index += 1) {\n const entry = entries[index];\n const key = entry[0];\n const value = entry[1];\n const keyLength = key.byteLength;\n const valueLength = value.byteLength;\n view.setUint32(metadataOffset, keyLength, true);\n metadataOffset += 4;\n view.setUint32(metadataOffset, valueLength, true);\n metadataOffset += 4;\n bytes.set(key, writeOffset);\n writeOffset += keyLength;\n bytes.set(value, writeOffset);\n writeOffset += valueLength;\n }\n return {\n __moyodbPacked: PACKED_BINARY_LIST_V1,\n bytes\n };\n}\n\nfunction packBinaryList(items: Uint8Array[]): PackedBinaryListV1 {\n const count = items.length;\n const metadataBytes = checkedByteCount(count, 4, 'packed binary-list metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n if (!(item instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'binary-list payload item is not a Uint8Array');\n }\n const itemLength = checkedU32(item.byteLength, 'binary-list item length');\n payloadBytes += itemLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list payload exceeds 32-bit payload limit');\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed binary-list header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed binary-list total');\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n const itemLength = item.byteLength;\n view.setUint32(metadataOffset, itemLength, true);\n metadataOffset += 4;\n bytes.set(item, writeOffset);\n writeOffset += itemLength;\n }\n return {\n __moyodbPacked: PACKED_BINARY_LIST_V1,\n bytes\n };\n}\n\nfunction unpackBinaryList(payload: PackedBytes): Uint8Array[] {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed binary-list payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 4, 'packed binary-list metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed binary-list header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list metadata exceeds payload length');\n }\n\n const items = new Array<Uint8Array>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const byteLength = view.getUint32(metadataOffset, true);\n metadataOffset += 4;\n const end = readOffset + byteLength;\n if (end > U32_MAX || end > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list item exceeds payload length');\n }\n items[index] = bytes.subarray(readOffset, end);\n readOffset = end;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed binary-list payload has trailing bytes');\n }\n return items;\n}\n\nfunction unpackPutManyPayload(payload: PackedBytes, keysOnly: true): Uint8Array[];\nfunction unpackPutManyPayload(payload: PackedBytes, keysOnly: false): Array<[Uint8Array, Uint8Array]>;\nfunction unpackPutManyPayload(payload: PackedBytes, keysOnly: boolean): Uint8Array[] | Array<[Uint8Array, Uint8Array]> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed putMany payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const itemCount = view.getUint32(0, true);\n if (itemCount % 2 !== 0) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload has an odd item count');\n }\n const metadataBytes = checkedByteCount(itemCount, 4, 'packed putMany metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed putMany header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany metadata exceeds payload length');\n }\n\n const entryCount = itemCount / 2;\n const entries = new Array<Uint8Array | [Uint8Array, Uint8Array]>(entryCount);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < entryCount; index += 1) {\n const keyLength = view.getUint32(metadataOffset, true);\n const valueLength = view.getUint32(metadataOffset + 4, true);\n metadataOffset += 8;\n\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany key exceeds payload length');\n }\n const valueEnd = keyEnd + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany value exceeds payload length');\n }\n if (keysOnly) {\n entries[index] = bytes.subarray(readOffset, keyEnd);\n } else {\n entries[index] = [bytes.subarray(readOffset, keyEnd), bytes.subarray(keyEnd, valueEnd)];\n }\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed putMany payload has trailing bytes');\n }\n return entries as Uint8Array[] | Array<[Uint8Array, Uint8Array]>;\n}\n\nfunction packNullableBinaryList(items: Array<Uint8Array | null>): PackedNullableBinaryListV1 | null {\n const count = items.length;\n const metadataBytes = checkedByteCount(count, 5, 'packed nullable binary-list metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n if (item === null) {\n continue;\n }\n if (!(item instanceof Uint8Array)) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n 'nullable binary-list payload item is not a Uint8Array or null'\n );\n }\n const itemLength = checkedU32(item.byteLength, 'nullable binary-list item length');\n payloadBytes += itemLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n 'packed nullable binary-list payload exceeds 32-bit payload limit'\n );\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed nullable binary-list header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed nullable binary-list total');\n if (totalBytes > MAX_PACKED_RESPONSE_BYTES) {\n return null;\n }\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const item = items[index];\n if (item === null) {\n view.setUint8(metadataOffset, 0);\n view.setUint32(metadataOffset + 1, 0, true);\n metadataOffset += 5;\n continue;\n }\n const itemLength = item.byteLength;\n view.setUint8(metadataOffset, 1);\n view.setUint32(metadataOffset + 1, itemLength, true);\n metadataOffset += 5;\n bytes.set(item, writeOffset);\n writeOffset += itemLength;\n }\n return {\n __moyodbPacked: PACKED_NULLABLE_BINARY_LIST_V1,\n bytes\n };\n}\n\nfunction unpackNullableBinaryList(payload: PackedBytes): Array<Uint8Array | null> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed nullable binary-list payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 5, 'packed nullable binary-list metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed nullable binary-list header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed nullable binary-list metadata exceeds payload length');\n }\n\n const items = new Array<Uint8Array | null>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const present = view.getUint8(metadataOffset);\n const byteLength = view.getUint32(metadataOffset + 1, true);\n metadataOffset += 5;\n if (present === 0) {\n if (byteLength !== 0) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n 'packed nullable binary-list null item has a payload length'\n );\n }\n items[index] = null;\n continue;\n }\n if (present !== 1) {\n throw workerProtocolError(\n 'WorkerProtocolError',\n `packed nullable binary-list item has invalid presence byte: ${present}`\n );\n }\n const end = readOffset + byteLength;\n if (end > U32_MAX || end > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed nullable binary-list item exceeds payload length');\n }\n items[index] = bytes.subarray(readOffset, end);\n readOffset = end;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed nullable binary-list payload has trailing bytes');\n }\n return items;\n}\n\nfunction packScanRows(rows: Array<{ key: Uint8Array; value: Uint8Array }>): PackedScanRowsV1 | null {\n const count = rows.length;\n const metadataBytes = checkedByteCount(count, 8, 'packed scan row metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const row = rows[index];\n if (!isRecord(row) || !(row.key instanceof Uint8Array) || !(row.value instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'scan row payload key/value is not a Uint8Array');\n }\n const keyLength = checkedU32(row.key.byteLength, 'scan row key length');\n const valueLength = checkedU32(row.value.byteLength, 'scan row value length');\n payloadBytes += keyLength + valueLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row payload exceeds 32-bit payload limit');\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed scan row header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed scan row total');\n if (totalBytes > MAX_PACKED_RESPONSE_BYTES) {\n return null;\n }\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const row = rows[index];\n const key = row.key;\n const value = row.value;\n const keyLength = key.byteLength;\n const valueLength = value.byteLength;\n view.setUint32(metadataOffset, keyLength, true);\n view.setUint32(metadataOffset + 4, valueLength, true);\n metadataOffset += 8;\n bytes.set(key, writeOffset);\n writeOffset += keyLength;\n bytes.set(value, writeOffset);\n writeOffset += valueLength;\n }\n return {\n __moyodbPacked: PACKED_SCAN_ROWS_V1,\n bytes\n };\n}\n\nfunction unpackScanRows(payload: PackedBytes): Array<{ key: Uint8Array; value: Uint8Array }> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed scan row payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 8, 'packed scan row metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed scan row header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row metadata exceeds payload length');\n }\n\n const rows = new Array<{ key: Uint8Array; value: Uint8Array }>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const keyLength = view.getUint32(metadataOffset, true);\n const valueLength = view.getUint32(metadataOffset + 4, true);\n metadataOffset += 8;\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row key exceeds payload length');\n }\n const valueEnd = keyEnd + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row value exceeds payload length');\n }\n rows[index] = {\n key: bytes.subarray(readOffset, keyEnd),\n value: bytes.subarray(keyEnd, valueEnd)\n };\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed scan row payload has trailing bytes');\n }\n return rows;\n}\n\nfunction packBatchOps(ops: Array<BatchOp>): PackedBatchOpsV1 {\n const count = ops.length;\n const metadataBytes = checkedByteCount(count, 9, 'packed batch metadata');\n let payloadBytes = 0;\n for (let index = 0; index < count; index += 1) {\n const op: unknown = ops[index];\n if (!isRecord(op) || (op.kind !== 'put' && op.kind !== 'delete')) {\n throw workerProtocolError('WorkerProtocolError', 'batch operation kind is not put or delete');\n }\n if (!(op.key instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'batch operation key is not a Uint8Array');\n }\n const keyLength = checkedU32(op.key.byteLength, 'batch operation key length');\n payloadBytes += keyLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch payload exceeds 32-bit payload limit');\n }\n if (op.kind === 'put') {\n if (!(op.value instanceof Uint8Array)) {\n throw workerProtocolError('WorkerProtocolError', 'batch put value is not a Uint8Array');\n }\n const valueLength = checkedU32(op.value.byteLength, 'batch put value length');\n payloadBytes += valueLength;\n if (payloadBytes > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch payload exceeds 32-bit payload limit');\n }\n }\n }\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed batch header');\n const totalBytes = checkedAdd(payloadOffset, payloadBytes, 'packed batch total');\n const bytes = new Uint8Array(totalBytes);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, count, true);\n let metadataOffset = 4;\n let writeOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const op = ops[index];\n const key = op.key;\n const keyLength = key.byteLength;\n const valueLength = op.kind === 'put' ? op.value.byteLength : 0;\n view.setUint8(metadataOffset, op.kind === 'put' ? BATCH_OP_PUT : BATCH_OP_DELETE);\n view.setUint32(metadataOffset + 1, keyLength, true);\n view.setUint32(metadataOffset + 5, valueLength, true);\n metadataOffset += 9;\n bytes.set(key, writeOffset);\n writeOffset += keyLength;\n if (op.kind === 'put') {\n bytes.set(op.value, writeOffset);\n writeOffset += valueLength;\n }\n }\n return {\n __moyodbPacked: PACKED_BATCH_OPS_V1,\n bytes\n };\n}\n\nfunction unpackBatchPayload(payload: PackedBytes, keysOnly: true): PackedBatchOpKey[];\nfunction unpackBatchPayload(payload: PackedBytes, keysOnly: false): Array<BatchOp>;\nfunction unpackBatchPayload(payload: PackedBytes, keysOnly: boolean): PackedBatchOpKey[] | Array<BatchOp> {\n const bytes = payload.bytes;\n if (!(bytes instanceof Uint8Array) || bytes.byteLength < 4) {\n throw workerProtocolError('WorkerProtocolError', 'invalid packed batch payload');\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const count = view.getUint32(0, true);\n const metadataBytes = checkedByteCount(count, 9, 'packed batch metadata');\n const payloadOffset = checkedAdd(4, metadataBytes, 'packed batch header');\n if (payloadOffset > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch metadata exceeds payload length');\n }\n\n const ops = new Array<BatchOp | PackedBatchOpKey>(count);\n let metadataOffset = 4;\n let readOffset = payloadOffset;\n for (let index = 0; index < count; index += 1) {\n const kind = view.getUint8(metadataOffset);\n const keyLength = view.getUint32(metadataOffset + 1, true);\n const valueLength = view.getUint32(metadataOffset + 5, true);\n metadataOffset += 9;\n\n const keyEnd = readOffset + keyLength;\n if (keyEnd > U32_MAX || keyEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch key exceeds payload length');\n }\n const key = bytes.subarray(readOffset, keyEnd);\n readOffset = keyEnd;\n\n if (kind === BATCH_OP_DELETE) {\n if (valueLength !== 0) {\n throw workerProtocolError('WorkerProtocolError', 'packed delete operation has a value payload');\n }\n ops[index] = { kind: 'delete', key };\n continue;\n }\n\n if (kind !== BATCH_OP_PUT) {\n throw workerProtocolError('WorkerProtocolError', `packed batch operation has invalid kind byte: ${kind}`);\n }\n const valueEnd = readOffset + valueLength;\n if (valueEnd > U32_MAX || valueEnd > bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch value exceeds payload length');\n }\n if (keysOnly) {\n ops[index] = { kind: 'put', key };\n } else {\n ops[index] = { kind: 'put', key, value: bytes.subarray(readOffset, valueEnd) };\n }\n readOffset = valueEnd;\n }\n if (readOffset !== bytes.byteLength) {\n throw workerProtocolError('WorkerProtocolError', 'packed batch payload has trailing bytes');\n }\n return ops as PackedBatchOpKey[] | Array<BatchOp>;\n}\n\nfunction isPackedPayload(value: unknown, tag: string): value is PackedBytes {\n return isRecord(value) && value.__moyodbPacked === tag && value.bytes instanceof Uint8Array;\n}\n\nfunction checkedByteCount(count: number, itemBytes: number, what: string): number {\n if (!Number.isSafeInteger(count) || count < 0) {\n throw workerProtocolError('WorkerProtocolError', `${what} count is invalid: ${count}`);\n }\n return checkedU32(count * itemBytes, what);\n}\n\nfunction checkedAdd(left: number, right: number, what: string): number {\n const total = left + right;\n return checkedU32(total, what);\n}\n\nfunction checkedU32(value: number, what: string): number {\n if (!Number.isSafeInteger(value) || value < 0 || value > U32_MAX) {\n throw workerProtocolError('WorkerProtocolError', `${what} exceeds 32-bit payload limit`);\n }\n return value;\n}\n\nfunction copyToOwnedUint8Array(value: Uint8Array): Uint8Array {\n const owned = new Uint8Array(value.byteLength);\n owned.set(value);\n return owned;\n}\n\nfunction stringOrUndefined(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n","import type { AutocommitCommand, WorkerApi } from './worker-api';\nimport {\n MAX_WORKER_BATCH_BYTES,\n MAX_WORKER_BATCH_MESSAGES,\n WORKER_PROTOCOL_READY,\n WORKER_PROTOCOL_RESPONSE,\n WORKER_PROTOCOL_RESPONSE_BATCH,\n WORKER_PROTOCOL_VERSION,\n captureWorkerPayload,\n decodeWorkerCommandPayload,\n isAutocommitCommand,\n packedBatchOpsBytes,\n packedBinaryListBytes,\n prepareWorkerResponsePayload,\n isWorkerCommand,\n isWorkerProtocolEnvelope,\n isWorkerProtocolRequestBatchMessage,\n isWorkerProtocolRequestMessage,\n serializeWorkerError,\n workerProtocolError,\n type WorkerProtocolErrorMessage,\n type WorkerProtocolResponseMessage,\n type WorkerProtocolResponseBatchMessage,\n type WorkerProtocolSuccessMessage,\n type WorkerCommand\n} from './worker-protocol';\nimport { isRecord } from './internal';\n\ntype PackedWorkerApi = WorkerApi & {\n getManyPacked?: (txId: number, store: string, packedKeys: Uint8Array) => Promise<unknown>;\n putManyPacked?: (txId: number, store: string, packedEntries: Uint8Array, options?: unknown) => Promise<unknown>;\n deleteManyPacked?: (txId: number, store: string, packedKeys: Uint8Array) => Promise<unknown>;\n applyBatchPacked?: (txId: number, store: string, packedOps: Uint8Array) => Promise<unknown>;\n};\n\nexport interface WorkerServerHandle {\n close(): void;\n}\n\nexport interface WorkerServerScope {\n postMessage(message: unknown, transfer?: Transferable[]): void;\n addEventListener(type: 'message', listener: (event: MessageEvent<unknown>) => void): void;\n removeEventListener(type: 'message', listener: (event: MessageEvent<unknown>) => void): void;\n readonly location: { readonly origin: string };\n}\n\n/** The first argument identifies the transaction lane. */\nconst TRANSACTION_COMMANDS = new Set<WorkerCommand>([\n 'commit',\n 'rollback',\n 'createStore',\n 'dropStore',\n 'clearStore',\n 'get',\n 'getMany',\n 'has',\n 'put',\n 'putMany',\n 'delete',\n 'deleteMany',\n 'applyBatch',\n 'scan',\n 'getByIndex',\n 'scanByIndex',\n 'scanByIndexPage',\n 'getIndexes',\n 'reconcileIndexes',\n 'setSchemaVersion'\n]);\n\n/** These commands require exclusive access to the open engine. */\nconst EXCLUSIVE_COMMANDS = new Set<WorkerCommand>([\n 'open',\n 'close',\n 'destroy',\n 'importSnapshot',\n 'reset',\n 'compact',\n 'rebuild'\n]);\n\n/**\n * These commands do not use the open engine, so browser storage calls\n * can run without delaying its close.\n */\nconst UNSCHEDULED_COMMANDS = new Set<WorkerCommand>(['deleteDB', 'storageInfo', 'requestPersistence']);\n\nconst noop = () => {};\n\n/**\n * Serializes each transaction lane, including awaited work. Readwrite\n * autocommits share one writer lane. Exclusive commands wait for scheduled\n * work and block later scheduled work until they finish.\n */\nclass RequestScheduler {\n #lanes = new Map<number | string, Promise<void>>();\n #inFlight = new Set<Promise<void>>();\n #barrier: Promise<void> = Promise.resolve();\n #cursorLanes = new Map<number, number | string>();\n\n schedule<T>(command: WorkerCommand, args: unknown[], task: () => Promise<T>): Promise<T> {\n if (UNSCHEDULED_COMMANDS.has(command)) {\n return task();\n }\n if (EXCLUSIVE_COMMANDS.has(command)) {\n if (this.#cursorLanes.size === 0) return this.#runExclusive(task);\n return this.#runExclusive(async () => {\n const result = await task();\n this.#cursorLanes.clear();\n return result;\n });\n }\n if (\n command !== 'scanPage' &&\n command !== 'closeCursor' &&\n !((command === 'commit' || command === 'rollback') && this.#cursorLanes.size > 0)\n ) {\n return this.#runShared(laneFor(command, args), task);\n }\n const request = command === 'scanPage' && isRecord(args[0]) ? args[0] : null;\n const cursorId = request?.cursorId ?? (command === 'closeCursor' ? args[0] : undefined);\n const cursorLane = typeof cursorId === 'number' ? this.#cursorLanes.get(cursorId) : undefined;\n // Explicit cursors share their transaction lane. Implicit cursors own a separate read snapshot.\n const lane =\n cursorLane ??\n (request && typeof request.txId === 'number'\n ? request.txId\n : typeof cursorId === 'number'\n ? `cursor:${cursorId}`\n : laneFor(command, args));\n return this.#runShared(lane, async () => {\n try {\n const result = await task();\n if (request && isRecord(result)) {\n if (typeof cursorId === 'number') this.#cursorLanes.delete(cursorId);\n if (typeof result.cursorId === 'number') {\n this.#cursorLanes.set(result.cursorId, lane ?? `cursor:${result.cursorId}`);\n }\n }\n return result;\n } finally {\n if (command === 'closeCursor' && typeof cursorId === 'number') this.#cursorLanes.delete(cursorId);\n if (command === 'commit' || command === 'rollback') {\n for (const [cursor, ownerLane] of this.#cursorLanes) {\n if (ownerLane === args[0]) this.#cursorLanes.delete(cursor);\n }\n }\n }\n });\n }\n\n #runShared<T>(lane: number | string | null, task: () => Promise<T>): Promise<T> {\n const barrier = this.#barrier;\n const previous = lane === null ? undefined : this.#lanes.get(lane);\n const result = (async () => {\n await barrier;\n if (previous) {\n await previous;\n }\n return task();\n })();\n const settled = result.then(noop, noop);\n this.#inFlight.add(settled);\n if (lane !== null) {\n this.#lanes.set(lane, settled);\n }\n void settled.then(() => {\n this.#inFlight.delete(settled);\n if (lane !== null && this.#lanes.get(lane) === settled) {\n this.#lanes.delete(lane);\n }\n });\n return result;\n }\n\n #runExclusive<T>(task: () => Promise<T>): Promise<T> {\n const previousBarrier = this.#barrier;\n const pending = Array.from(this.#inFlight);\n const result = (async () => {\n await previousBarrier;\n await Promise.all(pending);\n return task();\n })();\n this.#barrier = result.then(noop, noop);\n return result;\n }\n}\n\nconst AUTOCOMMIT_WRITER_LANE = 'autocommit:readwrite';\n\nfunction laneFor(command: WorkerCommand, args: unknown[]): number | string | null {\n if (TRANSACTION_COMMANDS.has(command) && typeof args[0] === 'number') {\n return args[0];\n }\n if (command === 'autocommit' && args[0] === 'readwrite') {\n return AUTOCOMMIT_WRITER_LANE;\n }\n return null;\n}\n\ntype SendResponse = (response: WorkerProtocolResponseMessage, transfer?: Transferable[]) => void;\n\nclass ResponseQueue {\n private queued: Array<{ response: WorkerProtocolResponseMessage; transfer: Transferable[] }> = [];\n private queuedBytes = 0;\n private flushScheduled = false;\n private flushChannel: MessageChannel | null = null;\n private closed = false;\n\n constructor(private readonly scope: WorkerServerScope) {}\n\n enqueue(response: WorkerProtocolResponseMessage, transfer: Transferable[] = [], flushNow = false): void {\n if (this.closed) return;\n const byteLength = payloadBytes(response);\n if (this.queued.length > 0 && this.queuedBytes + byteLength > MAX_WORKER_BATCH_BYTES) {\n this.flush();\n }\n // Posting before the next turn is the snapshot. Deferred replies are frozen first.\n const releaseNow =\n flushNow ||\n this.queued.length + 1 >= MAX_WORKER_BATCH_MESSAGES ||\n this.queuedBytes + byteLength >= MAX_WORKER_BATCH_BYTES;\n if (releaseNow) {\n this.queued.push({ response, transfer });\n this.queuedBytes += byteLength;\n this.flush();\n return;\n }\n const captured = snapshotQueuedPayload(response, transfer);\n this.queued.push({ response: captured.value, transfer: captured.transfer });\n this.queuedBytes += captured.byteLength;\n if (!this.flushScheduled) {\n this.flushScheduled = true;\n queueMicrotask(() => {\n if (this.closed || this.queued.length === 0) {\n this.flushScheduled = false;\n return;\n }\n // A task boundary groups replies from successive transaction-lane\n // microtasks and releases ready replies while other requests remain pending.\n this.flushChannel ??= this.createFlushChannel();\n this.flushChannel.port2.postMessage(null);\n });\n }\n }\n\n close(): void {\n this.closed = true;\n this.queued = [];\n this.queuedBytes = 0;\n this.flushChannel?.port1.close();\n this.flushChannel?.port2.close();\n this.flushChannel = null;\n }\n\n private createFlushChannel(): MessageChannel {\n const channel = new MessageChannel();\n channel.port1.addEventListener('message', () => {\n this.flushScheduled = false;\n this.flush();\n });\n channel.port1.start();\n return channel;\n }\n\n flush(): void {\n const queued = this.queued;\n this.queued = [];\n this.queuedBytes = 0;\n if (this.closed || queued.length === 0) return;\n const response: WorkerProtocolResponseMessage | WorkerProtocolResponseBatchMessage =\n queued.length === 1\n ? queued[0].response\n : {\n type: WORKER_PROTOCOL_RESPONSE_BATCH,\n version: WORKER_PROTOCOL_VERSION,\n responses: queued.map((entry) => entry.response)\n };\n const transfer: Transferable[] = [];\n for (const entry of queued) {\n for (const buffer of entry.transfer) transfer.push(buffer);\n }\n postWorkerResponse(this.scope, response, transfer);\n }\n}\n\nexport function exposeWorkerApi(api: WorkerApi, scope: WorkerServerScope = self): WorkerServerHandle {\n const scheduler = new RequestScheduler();\n const responses = new ResponseQueue(scope);\n const handleMessage = (event: MessageEvent<unknown>) => {\n if (event.origin !== '' && event.origin !== scope.location.origin) {\n return;\n }\n if (isWorkerProtocolRequestBatchMessage(event.data)) {\n let remaining = event.data.requests.length;\n const respond: SendResponse = (response, transfer) => {\n remaining -= 1;\n // Flush fully settled batches in this task. The fallback releases partial replies.\n responses.enqueue(response, transfer, remaining === 0);\n };\n for (const request of event.data.requests) {\n void dispatchWorkerRequest(scope, api, scheduler, request, respond);\n }\n return;\n }\n void dispatchWorkerRequest(scope, api, scheduler, event.data);\n };\n scope.addEventListener('message', handleMessage);\n scope.postMessage({\n type: WORKER_PROTOCOL_READY,\n version: WORKER_PROTOCOL_VERSION,\n batching: 1\n });\n return {\n close() {\n scope.removeEventListener('message', handleMessage);\n responses.close();\n }\n };\n}\n\nasync function dispatchWorkerRequest(\n scope: WorkerServerScope,\n api: WorkerApi,\n scheduler: RequestScheduler,\n data: unknown,\n respond: SendResponse = (response, transfer) => postWorkerResponse(scope, response, transfer)\n): Promise<void> {\n if (!isWorkerProtocolEnvelope(data)) {\n return;\n }\n const id = typeof data.id === 'number' && Number.isSafeInteger(data.id) ? data.id : 0;\n if (!isWorkerProtocolRequestMessage(data)) {\n respond(errorResponse(id, workerProtocolError('WorkerProtocolError', 'invalid worker protocol request')));\n return;\n }\n if (!isWorkerCommand(data.command)) {\n respond(\n errorResponse(\n data.id,\n workerProtocolError('WorkerProtocolError', `unsupported worker command: ${String(data.command)}`)\n )\n );\n return;\n }\n const command = data.command;\n const args = data.args as unknown[];\n try {\n let responseCommand: WorkerCommand = command;\n let invoke: () => Promise<unknown>;\n if (command === 'autocommit') {\n const [mode, inner, innerArgs] = args;\n if (\n (mode !== 'readonly' && mode !== 'readwrite') ||\n !isAutocommitCommand(inner) ||\n !Array.isArray(innerArgs)\n ) {\n throw workerProtocolError('WorkerProtocolError', 'invalid autocommit request');\n }\n assertImplemented(api, inner);\n responseCommand = inner;\n invoke = () => runAutocommit(api, mode, inner, innerArgs);\n } else {\n assertImplemented(api, command);\n invoke = () => invokeCommand(api, command, args);\n }\n const result = await scheduler.schedule(command, args, invoke);\n const responsePayload = prepareWorkerResponsePayload(responseCommand, result as never);\n respond(successResponse(data.id, responsePayload.result), responsePayload.transfer);\n } catch (error) {\n respond(errorResponse(data.id, error));\n }\n}\n\nfunction assertImplemented(api: WorkerApi, command: WorkerCommand): void {\n if (typeof (api[command] as unknown) !== 'function') {\n throw workerProtocolError('WorkerProtocolError', `worker command is not implemented: ${command}`);\n }\n}\n\nfunction invokeCommand(api: WorkerApi, command: WorkerCommand, args: unknown[]): Promise<unknown> {\n const packedResult = dispatchPackedCommand(api, command, args);\n if (packedResult !== null) {\n return packedResult;\n }\n return (api[command] as unknown as (...methodArgs: unknown[]) => Promise<unknown>).apply(\n api,\n decodeWorkerCommandPayload(command, args as never) as unknown[]\n );\n}\n\nasync function runAutocommit(\n api: WorkerApi,\n mode: 'readonly' | 'readwrite',\n command: AutocommitCommand,\n args: unknown[]\n): Promise<unknown> {\n const txId = await api.begin(mode);\n let result: unknown;\n try {\n result = await invokeCommand(api, command, [txId, ...args]);\n } catch (error) {\n try {\n await api.rollback(txId);\n } catch {}\n throw error;\n }\n if (mode === 'readwrite') {\n await api.commit(txId);\n } else {\n await api.rollback(txId);\n }\n return result;\n}\n\nfunction dispatchPackedCommand(api: WorkerApi, command: WorkerCommand, args: unknown[]): Promise<unknown> | null {\n const packedApi = api as PackedWorkerApi;\n if (command === 'getMany' || command === 'deleteMany') {\n const [txId, store, keys] = args;\n if (typeof txId !== 'number' || typeof store !== 'string') {\n return null;\n }\n const packedKeys = packedBinaryListBytes(keys);\n if (packedKeys === null) {\n return null;\n }\n if (command === 'getMany' && typeof packedApi.getManyPacked === 'function') {\n return packedApi.getManyPacked(txId, store, packedKeys);\n }\n if (command === 'deleteMany' && typeof packedApi.deleteManyPacked === 'function') {\n return packedApi.deleteManyPacked(txId, store, packedKeys);\n }\n return null;\n }\n\n if (command === 'putMany') {\n const [txId, store, entries, options] = args;\n if (typeof txId !== 'number' || typeof store !== 'string' || typeof packedApi.putManyPacked !== 'function') {\n return null;\n }\n const packedEntries = packedBinaryListBytes(entries);\n return packedEntries === null ? null : packedApi.putManyPacked(txId, store, packedEntries, options);\n }\n\n if (command === 'applyBatch') {\n const [txId, store, ops] = args;\n if (typeof txId !== 'number' || typeof store !== 'string' || typeof packedApi.applyBatchPacked !== 'function') {\n return null;\n }\n const packedOps = packedBatchOpsBytes(ops);\n return packedOps === null ? null : packedApi.applyBatchPacked(txId, store, packedOps);\n }\n\n return null;\n}\n\nfunction successResponse(id: number, result: unknown): WorkerProtocolSuccessMessage {\n return {\n type: WORKER_PROTOCOL_RESPONSE,\n version: WORKER_PROTOCOL_VERSION,\n id,\n ok: true,\n result\n };\n}\n\nfunction errorResponse(id: number, error: unknown): WorkerProtocolErrorMessage {\n return {\n type: WORKER_PROTOCOL_RESPONSE,\n version: WORKER_PROTOCOL_VERSION,\n id,\n ok: false,\n error: serializeWorkerError(error)\n };\n}\n\nfunction postWorkerResponse(\n scope: WorkerServerScope,\n response: WorkerProtocolResponseMessage | WorkerProtocolResponseBatchMessage,\n transfer: Transferable[] = []\n): void {\n if (transfer.length > 0) {\n try {\n scope.postMessage(response, transfer);\n return;\n } catch {}\n }\n scope.postMessage(response);\n}\n\ninterface ViewGeometry {\n offset: number;\n length: number;\n dataView: boolean;\n}\n\nconst STANDARD_VIEW_CONSTRUCTORS = new Set<object>([\n DataView,\n Uint8Array,\n Uint8ClampedArray,\n Uint16Array,\n Uint32Array,\n Int8Array,\n Int16Array,\n Int32Array,\n Float32Array,\n Float64Array,\n BigInt64Array,\n BigUint64Array\n]);\n\n/**\n * Freeze a queued payload so the later postMessage is its only structured clone.\n * Listed buffers move now. Other ArrayBuffers are copied. SharedArrayBuffers stay shared.\n */\nfunction snapshotQueuedPayload<T>(\n value: T,\n transfer: readonly Transferable[]\n): { value: T; transfer: Transferable[]; byteLength: number } {\n const moving = new Set<ArrayBuffer>();\n for (const item of transfer) {\n if (!(item instanceof ArrayBuffer) || isResizableBuffer(item)) {\n return captureWorkerPayload(value, transfer as Transferable[]);\n }\n moving.add(item);\n }\n const geometries = new Map<ArrayBufferView, ViewGeometry>();\n if (!isPlainPayload(value, geometries, new WeakSet<object>())) {\n return captureWorkerPayload(value, transfer as Transferable[]);\n }\n const relocated = new Map<ArrayBuffer, ArrayBuffer>();\n for (const buffer of moving) {\n relocated.set(buffer, moveArrayBuffer(buffer));\n }\n const owned: ArrayBuffer[] = [];\n const seen = new WeakMap<object, unknown>();\n const cloneValue = (item: unknown): unknown => {\n if (item === null || typeof item !== 'object') {\n return item;\n }\n const existing = seen.get(item);\n if (existing !== undefined) {\n return existing;\n }\n if (typeof SharedArrayBuffer !== 'undefined' && item instanceof SharedArrayBuffer) {\n seen.set(item, item);\n return item;\n }\n if (item instanceof ArrayBuffer) {\n const next = relocated.get(item) ?? item.slice(0);\n seen.set(item, next);\n owned.push(next);\n return next;\n }\n if (ArrayBuffer.isView(item)) {\n const geometry = geometries.get(item);\n if (!geometry) {\n throw workerProtocolError('WorkerProtocolError', 'worker payload could not be queued');\n }\n const buffer = item.buffer;\n const nextBuffer =\n typeof SharedArrayBuffer !== 'undefined' && buffer instanceof SharedArrayBuffer\n ? buffer\n : (cloneValue(buffer) as ArrayBuffer);\n const out = retargetView(item, nextBuffer, geometry);\n seen.set(item, out);\n return out;\n }\n if (Array.isArray(item)) {\n const out = new Array<unknown>(item.length);\n seen.set(item, out);\n for (let index = 0; index < item.length; index += 1) {\n if (index in item) {\n out[index] = cloneValue(item[index]);\n }\n }\n return out;\n }\n const out: Record<string, unknown> = Object.getPrototypeOf(item) === null ? Object.create(null) : {};\n seen.set(item, out);\n const record = item as Record<string, unknown>;\n for (const key in record) {\n if (Object.prototype.hasOwnProperty.call(record, key)) {\n out[key] = cloneValue(record[key]);\n }\n }\n return out;\n };\n const cloned = cloneValue(value) as T;\n return { value: cloned, transfer: owned, byteLength: payloadBytes(cloned) };\n}\n\nfunction payloadBytes(value: unknown): number {\n let byteLength = 0;\n const seen = new WeakSet<object>();\n const visit = (item: unknown): void => {\n if (!Number.isFinite(byteLength)) return;\n if (typeof item === 'string') {\n byteLength += 8 + item.length * 2;\n return;\n }\n if (item === null || typeof item !== 'object') {\n byteLength += 8;\n return;\n }\n if (seen.has(item)) {\n return;\n }\n seen.add(item);\n byteLength += 8;\n if (item instanceof ArrayBuffer) {\n byteLength += item.byteLength;\n } else if (typeof SharedArrayBuffer !== 'undefined' && item instanceof SharedArrayBuffer) {\n byteLength += item.byteLength;\n } else if (ArrayBuffer.isView(item)) {\n visit(item.buffer);\n } else if (Array.isArray(item)) {\n if (Object.getPrototypeOf(item) !== Array.prototype || hasExtraKeys(item)) {\n byteLength = Number.POSITIVE_INFINITY;\n return;\n }\n for (let index = 0; index < item.length; index += 1) {\n const descriptor = Object.getOwnPropertyDescriptor(item, String(index));\n if (descriptor && !('value' in descriptor)) {\n byteLength = Number.POSITIVE_INFINITY;\n return;\n }\n visit(descriptor?.value);\n }\n } else if (item instanceof Map) {\n for (const [key, child] of item) {\n visit(key);\n visit(child);\n }\n } else if (item instanceof Set) {\n for (const child of item) {\n visit(child);\n }\n } else {\n const record = item as Record<string, unknown>;\n for (const key in record) {\n if (Object.prototype.hasOwnProperty.call(record, key)) {\n const descriptor = Object.getOwnPropertyDescriptor(record, key);\n // Let postMessage evaluate accessors and preserve special data keys.\n if (key === '__proto__' || !descriptor || !('value' in descriptor)) {\n byteLength = Number.POSITIVE_INFINITY;\n return;\n }\n byteLength += 8 + key.length * 2;\n visit(descriptor.value);\n }\n }\n }\n };\n visit(value);\n return byteLength;\n}\n\nfunction isPlainPayload(\n value: unknown,\n geometries: Map<ArrayBufferView, ViewGeometry>,\n seen: WeakSet<object>\n): boolean {\n if (typeof value === 'function' || typeof value === 'symbol') {\n return false;\n }\n if (value === null || typeof value !== 'object') {\n return true;\n }\n if (seen.has(value)) {\n return true;\n }\n seen.add(value);\n if (typeof SharedArrayBuffer !== 'undefined' && value instanceof SharedArrayBuffer) {\n return !isResizableBuffer(value);\n }\n if (value instanceof ArrayBuffer) {\n return !isResizableBuffer(value);\n }\n if (ArrayBuffer.isView(value)) {\n if (!isStandardView(value)) {\n return false;\n }\n const buffer = value.buffer;\n if (typeof SharedArrayBuffer !== 'undefined' && buffer instanceof SharedArrayBuffer) {\n if (isResizableBuffer(buffer)) {\n return false;\n }\n geometries.set(value, viewGeometry(value));\n return true;\n }\n if (!(buffer instanceof ArrayBuffer) || isResizableBuffer(buffer)) {\n return false;\n }\n geometries.set(value, viewGeometry(value));\n return true;\n }\n if (value instanceof Map || value instanceof Set || value instanceof Date || value instanceof RegExp) {\n return false;\n }\n if (Array.isArray(value)) {\n if (hasExtraKeys(value) || hasEnumerableSymbols(value)) {\n return false;\n }\n for (const child of value) {\n if (!isPlainPayload(child, geometries, seen)) {\n return false;\n }\n }\n return true;\n }\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) {\n return false;\n }\n if (hasEnumerableSymbols(value)) {\n return false;\n }\n const record = value as Record<string, unknown>;\n for (const key in record) {\n if (Object.prototype.hasOwnProperty.call(record, key) && !isPlainPayload(record[key], geometries, seen)) {\n return false;\n }\n }\n return true;\n}\n\nfunction hasExtraKeys(value: readonly unknown[]): boolean {\n const record: object = value;\n for (const key in record) {\n if (!Object.prototype.hasOwnProperty.call(value, key)) {\n continue;\n }\n const index = Number(key);\n if (!Number.isInteger(index) || index < 0 || index >= value.length || String(index) !== key) {\n return true;\n }\n }\n return false;\n}\n\nfunction hasEnumerableSymbols(value: object): boolean {\n for (const symbol of Object.getOwnPropertySymbols(value)) {\n if (Object.prototype.propertyIsEnumerable.call(value, symbol)) {\n return true;\n }\n }\n return false;\n}\n\nfunction isStandardView(view: ArrayBufferView): boolean {\n return STANDARD_VIEW_CONSTRUCTORS.has(view.constructor);\n}\n\nfunction viewGeometry(view: ArrayBufferView): ViewGeometry {\n if (view instanceof DataView) {\n return { offset: view.byteOffset, length: view.byteLength, dataView: true };\n }\n return { offset: view.byteOffset, length: (view as Uint8Array).length, dataView: false };\n}\n\nfunction retargetView(view: ArrayBufferView, buffer: ArrayBufferLike, geometry: ViewGeometry): ArrayBufferView {\n if (geometry.dataView) {\n return new DataView(buffer, geometry.offset, geometry.length);\n }\n const Typed = view.constructor as new (\n buffer: ArrayBufferLike,\n byteOffset: number,\n length: number\n ) => ArrayBufferView;\n return new Typed(buffer, geometry.offset, geometry.length);\n}\n\nfunction moveArrayBuffer(buffer: ArrayBuffer): ArrayBuffer {\n const movable = buffer as ArrayBuffer & { transfer?: () => ArrayBuffer };\n if (typeof movable.transfer === 'function') {\n return movable.transfer();\n }\n return structuredClone(buffer, { transfer: [buffer] });\n}\n\nfunction isResizableBuffer(buffer: ArrayBuffer | SharedArrayBuffer): boolean {\n return (buffer as { resizable?: boolean }).resizable === true;\n}\n","import type { Range } from './types';\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst jsonDecoder = new TextDecoder('utf-8', { fatal: true });\nconst TYPE_NULL = 0x10;\nconst TYPE_FALSE = 0x20;\nconst TYPE_TRUE = 0x21;\nconst TYPE_NUMBER = 0x30;\nconst TYPE_STRING = 0x40;\nconst TYPE_BYTES = 0x50;\nconst COMPOUND_ESCAPE = 0x00;\nconst COMPOUND_ESCAPE_CONT = 0xff;\nconst COMPOUND_TERM = 0x00;\nconst F64_MASK = BigInt('0xffffffffffffffff');\nconst sortableNumberBytes = new Uint8Array(9);\nconst sortableNumberView = new DataView(sortableNumberBytes.buffer);\nexport type CompoundKeyPart = string | number | boolean | null | Uint8Array;\nexport type IndexKeyPrimitive = CompoundKeyPart;\nexport function utf8Encode(value: string): Uint8Array {\n return encoder.encode(value);\n}\nexport function utf8Decode(bytes: Uint8Array): string {\n return decoder.decode(bytes);\n}\nexport function jsonEncode(value: unknown): Uint8Array {\n const serialized = JSON.stringify(value) as string | undefined;\n if (serialized === undefined) {\n throw new TypeError('value has no JSON representation');\n }\n return utf8Encode(serialized);\n}\nexport function jsonDecode<T>(bytes: Uint8Array): T {\n return JSON.parse(jsonDecoder.decode(bytes)) as T;\n}\nexport function u64Key(value: bigint | number): Uint8Array {\n if (typeof value === 'number' && (!Number.isSafeInteger(value) || value < 0)) {\n throw new RangeError('u64Key number inputs must be safe non-negative integers; use bigint for larger values');\n }\n const asBigInt = typeof value === 'bigint' ? value : BigInt(value);\n if (asBigInt < 0n) {\n throw new RangeError('u64Key only accepts non-negative values');\n }\n if (asBigInt > F64_MASK) {\n throw new RangeError('u64Key value exceeds the unsigned 64-bit range');\n }\n const buf = new ArrayBuffer(8);\n const view = new DataView(buf);\n view.setBigUint64(0, asBigInt, false);\n return new Uint8Array(buf);\n}\nfunction isCompoundKeyPartList(\n value: CompoundKeyPart | ReadonlyArray<CompoundKeyPart>\n): value is ReadonlyArray<CompoundKeyPart> {\n return Array.isArray(value);\n}\nexport function indexKey(value: CompoundKeyPart | ReadonlyArray<CompoundKeyPart>): Uint8Array {\n if (isCompoundKeyPartList(value)) {\n return encodeCompoundKeyList(value);\n }\n return encodeCompoundKeyPart(value);\n}\nexport function compoundKey(...parts: CompoundKeyPart[]): Uint8Array {\n return encodeCompoundKeyList(parts);\n}\nexport function encodeIndexScalar(value: IndexKeyPrimitive): Uint8Array {\n return encodeCompoundKeyPart(value);\n}\nexport function encodeCompoundKeyParts(parts: ReadonlyArray<Uint8Array>): Uint8Array {\n return encodeCompoundBytes(parts);\n}\nexport function splitCompoundKey(key: Uint8Array): Uint8Array[] {\n const parts: Uint8Array[] = [];\n let index = 0;\n while (index < key.length) {\n const start = index;\n let length = 0;\n let closed = false;\n for (; index < key.length; index += 1) {\n const byte = key[index];\n if (byte !== COMPOUND_ESCAPE) {\n length += 1;\n continue;\n }\n const next = key[index + 1];\n if (next === COMPOUND_ESCAPE_CONT) {\n length += 1;\n index += 1;\n continue;\n }\n if (next === COMPOUND_TERM) {\n index += 2;\n closed = true;\n break;\n }\n throw new TypeError('invalid compound key encoding');\n }\n if (!closed) {\n throw new TypeError('compound key terminated unexpectedly');\n }\n const part = new Uint8Array(length);\n let offset = 0;\n for (let cursor = start; cursor < index - 2; cursor += 1) {\n const byte = key[cursor];\n if (byte !== COMPOUND_ESCAPE) {\n part[offset] = byte;\n offset += 1;\n continue;\n }\n part[offset] = COMPOUND_ESCAPE;\n offset += 1;\n cursor += 1;\n }\n parts.push(part);\n }\n return parts;\n}\nexport function prefixSuccessor(prefix: Uint8Array): Uint8Array | null {\n let end = prefix.length;\n while (end > 0 && prefix[end - 1] === 0xff) {\n end -= 1;\n }\n if (end === 0) {\n return null;\n }\n const out = new Uint8Array(end);\n out.set(end === prefix.length ? prefix : prefix.subarray(0, end));\n out[end - 1] += 1;\n return out;\n}\nexport function prefixRange(prefix: Uint8Array): Range {\n const upper = prefixSuccessor(prefix);\n return upper ? { gte: prefix, lt: upper } : { gte: prefix };\n}\nexport function compoundKeyRange(...parts: CompoundKeyPart[]): Range {\n return prefixRange(compoundKey(...parts));\n}\nfunction encodeCompoundKeyPart(value: CompoundKeyPart): Uint8Array {\n if (value === null) {\n return Uint8Array.of(TYPE_NULL);\n }\n if (typeof value === 'boolean') {\n return Uint8Array.of(value ? TYPE_TRUE : TYPE_FALSE);\n }\n if (typeof value === 'number') {\n return encodeSortableNumber(value);\n }\n if (typeof value === 'string') {\n return encodeStringKey(value);\n }\n if (value instanceof Uint8Array) {\n const out = new Uint8Array(1 + value.length);\n out[0] = TYPE_BYTES;\n out.set(value, 1);\n return out;\n }\n throw new TypeError('compound key parts must be string, number, boolean, null, or Uint8Array');\n}\nfunction encodeCompoundKeyList(parts: ReadonlyArray<CompoundKeyPart>): Uint8Array {\n let length = 0;\n for (let index = 0; index < parts.length; index += 1) {\n length += compoundPartEncodedLength(parts[index]);\n }\n const out = new Uint8Array(length);\n let offset = 0;\n for (let index = 0; index < parts.length; index += 1) {\n offset = writeCompoundPart(out, offset, parts[index]);\n }\n return out;\n}\nfunction compoundPartEncodedLength(value: CompoundKeyPart): number {\n if (value === null || typeof value === 'boolean') {\n return 3;\n }\n if (typeof value === 'number') {\n writeSortableNumber(sortableNumberView, value);\n return escapedByteLength(sortableNumberBytes) + 2;\n }\n if (typeof value === 'string') {\n return 1 + walkUtf8(value, null, 0, true) + 2;\n }\n if (value instanceof Uint8Array) {\n return 1 + escapedByteLength(value) + 2;\n }\n throw new TypeError('compound key parts must be string, number, boolean, null, or Uint8Array');\n}\nfunction writeCompoundPart(out: Uint8Array, offset: number, value: CompoundKeyPart): number {\n if (value === null) {\n out[offset] = TYPE_NULL;\n return writeTerminator(out, offset + 1);\n }\n if (typeof value === 'boolean') {\n out[offset] = value ? TYPE_TRUE : TYPE_FALSE;\n return writeTerminator(out, offset + 1);\n }\n if (typeof value === 'number') {\n writeSortableNumber(sortableNumberView, value);\n return writeTerminator(out, writeEscapedBytes(out, offset, sortableNumberBytes));\n }\n if (typeof value === 'string') {\n out[offset] = TYPE_STRING;\n return writeTerminator(out, walkUtf8(value, out, offset + 1, true));\n }\n if (value instanceof Uint8Array) {\n out[offset] = TYPE_BYTES;\n return writeTerminator(out, writeEscapedBytes(out, offset + 1, value));\n }\n throw new TypeError('compound key parts must be string, number, boolean, null, or Uint8Array');\n}\nfunction encodeCompoundBytes(parts: ReadonlyArray<Uint8Array>): Uint8Array {\n let length = 0;\n for (let index = 0; index < parts.length; index += 1) {\n length += escapedByteLength(parts[index]) + 2;\n }\n const out = new Uint8Array(length);\n let offset = 0;\n for (let index = 0; index < parts.length; index += 1) {\n offset = writeTerminator(out, writeEscapedBytes(out, offset, parts[index]));\n }\n return out;\n}\nfunction escapedByteLength(bytes: Uint8Array): number {\n let extra = 0;\n for (let index = 0; index < bytes.length; index += 1) {\n if (bytes[index] === COMPOUND_ESCAPE) {\n extra += 1;\n }\n }\n return bytes.length + extra;\n}\nfunction writeEscapedBytes(out: Uint8Array, offset: number, bytes: Uint8Array): number {\n for (let index = 0; index < bytes.length; index += 1) {\n const byte = bytes[index];\n if (byte === COMPOUND_ESCAPE) {\n out[offset] = COMPOUND_ESCAPE;\n out[offset + 1] = COMPOUND_ESCAPE_CONT;\n offset += 2;\n } else {\n out[offset] = byte;\n offset += 1;\n }\n }\n return offset;\n}\nfunction writeTerminator(out: Uint8Array, offset: number): number {\n out[offset] = COMPOUND_TERM;\n out[offset + 1] = COMPOUND_TERM;\n return offset + 2;\n}\nfunction encodeStringKey(value: string): Uint8Array {\n const length = walkUtf8(value, null, 0, false);\n const out = new Uint8Array(1 + length);\n out[0] = TYPE_STRING;\n walkUtf8(value, out, 1, false);\n return out;\n}\n// Reject lone surrogates so distinct keys cannot collapse to U+FFFD.\nfunction walkUtf8(value: string, out: Uint8Array | null, offset: number, escapeNul: boolean): number {\n for (let index = 0; index < value.length; index += 1) {\n const code = value.charCodeAt(index);\n if (code <= 0x7f) {\n if (escapeNul && code === 0) {\n if (out !== null) {\n out[offset] = COMPOUND_ESCAPE;\n out[offset + 1] = COMPOUND_ESCAPE_CONT;\n }\n offset += 2;\n } else {\n if (out !== null) {\n out[offset] = code;\n }\n offset += 1;\n }\n continue;\n }\n if (code <= 0x7ff) {\n if (out !== null) {\n out[offset] = 0xc0 | (code >> 6);\n out[offset + 1] = 0x80 | (code & 0x3f);\n }\n offset += 2;\n continue;\n }\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (next >= 0xdc00 && next <= 0xdfff) {\n const point = ((code - 0xd800) << 10) + (next - 0xdc00) + 0x10000;\n if (out !== null) {\n out[offset] = 0xf0 | (point >> 18);\n out[offset + 1] = 0x80 | ((point >> 12) & 0x3f);\n out[offset + 2] = 0x80 | ((point >> 6) & 0x3f);\n out[offset + 3] = 0x80 | (point & 0x3f);\n }\n offset += 4;\n index += 1;\n continue;\n }\n }\n if (code >= 0xd800 && code <= 0xdfff) {\n throw new TypeError('compound key string parts must contain valid Unicode scalar values');\n }\n if (out !== null) {\n out[offset] = 0xe0 | (code >> 12);\n out[offset + 1] = 0x80 | ((code >> 6) & 0x3f);\n out[offset + 2] = 0x80 | (code & 0x3f);\n }\n offset += 3;\n }\n return offset;\n}\nfunction encodeSortableNumber(value: number): Uint8Array {\n const bytes = new Uint8Array(9);\n writeSortableNumber(new DataView(bytes.buffer), value);\n return bytes;\n}\nfunction writeSortableNumber(view: DataView, value: number): void {\n if (!Number.isFinite(value)) {\n throw new TypeError('compound key number parts must be finite');\n }\n const normalized = Object.is(value, -0) ? 0 : value;\n view.setUint8(0, TYPE_NUMBER);\n view.setFloat64(1, normalized, false);\n let bits = view.getBigUint64(1, false);\n bits = (bits & (1n << 63n)) !== 0n ? ~bits & F64_MASK : bits ^ (1n << 63n);\n view.setBigUint64(1, bits, false);\n}\n","const BLOCK_SIZE = 65536;\nconst HASH_BITS = 14;\nconst HASH_SIZE = 1 << HASH_BITS;\nconst MAX_LENGTH = 0xffff_ffff;\nconst MATCH_TABLE = new Uint32Array(HASH_SIZE);\n\nfunction corrupt(message: string): Error {\n const error = new Error(`invalid Snappy block: ${message}`);\n error.name = 'CorruptionError';\n return error;\n}\n\nfunction word(bytes: Uint8Array, offset: number): number {\n return (bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24)) >>> 0;\n}\n\nfunction hash(value: number, bits: number): number {\n return Math.imul(value, 0x9e3779b1) >>> (32 - bits);\n}\n\nexport function encodeSnappy(input: Uint8Array): Uint8Array {\n if (input.byteLength > MAX_LENGTH) {\n throw new RangeError('Snappy input exceeds the 32-bit length limit');\n }\n const output = new Uint8Array(input.byteLength + Math.ceil(input.byteLength / 6) + 32);\n let written = 0;\n let remainingLength = input.byteLength;\n while (remainingLength >= 128) {\n output[written++] = (remainingLength & 0x7f) | 0x80;\n remainingLength = Math.floor(remainingLength / 128);\n }\n output[written++] = remainingLength;\n\n const literal = (start: number, end: number): void => {\n if (start === end) {\n return;\n }\n let length = end - start - 1;\n if (length < 60) {\n output[written++] = length << 2;\n } else {\n const lengthBytes = length <= 0xff ? 1 : length <= 0xffff ? 2 : length <= 0xffffff ? 3 : 4;\n output[written++] = (59 + lengthBytes) << 2;\n for (let index = 0; index < lengthBytes; index += 1) {\n output[written++] = length & 0xff;\n length >>>= 8;\n }\n }\n output.set(input.subarray(start, end), written);\n written += end - start;\n };\n const copy = (offset: number, length: number): void => {\n while (length > 0) {\n const count = Math.min(length, 64);\n if (count >= 4 && count <= 11 && offset < 2048) {\n output[written++] = 1 | ((count - 4) << 2) | ((offset >>> 8) << 5);\n output[written++] = offset & 0xff;\n } else {\n output[written++] = 2 | ((count - 1) << 2);\n output[written++] = offset & 0xff;\n output[written++] = offset >>> 8;\n }\n length -= count;\n }\n };\n\n let hashBits = 8;\n while (1 << hashBits < Math.min(input.byteLength, HASH_SIZE)) {\n hashBits += 1;\n }\n const tableSize = 1 << hashBits;\n // Encoding is synchronous. Calls can reuse this bounded scratch table.\n const table = MATCH_TABLE;\n for (let blockStart = 0; blockStart < input.byteLength; blockStart += BLOCK_SIZE) {\n const blockEnd = Math.min(blockStart + BLOCK_SIZE, input.byteLength);\n table.fill(0, 0, tableSize);\n let position = blockStart;\n let literalStart = blockStart;\n let misses = 0;\n while (position + 4 <= blockEnd) {\n const current = word(input, position);\n const slot = hash(current, hashBits);\n const previous = table[slot];\n table[slot] = position - blockStart + 1;\n const candidate = blockStart + previous - 1;\n if (previous === 0 || current !== word(input, candidate)) {\n misses += 1;\n position += 1 + Math.min(misses >>> 5, 64);\n continue;\n }\n literal(literalStart, position);\n const matchStart = position;\n position += 4;\n while (position < blockEnd && input[position] === input[candidate + position - matchStart]) {\n position += 1;\n }\n copy(matchStart - candidate, position - matchStart);\n literalStart = position;\n misses = 0;\n if (position + 4 <= blockEnd) {\n table[hash(word(input, position - 1), hashBits)] = position - blockStart;\n }\n }\n literal(literalStart, blockEnd);\n }\n return output.subarray(0, written);\n}\n\nexport function decodeSnappy(input: Uint8Array, maxOutputBytes: number, expectedOutputBytes?: number): Uint8Array {\n if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0 || maxOutputBytes > MAX_LENGTH) {\n throw new RangeError('invalid Snappy output limit');\n }\n let read = 0;\n let length = 0;\n for (let index = 0; ; index += 1) {\n if (read >= input.byteLength || index === 5) {\n throw corrupt('truncated or invalid length');\n }\n const byte = input[read++];\n if (index === 4 && byte > 0x0f) {\n throw corrupt('length exceeds 32 bits');\n }\n length += (byte & 0x7f) * 2 ** (index * 7);\n if (byte < 128) {\n break;\n }\n }\n if (length > maxOutputBytes) {\n throw corrupt(`output exceeds ${maxOutputBytes} byte limit`);\n }\n if (expectedOutputBytes !== undefined && length !== expectedOutputBytes) {\n throw corrupt(`length mismatch: expected ${expectedOutputBytes} bytes, got ${length}`);\n }\n const output = new Uint8Array(length);\n let written = 0;\n while (read < input.byteLength) {\n const tag = input[read++];\n const kind = tag & 3;\n if (kind === 0) {\n let count = tag >>> 2;\n if (count < 60) {\n count += 1;\n } else {\n const lengthBytes = count - 59;\n if (lengthBytes > input.byteLength - read) {\n throw corrupt('truncated literal length');\n }\n count = 1;\n for (let index = 0; index < lengthBytes; index += 1) {\n count += input[read++] * 2 ** (index * 8);\n }\n }\n if (count > input.byteLength - read || count > length - written) {\n throw corrupt('literal exceeds input or output');\n }\n output.set(input.subarray(read, read + count), written);\n read += count;\n written += count;\n continue;\n }\n const offsetBytes = kind === 1 ? 1 : kind === 2 ? 2 : 4;\n if (offsetBytes > input.byteLength - read) {\n throw corrupt('truncated copy offset');\n }\n const count = kind === 1 ? 4 + ((tag >>> 2) & 7) : 1 + (tag >>> 2);\n let offset = kind === 1 ? (tag & 0xe0) << 3 : 0;\n for (let index = 0; index < offsetBytes; index += 1) {\n offset += input[read++] * 2 ** (index * 8);\n }\n if (offset === 0 || offset > written || count > length - written) {\n throw corrupt('copy exceeds output or has an invalid offset');\n }\n let copied = 0;\n // Overlapping copies repeat the decoded prefix. Each step doubles it.\n while (copied < count) {\n const chunk = Math.min(offset + copied, count - copied);\n output.copyWithin(written + copied, written - offset, written - offset + chunk);\n copied += chunk;\n }\n written += count;\n }\n if (written !== length) {\n throw corrupt(`length mismatch: expected ${length} bytes, got ${written}`);\n }\n return output;\n}\n","import { utf8Encode } from './codec';\nimport { decodeSnappy, encodeSnappy } from './snappy';\nimport type { CompressionKind, SnapshotCompressionKind } from './types';\nexport type CompressionOption = CompressionKind | false;\nconst STORE_RECORD_MAGIC = utf8Encode('BDBZVAL1');\nconst SNAPSHOT_EXPORT_MAGIC = utf8Encode('BDBZSNP1');\nconst ENVELOPE_VERSION = 1;\nconst ENVELOPE_HEADER_SIZE = 18;\nconst COMPRESSION_TAG_NONE = 0;\nconst COMPRESSION_TAG_GZIP = 1;\nconst COMPRESSION_TAG_DEFLATE = 2;\nconst COMPRESSION_TAG_SNAPPY = 3;\nconst STORE_FLAG_COMPRESSION_SHIFT = 2;\nconst STORE_FLAG_COMPRESSION_MASK = 0b11 << STORE_FLAG_COMPRESSION_SHIFT;\nexport const STORE_VALUE_COMPRESSION_THRESHOLD = 1024;\nexport const STORE_VALUE_MIN_COMPRESSION_SAVING_PERCENT = 10;\nexport const STORE_VALUE_COMPRESSION_POLICY_VERSION = 2;\nexport const STORE_VALUE_COMPRESSION_PREFLIGHT_MIN_BYTES = 64 * 1024;\nexport const STORE_VALUE_COMPRESSION_PREFLIGHT_WINDOW_BYTES = 1024;\nexport const STORE_VALUE_COMPRESSION_PREFLIGHT_WINDOW_COUNT = 3;\nexport const STORE_VALUE_COMPRESSION_ENVELOPE_BYTES = ENVELOPE_HEADER_SIZE;\nconst MAX_DECOMPRESSED_STORE_VALUE_BYTES = 8 * 1024 * 1024;\nconst MAX_DECOMPRESSED_SNAPSHOT_BYTES = 256 * 1024 * 1024;\nconst CRC32_TABLE = (() => {\n const table = new Uint32Array(8 * 256);\n for (let index = 0; index < 256; index += 1) {\n let crc = index;\n for (let bit = 0; bit < 8; bit += 1) {\n if ((crc & 1) !== 0) {\n crc = (crc >>> 1) ^ 0xedb88320;\n } else {\n crc >>>= 1;\n }\n }\n table[index] = crc >>> 0;\n }\n for (let index = 0; index < 256; index += 1) {\n let crc = table[index];\n for (let slice = 1; slice < 8; slice += 1) {\n crc = (crc >>> 8) ^ table[crc & 0xff];\n table[slice * 256 + index] = crc >>> 0;\n }\n }\n return table;\n})();\ntype EnvelopeHeader = {\n version: number;\n kindTag: number;\n rawLength: number;\n payloadChecksum: number;\n};\nexport type PreparedStoreValueRecord = {\n readonly byteLength: number;\n readonly payload: Uint8Array;\n readonly rawLength: number;\n readonly kindTag: number | null;\n};\nfunction namedError(name: string, message: string): Error {\n const error = new Error(message);\n error.name = name;\n return error;\n}\nfunction compressionTag(kind: CompressionOption): number {\n switch (kind) {\n case false:\n return COMPRESSION_TAG_NONE;\n case 'gzip':\n return COMPRESSION_TAG_GZIP;\n case 'deflate':\n return COMPRESSION_TAG_DEFLATE;\n case 'snappy':\n return COMPRESSION_TAG_SNAPPY;\n default:\n throw namedError('InternalError', `unsupported compression kind: ${String(kind)}`);\n }\n}\nfunction compressionKindFromTag(tag: number): CompressionOption {\n switch (tag) {\n case COMPRESSION_TAG_NONE:\n return false;\n case COMPRESSION_TAG_GZIP:\n return 'gzip';\n case COMPRESSION_TAG_DEFLATE:\n return 'deflate';\n case COMPRESSION_TAG_SNAPPY:\n return 'snappy';\n default:\n throw namedError('CorruptionError', `invalid compression tag: ${tag}`);\n }\n}\nfunction compressionRuntimeUnavailable(): Error {\n return namedError(\n 'UnsupportedPlatformError',\n 'CompressionStream and DecompressionStream are required for moyodb compression'\n );\n}\nfunction ensureCompressionRuntime(): void {\n if (typeof CompressionStream !== 'function' || typeof DecompressionStream !== 'function') {\n throw compressionRuntimeUnavailable();\n }\n}\nfunction crc32(bytes: Uint8Array): number {\n let crc = 0xffffffff;\n let offset = 0;\n const blockEnd = bytes.byteLength - 7;\n // Table slices apply eight IEEE CRC32 byte updates in one step.\n for (; offset < blockEnd; offset += 8) {\n const first =\n crc ^ bytes[offset] ^ (bytes[offset + 1] << 8) ^ (bytes[offset + 2] << 16) ^ (bytes[offset + 3] << 24);\n crc =\n CRC32_TABLE[1792 + (first & 0xff)] ^\n CRC32_TABLE[1536 + ((first >>> 8) & 0xff)] ^\n CRC32_TABLE[1280 + ((first >>> 16) & 0xff)] ^\n CRC32_TABLE[1024 + (first >>> 24)] ^\n CRC32_TABLE[768 + bytes[offset + 4]] ^\n CRC32_TABLE[512 + bytes[offset + 5]] ^\n CRC32_TABLE[256 + bytes[offset + 6]] ^\n CRC32_TABLE[bytes[offset + 7]];\n }\n for (; offset < bytes.byteLength; offset += 1) {\n crc = (crc >>> 8) ^ CRC32_TABLE[(crc ^ bytes[offset]) & 0xff];\n }\n return (crc ^ 0xffffffff) >>> 0;\n}\nfunction buildEnvelope(magic: Uint8Array, kindTag: number, rawLength: number, payload: Uint8Array): Uint8Array {\n const out = new Uint8Array(ENVELOPE_HEADER_SIZE + payload.byteLength);\n writeEnvelope(out, 0, magic, kindTag, rawLength, payload);\n return out;\n}\nfunction writeEnvelope(\n out: Uint8Array,\n offset: number,\n magic: Uint8Array,\n kindTag: number,\n rawLength: number,\n payload: Uint8Array\n): void {\n // A borrowed payload can overlap the destination header.\n const checksum = crc32(payload);\n out.set(payload, offset + ENVELOPE_HEADER_SIZE);\n out.set(magic, offset);\n out[offset + 8] = ENVELOPE_VERSION;\n out[offset + 9] = kindTag;\n const view = new DataView(out.buffer, out.byteOffset + offset, ENVELOPE_HEADER_SIZE);\n view.setUint32(10, rawLength, true);\n view.setUint32(14, checksum, true);\n}\nfunction writeEnvelopeHeader(\n out: Uint8Array,\n magic: Uint8Array,\n kindTag: number,\n rawLength: number,\n payload: Uint8Array\n): void {\n const checksum = crc32(payload);\n out.set(magic);\n out[8] = ENVELOPE_VERSION;\n out[9] = kindTag;\n const view = new DataView(out.buffer, out.byteOffset, ENVELOPE_HEADER_SIZE);\n view.setUint32(10, rawLength, true);\n view.setUint32(14, checksum, true);\n}\nfunction envelopeFromChunks(\n magic: Uint8Array,\n kindTag: number,\n rawLength: number,\n chunks: Uint8Array[],\n totalBytes: number\n): Uint8Array {\n const out = new Uint8Array(ENVELOPE_HEADER_SIZE + totalBytes);\n let offset = ENVELOPE_HEADER_SIZE;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n writeEnvelopeHeader(out, magic, kindTag, rawLength, out.subarray(ENVELOPE_HEADER_SIZE));\n return out;\n}\nfunction compressionIsProfitable(rawLength: number, compressedLength: number): boolean {\n return (\n (compressedLength + ENVELOPE_HEADER_SIZE) * 100 <=\n rawLength * (100 - STORE_VALUE_MIN_COMPRESSION_SAVING_PERCENT)\n );\n}\nfunction snappyPreflightIsProfitable(value: Uint8Array): boolean {\n if (value.byteLength < STORE_VALUE_COMPRESSION_PREFLIGHT_MIN_BYTES) {\n return true;\n }\n let compressedLength = 0;\n for (let index = 0; index < STORE_VALUE_COMPRESSION_PREFLIGHT_WINDOW_COUNT; index += 1) {\n const offset = Math.floor(\n ((value.byteLength - STORE_VALUE_COMPRESSION_PREFLIGHT_WINDOW_BYTES) * index) /\n (STORE_VALUE_COMPRESSION_PREFLIGHT_WINDOW_COUNT - 1)\n );\n compressedLength += encodeSnappy(\n value.subarray(offset, offset + STORE_VALUE_COMPRESSION_PREFLIGHT_WINDOW_BYTES)\n ).byteLength;\n }\n return compressionIsProfitable(\n STORE_VALUE_COMPRESSION_PREFLIGHT_WINDOW_BYTES * STORE_VALUE_COMPRESSION_PREFLIGHT_WINDOW_COUNT,\n compressedLength\n );\n}\nfunction validateStoreValueLength(value: Uint8Array): void {\n if (value.byteLength > MAX_DECOMPRESSED_STORE_VALUE_BYTES) {\n throw namedError(\n 'ValueTooLargeError',\n `value has ${value.byteLength} bytes, exceeding the ${MAX_DECOMPRESSED_STORE_VALUE_BYTES} byte limit`\n );\n }\n}\n// Raw payloads borrow value until the prepared record is written.\nexport function prepareFastStoreValueRecord(\n value: Uint8Array,\n compression: 'snappy' | false\n): PreparedStoreValueRecord {\n if (compression === false) {\n return { payload: value, rawLength: value.byteLength, byteLength: value.byteLength, kindTag: null };\n }\n validateStoreValueLength(value);\n let payload = value;\n let kindTag = COMPRESSION_TAG_NONE;\n if (value.byteLength >= STORE_VALUE_COMPRESSION_THRESHOLD && snappyPreflightIsProfitable(value)) {\n const compressed = encodeSnappy(value);\n if (compressionIsProfitable(value.byteLength, compressed.byteLength)) {\n payload = compressed;\n kindTag = COMPRESSION_TAG_SNAPPY;\n }\n }\n return { payload, rawLength: value.byteLength, byteLength: ENVELOPE_HEADER_SIZE + payload.byteLength, kindTag };\n}\nexport function writePreparedStoreValueRecord(\n record: PreparedStoreValueRecord,\n target: Uint8Array,\n offset: number\n): number {\n if (!Number.isSafeInteger(offset) || offset < 0 || record.byteLength > target.byteLength - offset) {\n throw namedError('InternalError', 'prepared store value exceeds its destination');\n }\n if (record.kindTag === null) {\n target.set(record.payload, offset);\n } else {\n writeEnvelope(target, offset, STORE_RECORD_MAGIC, record.kindTag, record.rawLength, record.payload);\n }\n return offset + record.byteLength;\n}\n// Copy before the stream can suspend so caller mutations cannot change its input.\nfunction copyBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return copy;\n}\nfunction byteStream(bytes: Uint8Array<ArrayBuffer>): ReadableStream<Uint8Array<ArrayBuffer>> {\n let offset = 0;\n return new ReadableStream({\n pull(controller) {\n if (offset < bytes.byteLength) {\n const end = Math.min(offset + 64 * 1024, bytes.byteLength);\n // The stream owns the input; chunk views need no further copies.\n controller.enqueue(bytes.subarray(offset, end));\n offset = end;\n }\n if (offset === bytes.byteLength) {\n controller.close();\n }\n }\n });\n}\nfunction readEnvelopeHeader(magic: Uint8Array, bytes: Uint8Array, strict = true): EnvelopeHeader | null {\n if (bytes.byteLength < magic.byteLength) {\n return null;\n }\n for (let index = 0; index < magic.byteLength; index += 1) {\n if (bytes[index] !== magic[index]) {\n return null;\n }\n }\n if (bytes.byteLength < ENVELOPE_HEADER_SIZE) {\n if (strict) {\n throw namedError(\n 'CorruptionError',\n `truncated compression envelope: expected at least ${ENVELOPE_HEADER_SIZE} bytes, got ${bytes.byteLength}`\n );\n }\n return null;\n }\n const view = new DataView(bytes.buffer, bytes.byteOffset, ENVELOPE_HEADER_SIZE);\n return {\n version: bytes[8],\n kindTag: bytes[9],\n rawLength: view.getUint32(10, true),\n payloadChecksum: view.getUint32(14, true)\n };\n}\n// `stopAtBytes` abandons a result that will not be smaller than the raw payload.\n// The caller then seals the snapshot it already owns instead of copying those bytes again.\nasync function collectCompressed(\n input: Uint8Array<ArrayBuffer>,\n kind: SnapshotCompressionKind,\n stopAtBytes?: number\n): Promise<{\n chunks: Uint8Array[];\n totalBytes: number;\n} | null> {\n ensureCompressionRuntime();\n let stream: ReadableStream<Uint8Array>;\n try {\n stream = byteStream(input).pipeThrough(new CompressionStream(kind));\n } catch {\n throw compressionRuntimeUnavailable();\n }\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n let stopped = false;\n try {\n for (let next = await reader.read(); !next.done; next = await reader.read()) {\n const part = next.value;\n totalBytes += part.byteLength;\n if (stopAtBytes !== undefined && totalBytes >= stopAtBytes) {\n stopped = true;\n await reader.cancel('compressed output is not smaller than the raw payload');\n break;\n }\n chunks.push(part);\n }\n } catch (error) {\n if (!stopped) {\n throw namedError('InternalError', `failed to compress bytes with ${kind}: ${String(error)}`);\n }\n } finally {\n try {\n reader.releaseLock();\n } catch {\n // cancel() may already have released this reader.\n }\n }\n if (stopped || (stopAtBytes !== undefined && totalBytes >= stopAtBytes)) {\n return null;\n }\n return { chunks, totalBytes };\n}\nasync function decompressBytes(\n data: Uint8Array,\n kind: CompressionKind,\n label: string,\n maxOutputBytes?: number\n): Promise<Uint8Array> {\n if (kind === 'snappy') {\n return decodeSnappy(data, maxOutputBytes ?? MAX_DECOMPRESSED_STORE_VALUE_BYTES, maxOutputBytes);\n }\n ensureCompressionRuntime();\n let stream: ReadableStream<Uint8Array>;\n try {\n stream = byteStream(copyBytes(data)).pipeThrough(new DecompressionStream(kind));\n } catch {\n throw compressionRuntimeUnavailable();\n }\n try {\n return await readBoundedStream(stream, label, maxOutputBytes);\n } catch (error) {\n throw namedError('CorruptionError', `failed to decompress ${label}: ${String(error)}`);\n }\n}\n\nasync function readBoundedStream(\n stream: ReadableStream<Uint8Array>,\n label: string,\n maxOutputBytes?: number\n): Promise<Uint8Array> {\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n try {\n for (let next = await reader.read(); !next.done; next = await reader.read()) {\n const value = next.value;\n totalBytes += value.byteLength;\n if (maxOutputBytes !== undefined && totalBytes > maxOutputBytes) {\n await reader.cancel(`decompressed ${label} exceeded ${maxOutputBytes} bytes`);\n throw namedError('CorruptionError', `decompressed ${label} exceeds ${maxOutputBytes} byte limit`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n if (chunks.length === 1) {\n return chunks[0];\n }\n const out = new Uint8Array(totalBytes);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n}\nexport function compressionFromStoreFlags(flags: number): CompressionOption {\n const encoded = (flags & STORE_FLAG_COMPRESSION_MASK) >>> STORE_FLAG_COMPRESSION_SHIFT;\n switch (encoded) {\n case 0:\n return false;\n case 1:\n return 'gzip';\n case 2:\n return 'deflate';\n case 3:\n return 'snappy';\n default:\n throw namedError('CorruptionError', `invalid store compression flags: ${encoded}`);\n }\n}\nexport async function encodeStoreValueRecord(value: Uint8Array, compression: CompressionOption): Promise<Uint8Array> {\n validateStoreValueLength(value);\n if (compression === false) {\n return value;\n }\n if (compression === 'snappy') {\n const record = prepareFastStoreValueRecord(value, compression);\n const output = new Uint8Array(record.byteLength);\n writePreparedStoreValueRecord(record, output, 0);\n return output;\n }\n if (value.byteLength < STORE_VALUE_COMPRESSION_THRESHOLD) {\n return buildEnvelope(STORE_RECORD_MAGIC, COMPRESSION_TAG_NONE, value.byteLength, value);\n }\n const stored = new Uint8Array(ENVELOPE_HEADER_SIZE + value.byteLength);\n const payload = stored.subarray(ENVELOPE_HEADER_SIZE);\n payload.set(value);\n const compressed = await collectCompressed(payload, compression, payload.byteLength);\n if (compressed === null || !compressionIsProfitable(payload.byteLength, compressed.totalBytes)) {\n writeEnvelopeHeader(stored, STORE_RECORD_MAGIC, COMPRESSION_TAG_NONE, payload.byteLength, payload);\n return stored;\n }\n return envelopeFromChunks(\n STORE_RECORD_MAGIC,\n compressionTag(compression),\n payload.byteLength,\n compressed.chunks,\n compressed.totalBytes\n );\n}\nexport async function decodeStoreValueRecord(\n value: Uint8Array,\n options: {\n strict: boolean;\n }\n): Promise<Uint8Array> {\n const header = readEnvelopeHeader(STORE_RECORD_MAGIC, value, options.strict);\n if (!header) {\n return value;\n }\n if (header.version !== ENVELOPE_VERSION) {\n if (options.strict) {\n throw namedError('CorruptionError', `unsupported value record version: ${header.version}`);\n }\n return value;\n }\n let compression: CompressionOption;\n try {\n compression = compressionKindFromTag(header.kindTag);\n } catch (error) {\n if (options.strict) {\n throw error;\n }\n return value;\n }\n const payload = value.subarray(ENVELOPE_HEADER_SIZE);\n if (crc32(payload) !== header.payloadChecksum) {\n if (options.strict) {\n throw namedError('CorruptionError', 'value record checksum mismatch');\n }\n return value;\n }\n if (compression === false) {\n if (payload.byteLength !== header.rawLength) {\n if (options.strict) {\n throw namedError(\n 'CorruptionError',\n `value record length mismatch: expected ${header.rawLength} bytes, got ${payload.byteLength}`\n );\n }\n return value;\n }\n return payload.slice();\n }\n if (header.rawLength > MAX_DECOMPRESSED_STORE_VALUE_BYTES) {\n throw namedError(\n 'CorruptionError',\n `compressed value advertises ${header.rawLength} decompressed bytes, exceeding the ${MAX_DECOMPRESSED_STORE_VALUE_BYTES} byte limit`\n );\n }\n const decompressed = await decompressBytes(payload, compression, `value record (${compression})`, header.rawLength);\n if (decompressed.byteLength !== header.rawLength) {\n throw namedError(\n 'CorruptionError',\n `decompressed value length mismatch: expected ${header.rawLength} bytes, got ${decompressed.byteLength}`\n );\n }\n return decompressed;\n}\nexport async function wrapSnapshotWithCompression(\n snapshot: Uint8Array,\n compression: SnapshotCompressionKind | false\n): Promise<Uint8Array> {\n if (compression === false) {\n return snapshot;\n }\n if (!['gzip', 'deflate'].includes(compression)) {\n throw namedError('InternalError', `unsupported snapshot compression kind: ${String(compression)}`);\n }\n if (snapshot.byteLength > MAX_DECOMPRESSED_SNAPSHOT_BYTES) {\n throw namedError(\n 'SerializationError',\n `snapshot has ${snapshot.byteLength} bytes, exceeding the ${MAX_DECOMPRESSED_SNAPSHOT_BYTES} byte limit`\n );\n }\n const input = copyBytes(snapshot);\n const compressed = await collectCompressed(input, compression);\n if (compressed === null) {\n throw namedError('InternalError', `failed to compress bytes with ${compression}`);\n }\n return envelopeFromChunks(\n SNAPSHOT_EXPORT_MAGIC,\n compressionTag(compression),\n input.byteLength,\n compressed.chunks,\n compressed.totalBytes\n );\n}\nexport async function unwrapSnapshotCompression(snapshot: Uint8Array): Promise<Uint8Array> {\n const header = readEnvelopeHeader(SNAPSHOT_EXPORT_MAGIC, snapshot);\n if (!header) {\n return snapshot;\n }\n if (header.version !== ENVELOPE_VERSION) {\n throw namedError('CorruptionError', `unsupported snapshot compression version: ${header.version}`);\n }\n const compression = compressionKindFromTag(header.kindTag);\n if (compression === false) {\n throw namedError('CorruptionError', 'snapshot compression envelope cannot store kind \"none\"');\n }\n if (compression === 'snappy') {\n throw namedError('CorruptionError', `invalid snapshot compression tag: ${header.kindTag}`);\n }\n const payload = snapshot.subarray(ENVELOPE_HEADER_SIZE);\n if (crc32(payload) !== header.payloadChecksum) {\n throw namedError('CorruptionError', 'snapshot compression checksum mismatch');\n }\n if (header.rawLength > MAX_DECOMPRESSED_SNAPSHOT_BYTES) {\n throw namedError(\n 'CorruptionError',\n `compressed snapshot advertises ${header.rawLength} decompressed bytes, exceeding the ${MAX_DECOMPRESSED_SNAPSHOT_BYTES} byte limit`\n );\n }\n const decompressed = await decompressBytes(\n payload,\n compression,\n `snapshot export (${compression})`,\n header.rawLength\n );\n if (decompressed.byteLength !== header.rawLength) {\n throw namedError(\n 'CorruptionError',\n `decompressed snapshot length mismatch: expected ${header.rawLength} bytes, got ${decompressed.byteLength}`\n );\n }\n return decompressed;\n}\n","export class MoyoDbError extends Error {\n constructor(name: string, message: string) {\n super(message);\n this.name = name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\nexport class UnsupportedPlatformError extends MoyoDbError {\n constructor(message: string) {\n super('UnsupportedPlatformError', message);\n }\n}\nexport class DatabaseBusyError extends MoyoDbError {\n constructor(message: string) {\n super('DatabaseBusyError', message);\n }\n}\nexport class CorruptionError extends MoyoDbError {\n constructor(message: string) {\n super('CorruptionError', message);\n }\n}\nexport class StoreExistsError extends MoyoDbError {\n constructor(message: string) {\n super('StoreExistsError', message);\n }\n}\nexport class StoreNotFoundError extends MoyoDbError {\n constructor(message: string) {\n super('StoreNotFoundError', message);\n }\n}\nexport class IndexNotFoundError extends MoyoDbError {\n constructor(message: string) {\n super('IndexNotFoundError', message);\n }\n}\nexport class ConstraintError extends MoyoDbError {\n constructor(message: string) {\n super('ConstraintError', message);\n }\n}\nexport class UniqueIndexConstraintError extends ConstraintError {\n constructor(message: string) {\n super(message);\n this.name = 'UniqueIndexConstraintError';\n }\n}\nexport class WriteTransactionAlreadyOpenError extends MoyoDbError {\n constructor(message = 'write transaction already open') {\n super('WriteTransactionAlreadyOpenError', message);\n }\n}\nexport class TransactionConflictError extends MoyoDbError {\n constructor(message = 'transaction snapshot is stale; start a new transaction') {\n super('TransactionConflictError', message);\n }\n}\nexport class ReadonlyTransactionError extends MoyoDbError {\n constructor(message = 'readonly transaction cannot perform this operation') {\n super('ReadonlyTransactionError', message);\n }\n}\nexport class TransactionClosedError extends MoyoDbError {\n constructor(message = 'transaction is already closed') {\n super('TransactionClosedError', message);\n }\n}\nexport class DatabaseClosedError extends MoyoDbError {\n constructor(message = 'database handle is closed') {\n super('DatabaseClosedError', message);\n }\n}\nexport class ValueTooLargeError extends MoyoDbError {\n constructor(message: string) {\n super('ValueTooLargeError', message);\n }\n}\nexport class KeyTooLargeError extends MoyoDbError {\n constructor(message: string) {\n super('KeyTooLargeError', message);\n }\n}\nexport class StoreNameTooLongError extends MoyoDbError {\n constructor(message: string) {\n super('StoreNameTooLongError', message);\n }\n}\nexport class ReservedStoreNameError extends MoyoDbError {\n constructor(message: string) {\n super('ReservedStoreNameError', message);\n }\n}\nexport class InvalidRangeError extends MoyoDbError {\n constructor(message: string) {\n super('InvalidRangeError', message);\n }\n}\nexport class StorageError extends MoyoDbError {\n constructor(message: string) {\n super('StorageError', message);\n }\n}\nexport class SerializationError extends MoyoDbError {\n constructor(message: string) {\n super('SerializationError', message);\n }\n}\nexport class InjectedFailureError extends MoyoDbError {\n constructor(message: string) {\n super('InjectedFailureError', message);\n }\n}\nexport class ChangeFeedCompactedError extends MoyoDbError {\n constructor(message: string) {\n super('ChangeFeedCompactedError', message);\n }\n}\n/**\n * The engine state could not be trusted, or automatic recovery failed.\n * A failed commit may already be durable. The worker attempts recovery before\n * a new transaction and after a failed commit. Recovery discards all open transactions.\n */\nexport class RecoveryRequiredError extends MoyoDbError {\n constructor(message: string) {\n super('RecoveryRequiredError', message);\n }\n}\nexport class InternalError extends MoyoDbError {\n constructor(message: string) {\n super('InternalError', message);\n }\n}\nexport class InvalidOpenOptionsError extends MoyoDbError {\n constructor(message: string) {\n super('InvalidOpenOptionsError', message);\n }\n}\nexport class VersionError extends MoyoDbError {\n constructor(message: string) {\n super('VersionError', message);\n }\n}\ntype ErrorPayload = {\n code?: string;\n name?: string;\n message?: string;\n};\ntype ErrorConstructor = new (message: string) => Error;\nconst ERROR_CONSTRUCTORS = {\n UnsupportedPlatformError,\n DatabaseBusyError,\n CorruptionError,\n StoreExistsError,\n StoreNotFoundError,\n IndexNotFoundError,\n ConstraintError,\n UniqueIndexConstraintError,\n WriteTransactionAlreadyOpenError,\n TransactionConflictError,\n ReadonlyTransactionError,\n TransactionClosedError,\n DatabaseClosedError,\n ValueTooLargeError,\n KeyTooLargeError,\n StoreNameTooLongError,\n ReservedStoreNameError,\n InvalidRangeError,\n StorageError,\n SerializationError,\n InjectedFailureError,\n ChangeFeedCompactedError,\n RecoveryRequiredError,\n InternalError,\n InvalidOpenOptionsError,\n VersionError\n} satisfies Record<string, ErrorConstructor>;\n\nfunction instantiateError(code: string, message: string): Error {\n if (Object.prototype.hasOwnProperty.call(ERROR_CONSTRUCTORS, code)) {\n const ErrorConstructor = ERROR_CONSTRUCTORS[code as keyof typeof ERROR_CONSTRUCTORS];\n return new ErrorConstructor(message);\n }\n const err = new Error(message);\n err.name = code;\n return err;\n}\n\nexport function normalizeError(error: unknown): Error {\n if (error instanceof MoyoDbError) {\n return error;\n }\n if (error instanceof Error) {\n if (error.name === 'Error') {\n return error;\n }\n return instantiateError(error.name, error.message);\n }\n const payload = error as ErrorPayload | undefined;\n const code = payload?.code ?? payload?.name ?? 'Error';\n const message = payload?.message ?? String(error);\n return instantiateError(code, message);\n}\n","import { InvalidOpenOptionsError, InvalidRangeError, ReservedStoreNameError, SerializationError } from './errors';\nimport { compareStringsByCodeUnit } from './internal';\nimport { encodeCompoundKeyParts, encodeIndexScalar, utf8Encode } from './codec';\nimport type { IndexDef, Range } from './types';\nconst fatalDecoder = new TextDecoder('utf-8', { fatal: true });\nconst MISSING = Symbol('moyodb.indexing.missing');\nconst FNV64_OFFSET = BigInt('0xcbf29ce484222325');\nconst FNV64_PRIME = BigInt('0x100000001b3');\nconst FNV64_MASK = BigInt('0xffffffffffffffff');\n// Persisted store names use this legacy namespace. Renaming requires a migration.\nconst INTERNAL_STORE_PREFIX = '__browserdb:';\nconst INTERNAL_INDEX_STORE_PREFIX = '__browserdb:index:';\nexport const INDEX_METADATA_STORE = '__browserdb:indexes';\nexport interface NormalizedIndexDef {\n store: string;\n name: string;\n keyPath: string[];\n compound: boolean;\n unique: boolean;\n internalStore: string;\n}\nexport interface DecodedIndexEntryKey {\n logicalKey: Uint8Array;\n primaryKey: Uint8Array;\n}\nexport function isInternalStoreName(name: string): boolean {\n return name.startsWith(INTERNAL_STORE_PREFIX);\n}\nexport function assertPublicStoreName(name: string): void {\n if (isInternalStoreName(name)) {\n throw new ReservedStoreNameError(`reserved store name: ${name}`);\n }\n}\nexport function normalizeIndexDefinitions(value: unknown): NormalizedIndexDef[] {\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n throw new InvalidOpenOptionsError('indexes must be an array');\n }\n const normalized: NormalizedIndexDef[] = [];\n const identities = new Set<string>();\n const internalStores = new Map<string, string>();\n for (const entry of value) {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {\n throw new InvalidOpenOptionsError('each index definition must be an object');\n }\n const { store, name, keyPath, unique } = entry as {\n store?: unknown;\n name?: unknown;\n keyPath?: unknown;\n unique?: unknown;\n };\n if (typeof store !== 'string' || store.length === 0) {\n throw new InvalidOpenOptionsError('index store must be a non-empty string');\n }\n if (typeof name !== 'string' || name.length === 0) {\n throw new InvalidOpenOptionsError('index name must be a non-empty string');\n }\n assertPublicStoreName(store);\n const keyPathInfo = normalizeIndexKeyPath(keyPath);\n if (unique !== undefined && typeof unique !== 'boolean') {\n throw new InvalidOpenOptionsError('index unique must be a boolean');\n }\n const def: NormalizedIndexDef = {\n store,\n name,\n keyPath: keyPathInfo.paths,\n compound: keyPathInfo.compound,\n unique: unique ?? false,\n internalStore: makeInternalIndexStoreName(store, name)\n };\n const identity = indexDefinitionIdentity(def.store, def.name);\n if (identities.has(identity)) {\n throw new InvalidOpenOptionsError(`duplicate index definition ${def.store}.${def.name}`);\n }\n identities.add(identity);\n const mappedIdentity = internalStores.get(def.internalStore);\n if (mappedIdentity && mappedIdentity !== identity) {\n throw new InvalidOpenOptionsError(\n `index definitions ${mappedIdentity} and ${identity} map to the same internal store ${def.internalStore}`\n );\n }\n internalStores.set(def.internalStore, identity);\n normalized.push(def);\n }\n normalized.sort(compareNormalizedIndexDefinitions);\n return normalized;\n}\nexport function compareNormalizedIndexDefinitions(left: NormalizedIndexDef, right: NormalizedIndexDef): number {\n const storeCompare = compareStringsByCodeUnit(left.store, right.store);\n if (storeCompare !== 0) {\n return storeCompare;\n }\n const nameCompare = compareStringsByCodeUnit(left.name, right.name);\n if (nameCompare !== 0) {\n return nameCompare;\n }\n const uniqueCompare = Number(left.unique) - Number(right.unique);\n if (uniqueCompare !== 0) {\n return uniqueCompare;\n }\n return compareStringsByCodeUnit(serializeIndexKeyPath(left), serializeIndexKeyPath(right));\n}\nexport function indexDefinitionIdentity(store: string, name: string): string {\n return JSON.stringify([store, name]);\n}\nexport function findIndexDefinition(\n defs: ReadonlyArray<NormalizedIndexDef>,\n store: string,\n name: string\n): NormalizedIndexDef | null {\n return defs.find((def) => def.store === store && def.name === name) ?? null;\n}\nexport function indexesForStore(defs: ReadonlyArray<NormalizedIndexDef>, store: string): NormalizedIndexDef[] {\n return defs.filter((def) => def.store === store);\n}\nexport function encodeIndexMetadataKey(store: string, name: string): Uint8Array {\n return encodeCompoundKeyParts([utf8Encode(store), utf8Encode(name)]);\n}\nexport function encodeIndexMetadataValue(def: NormalizedIndexDef): Uint8Array {\n return utf8Encode(JSON.stringify(toPublicIndexDefinition(def)));\n}\nexport function decodeIndexMetadataValue(bytes: Uint8Array): NormalizedIndexDef {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fatalDecoder.decode(bytes));\n const [def] = normalizeIndexDefinitions([parsed]);\n return def;\n } catch (error) {\n throw new SerializationError(`invalid persisted index metadata: ${String(error)}`);\n }\n}\nexport function encodeIndexEntryKey(logicalIndexKey: Uint8Array, primaryKey: Uint8Array): Uint8Array {\n const out = new Uint8Array(compoundEncodedLength(logicalIndexKey) + compoundEncodedLength(primaryKey));\n const primaryAt = writeCompoundPart(out, 0, logicalIndexKey);\n writeCompoundPart(out, primaryAt, primaryKey);\n return out;\n}\nexport function decodeIndexEntryKey(bytes: Uint8Array): DecodedIndexEntryKey {\n try {\n return decodeTwoPartIndexKey(bytes);\n } catch (error) {\n if (error instanceof SerializationError) {\n throw error;\n }\n throw new SerializationError(`invalid index entry key encoding: ${String(error)}`);\n }\n}\nexport function indexKeyExactRange(logicalIndexKey: Uint8Array): Range {\n const gte = encodeCompoundPrefix(logicalIndexKey);\n const lt = advanceEncodedPrefix(gte.slice());\n return lt ? { gte, lt } : { gte };\n}\n/** WASM `usize` is 32-bit, so this is the largest limit the engine can accept. */\nexport const MAX_ENGINE_SCAN_LIMIT = 0xffff_ffff;\n\n/**\n * Bounds and limits follow the engine `RangeSpec` contract.\n * Conflicting bounds and a limit the engine cannot store are `InvalidRangeError`.\n */\nexport function assertValidScanRange(range: Range = {}): void {\n if (range.gt !== undefined && range.gte !== undefined) {\n throw new InvalidRangeError('range cannot include both gt and gte');\n }\n if (range.lt !== undefined && range.lte !== undefined) {\n throw new InvalidRangeError('range cannot include both lt and lte');\n }\n if (\n range.limit !== undefined &&\n (!Number.isSafeInteger(range.limit) || range.limit < 0 || range.limit > MAX_ENGINE_SCAN_LIMIT)\n ) {\n throw new InvalidRangeError('limit must be an integer between 0 and 4294967295');\n }\n}\n\nexport function indexRangeToPhysicalRange(range: Range = {}): Range {\n assertValidScanRange(range);\n const physical: Range = {};\n if (range.reverse !== undefined) {\n physical.reverse = range.reverse;\n }\n if (range.limit !== undefined) {\n physical.limit = range.limit;\n }\n if (range.gte) {\n physical.gte = encodeCompoundPrefix(range.gte);\n }\n if (range.gt) {\n const lower = advanceEncodedPrefix(encodeCompoundPrefix(range.gt));\n if (lower) {\n physical.gte = lower;\n }\n }\n if (range.lt) {\n physical.lt = encodeCompoundPrefix(range.lt);\n }\n if (range.lte) {\n const upper = advanceEncodedPrefix(encodeCompoundPrefix(range.lte));\n if (upper) {\n physical.lt = upper;\n }\n }\n return physical;\n}\nexport function extractLogicalIndexKey(def: NormalizedIndexDef, valueBytes: Uint8Array): Uint8Array | null {\n return extractLogicalIndexKeyFromDocument(def, decodeIndexedDocument(valueBytes));\n}\n/**\n * Reuse the decoded document only within one synchronous mutation plan.\n * Lazy decoding preserves validation order. Do not retain the extractor\n * across operations or an await.\n */\nexport function createIndexKeyExtractor(valueBytes: Uint8Array): (def: NormalizedIndexDef) => Uint8Array | null {\n let decoded = false;\n let documentValue: unknown;\n return (def) => {\n if (!decoded) {\n documentValue = decodeIndexedDocument(valueBytes);\n decoded = true;\n }\n return extractLogicalIndexKeyFromDocument(def, documentValue);\n };\n}\nexport function extractLogicalIndexKeyFromDocument(def: NormalizedIndexDef, documentValue: unknown): Uint8Array | null {\n if (def.compound) {\n const parts: Uint8Array[] = [];\n for (const keyPath of def.keyPath) {\n const resolved = resolveKeyPath(documentValue, keyPath);\n if (resolved === MISSING) {\n return null;\n }\n parts.push(encodeDocumentIndexValue(resolved));\n }\n return encodeCompoundKeyParts(parts);\n }\n const resolved = resolveKeyPath(documentValue, def.keyPath[0]);\n if (resolved === MISSING) {\n return null;\n }\n return encodeDocumentIndexValue(resolved);\n}\nexport function serializeNormalizedIndexDefinitions(defs: ReadonlyArray<NormalizedIndexDef>): string {\n return JSON.stringify(toPublicIndexDefinitions(defs));\n}\nexport function cloneNormalizedIndexDefinitions(defs: ReadonlyArray<NormalizedIndexDef>): NormalizedIndexDef[] {\n return defs.map((def) => ({\n store: def.store,\n name: def.name,\n keyPath: [...def.keyPath],\n compound: def.compound,\n unique: def.unique,\n internalStore: def.internalStore\n }));\n}\nexport function toPublicIndexDefinitions(defs: ReadonlyArray<NormalizedIndexDef>): IndexDef[] {\n return defs.map(toPublicIndexDefinition);\n}\nfunction toPublicIndexDefinition(def: NormalizedIndexDef): IndexDef {\n return {\n store: def.store,\n name: def.name,\n keyPath: def.compound ? [...def.keyPath] : def.keyPath[0],\n unique: def.unique\n };\n}\nfunction normalizeIndexKeyPath(value: unknown): {\n paths: string[];\n compound: boolean;\n} {\n if (typeof value === 'string') {\n validateSingleKeyPath(value);\n return { paths: [value], compound: false };\n }\n if (\n !Array.isArray(value) ||\n value.length === 0 ||\n !value.every((item): item is string => typeof item === 'string')\n ) {\n throw new InvalidOpenOptionsError('index keyPath must be a non-empty string or non-empty string[]');\n }\n for (const path of value) {\n validateSingleKeyPath(path);\n }\n return { paths: [...value], compound: true };\n}\nfunction validateSingleKeyPath(value: string): void {\n if (value.length === 0) {\n throw new InvalidOpenOptionsError('index keyPath strings must be non-empty');\n }\n if (value.startsWith('.') || value.endsWith('.') || value.includes('..')) {\n throw new InvalidOpenOptionsError(`invalid index keyPath: ${value}`);\n }\n}\nfunction serializeIndexKeyPath(def: NormalizedIndexDef): string {\n return def.compound ? `[${def.keyPath.join(',')}]` : def.keyPath[0];\n}\nfunction makeInternalIndexStoreName(store: string, name: string): string {\n const storeToken = base64Url(utf8Encode(store));\n const nameToken = base64Url(utf8Encode(name));\n const candidate = `${INTERNAL_INDEX_STORE_PREFIX}${storeToken}:${nameToken}`;\n if (utf8Encode(candidate).length <= 255) {\n return candidate;\n }\n // Preserve the persisted hash format. Normalization rejects distinct\n // identities that map to the same internal store, including separator collisions.\n const payload = utf8Encode(`${store}\\u0000${name}`);\n return `${INTERNAL_INDEX_STORE_PREFIX}h:${fnv1a64Hex(payload)}`;\n}\nfunction base64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/u, '');\n}\nfunction fnv1a64Hex(bytes: Uint8Array): string {\n let hash = FNV64_OFFSET;\n for (const byte of bytes) {\n hash ^= BigInt(byte);\n hash = (hash * FNV64_PRIME) & FNV64_MASK;\n }\n return hash.toString(16).padStart(16, '0');\n}\nexport function decodeIndexedDocument(bytes: Uint8Array): unknown {\n try {\n return JSON.parse(fatalDecoder.decode(bytes));\n } catch (error) {\n throw new SerializationError(`indexed values must be valid UTF-8 JSON: ${String(error)}`);\n }\n}\nfunction resolveKeyPath(root: unknown, keyPath: string): unknown {\n let current: unknown = root;\n for (const segment of keyPath.split('.')) {\n // JSON strings and numbers have no nested fields. Boxing them would index\n // UTF-16 code units and string length, which JSON.stringify does not preserve.\n if (current === null || typeof current !== 'object') {\n return MISSING;\n }\n if (!Object.hasOwn(current, segment)) {\n return MISSING;\n }\n current = Reflect.get(current, segment);\n }\n return current;\n}\nfunction encodeDocumentIndexValue(value: unknown): Uint8Array {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n value instanceof Uint8Array\n ) {\n try {\n return encodeIndexScalar(value);\n } catch (error) {\n if (error instanceof TypeError) {\n throw new SerializationError(`invalid indexed keyPath value: ${error.message}`);\n }\n throw error;\n }\n }\n throw new SerializationError(\n `indexed keyPath values must resolve to string, number, boolean, null, or Uint8Array; got ${describeValue(value)}`\n );\n}\nfunction describeValue(value: unknown): string {\n if (Array.isArray(value)) {\n return 'array';\n }\n return typeof value;\n}\nconst INDEX_KEY_ESCAPE = 0x00;\nconst INDEX_KEY_ESCAPE_CONT = 0xff;\nconst INDEX_KEY_TERM = 0x00;\nfunction compoundEncodedLength(part: Uint8Array): number {\n let zeros = 0;\n const length = part.length;\n for (let index = 0; index < length; index += 1) {\n if (part[index] === INDEX_KEY_ESCAPE) {\n zeros += 1;\n }\n }\n return length + zeros + 2;\n}\nfunction writeCompoundPart(out: Uint8Array, offset: number, part: Uint8Array): number {\n const length = part.length;\n for (let index = 0; index < length; index += 1) {\n const byte = part[index];\n if (byte === INDEX_KEY_ESCAPE) {\n out[offset] = INDEX_KEY_ESCAPE;\n out[offset + 1] = INDEX_KEY_ESCAPE_CONT;\n offset += 2;\n } else {\n out[offset] = byte;\n offset += 1;\n }\n }\n out[offset] = INDEX_KEY_TERM;\n out[offset + 1] = INDEX_KEY_TERM;\n return offset + 2;\n}\nfunction encodeCompoundPrefix(part: Uint8Array): Uint8Array {\n const out = new Uint8Array(compoundEncodedLength(part));\n writeCompoundPart(out, 0, part);\n return out;\n}\n// In-place prefixSuccessor. Compound prefixes end in 0x00, so the final byte\n// advances inside this buffer instead of allocating a second copy.\nfunction advanceEncodedPrefix(prefix: Uint8Array): Uint8Array | null {\n for (let index = prefix.length - 1; index >= 0; index -= 1) {\n if (prefix[index] !== 0xff) {\n prefix[index] += 1;\n return index + 1 === prefix.length ? prefix : prefix.subarray(0, index + 1);\n }\n }\n return null;\n}\n// Count both parts, then fill exact buffers. splitCompoundKey would also build a\n// temporary number list for every byte of every scanned index row.\nfunction decodeTwoPartIndexKey(bytes: Uint8Array): DecodedIndexEntryKey {\n const cursor = { unescaped: 0, end: 0 };\n if (!readCompoundPart(bytes, 0, cursor)) {\n throw new SerializationError('invalid index entry key encoding');\n }\n const logicalLength = cursor.unescaped;\n const primaryStart = cursor.end;\n if (!readCompoundPart(bytes, primaryStart, cursor)) {\n throw new SerializationError('invalid index entry key encoding');\n }\n const primaryLength = cursor.unescaped;\n let end = cursor.end;\n if (end !== bytes.length) {\n for (;;) {\n if (!readCompoundPart(bytes, end, cursor)) {\n throw new SerializationError('invalid index entry key encoding');\n }\n if (cursor.end <= end) {\n throw new TypeError('invalid compound key encoding');\n }\n end = cursor.end;\n if (end === bytes.length) {\n throw new SerializationError('invalid index entry key encoding');\n }\n }\n }\n const logicalKey = new Uint8Array(logicalLength);\n const primaryKey = new Uint8Array(primaryLength);\n copyUnescapedPart(bytes, 0, logicalKey);\n copyUnescapedPart(bytes, primaryStart, primaryKey);\n return { logicalKey, primaryKey };\n}\nfunction readCompoundPart(bytes: Uint8Array, start: number, cursor: { unescaped: number; end: number }): boolean {\n if (start >= bytes.length) {\n return false;\n }\n let unescaped = 0;\n for (let index = start; index < bytes.length; index += 1) {\n const byte = bytes[index];\n if (byte !== INDEX_KEY_ESCAPE) {\n unescaped += 1;\n continue;\n }\n const next = bytes[index + 1];\n if (next === INDEX_KEY_ESCAPE_CONT) {\n unescaped += 1;\n index += 1;\n continue;\n }\n if (next === INDEX_KEY_TERM) {\n cursor.unescaped = unescaped;\n cursor.end = index + 2;\n return true;\n }\n throw new TypeError('invalid compound key encoding');\n }\n throw new TypeError('compound key terminated unexpectedly');\n}\nfunction copyUnescapedPart(bytes: Uint8Array, start: number, out: Uint8Array): void {\n const needed = out.length;\n let offset = 0;\n for (let index = start; offset < needed; index += 1) {\n const byte = bytes[index];\n if (byte !== INDEX_KEY_ESCAPE) {\n out[offset] = byte;\n offset += 1;\n continue;\n }\n if (bytes[index + 1] === INDEX_KEY_ESCAPE_CONT) {\n out[offset] = INDEX_KEY_ESCAPE;\n offset += 1;\n index += 1;\n continue;\n }\n return;\n }\n}\n","export { exposeWorkerApi } from './worker-server';\nimport {\n packedOptionalValues,\n packedScanRows,\n unpackPackedBatchOpKeys,\n unpackPackedBatchOps,\n unpackPackedBinaryList,\n unpackPackedBinaryPairKeys,\n unpackPackedOptionalValues,\n unpackPackedScanRows,\n type PackedBatchOpKey,\n type PackedOptionalValuesV1\n} from './worker-protocol';\nimport type { CommitAppliedEvent, StoreChangeSet } from './change-events';\nimport {\n compressionFromStoreFlags,\n decodeStoreValueRecord,\n encodeStoreValueRecord,\n prepareFastStoreValueRecord,\n writePreparedStoreValueRecord,\n wrapSnapshotWithCompression,\n unwrapSnapshotCompression,\n type CompressionOption,\n type PreparedStoreValueRecord\n} from './compression';\nimport { utf8Encode } from './codec';\nimport { clampTimerDelayMs, isRecord } from './internal';\nimport {\n INDEX_METADATA_STORE,\n cloneNormalizedIndexDefinitions,\n compareNormalizedIndexDefinitions,\n createIndexKeyExtractor,\n decodeIndexEntryKey,\n decodeIndexMetadataValue,\n decodeIndexedDocument,\n encodeIndexEntryKey,\n encodeIndexMetadataKey,\n encodeIndexMetadataValue,\n extractLogicalIndexKey,\n extractLogicalIndexKeyFromDocument,\n findIndexDefinition,\n assertValidScanRange,\n indexKeyExactRange,\n indexRangeToPhysicalRange,\n isInternalStoreName,\n normalizeIndexDefinitions,\n toPublicIndexDefinitions,\n type DecodedIndexEntryKey,\n type NormalizedIndexDef\n} from './indexing';\nimport type {\n AutocommitCommand,\n IndexScanPage,\n WorkerApi,\n WorkerOpenRequest,\n WorkerScanPage,\n WorkerScanPageRequest\n} from './worker-api';\nimport type {\n BatchOp,\n ChangeFeed,\n ChangeFeedOptions,\n ChangeFeedSettings,\n CompactionResult,\n CreateStoreOptions,\n DbChange,\n DbStats,\n DebugFailpoint,\n EngineHealth,\n ExportSnapshotOptions,\n IndexDef,\n PutOptions,\n Range,\n ScanItem,\n StorageInfo,\n TxMode\n} from './types';\ntype WasmBatchOutcome =\n | {\n kind: 'put';\n baselineExists: boolean;\n }\n | {\n kind: 'delete';\n deleted: boolean;\n };\ntype IndexedPutOp = { store: string; kind: 'delete' | 'put'; key: Uint8Array };\ntype PreparedPutValue = PreparedStoreValueRecord | Uint8Array;\ntype NativeValueState = {\n live: boolean;\n expired: boolean;\n revisionKnown: boolean;\n revisionEpoch: bigint;\n revisionOrdinal: bigint;\n expiresAt: bigint;\n maxValueBytes: number;\n};\ntype WasmChangeRecord = Omit<ChangeFeed['changes'][number], 'txId'> & {\n txId: number | bigint;\n};\ntype WasmChangeFeed = {\n changes: WasmChangeRecord[];\n latestTxId: number | bigint;\n};\ntype WasmDbStats = Omit<\n DbStats,\n | 'db_id'\n | 'catalog_root_page_id'\n | 'next_page_id'\n | 'last_committed_txid'\n | 'last_replayed_wal_offset'\n | 'manifest_len'\n | 'main_len'\n | 'wal_len'\n | 'health'\n> & {\n db_id: number | bigint;\n catalog_root_page_id: number | bigint;\n next_page_id: number | bigint;\n last_committed_txid: number | bigint;\n last_replayed_wal_offset: number | bigint;\n manifest_len: number | bigint;\n main_len: number | bigint;\n wal_len: number | bigint;\n health: WasmEngineHealth;\n};\ntype WasmEngineHealth =\n | { state: 'healthy' }\n | { state: 'recoveryRequired'; reason: string; pendingTxid?: number | bigint | null }\n | { state: 'closed' };\ntype WasmRecoveryReport = {\n lastCommittedTxid: number | bigint;\n pendingTxid?: number | bigint | null;\n pendingCommitted: boolean;\n};\ntype WasmChangeFeedPolicy = {\n enabled: boolean;\n retainTxids?: number | bigint | null;\n};\ntype WasmEngine = {\n open(name: string, options: unknown): Promise<void>;\n openGeneration(name: string, generationName: string, options: unknown): Promise<void>;\n /** Checkpoints when healthy, then releases the files. */\n close(): void;\n /** Releases the files without writing anything. */\n abandon(): void;\n health(): WasmEngineHealth;\n needs_recovery(): boolean;\n recover(): WasmRecoveryReport;\n checkpoint(): void;\n compact_into(target: WasmEngine): WasmU64;\n compact_into_skipping_stores(target: WasmEngine, skipStores: string[]): WasmU64;\n change_feed_policy(): WasmChangeFeedPolicy;\n set_change_feed_policy(txId: WasmU64, policy: { enabled: boolean; retainTxids: number | null }): void;\n begin_tx(mode: TxMode): WasmU64;\n commit_tx(txId: WasmU64): WasmU64;\n rollback_tx(txId: WasmU64): void;\n create_store(txId: WasmU64, name: string, options?: unknown): void;\n drop_store(txId: WasmU64, name: string): void;\n clear_store(txId: WasmU64, name: string): void;\n get(txId: WasmU64, store: string, key: Uint8Array): Uint8Array | null;\n get_many(txId: WasmU64, store: string, keys: Array<Uint8Array>): Array<Uint8Array | null>;\n /** Little-endian u32 count | count x u32 length (u32::MAX = missing) | bytes. */\n get_many_packed(txId: WasmU64, store: string, keys: Uint8Array): Uint8Array;\n get_many_value_sizes?(txId: WasmU64, store: string, keys: Uint8Array): Uint32Array;\n get_many_value_states?(txId: WasmU64, store: string, keys: Uint8Array): Uint8Array;\n /** Checks existence without loading the value body; TTL headers may be read. */\n has(txId: WasmU64, store: string, key: Uint8Array): boolean;\n /** Optional for SDK compatibility with older bindings. */\n has_many?(txId: WasmU64, store: string, keys: Array<Uint8Array>): boolean[];\n /** Returns whether a live value existed before the write. */\n put(txId: WasmU64, store: string, key: Uint8Array, value: Uint8Array, options?: unknown): boolean;\n put_many(txId: WasmU64, store: string, entries: Array<[Uint8Array, Uint8Array]>, options?: unknown): boolean[];\n /** One byte per entry: 1 when a live value existed before the write. */\n put_many_packed(txId: WasmU64, store: string, entries: Uint8Array, options?: unknown): Uint8Array;\n put_many_indexed_packed(\n txId: WasmU64,\n store: string,\n entries: Uint8Array,\n indexOps: IndexedPutOp[][],\n options?: unknown\n ): Uint8Array;\n put_index_entry_checked?(\n txId: WasmU64,\n primaryStore: string,\n indexStore: string,\n primaryKey: Uint8Array,\n indexKey: Uint8Array,\n revisionEpoch: WasmU64,\n revisionOrdinal: WasmU64\n ): void;\n delete(txId: WasmU64, store: string, key: Uint8Array): boolean;\n delete_many(txId: WasmU64, store: string, keys: Array<Uint8Array>): boolean[];\n /** One byte per key: 1 when a live value was deleted. */\n delete_many_packed(txId: WasmU64, store: string, keys: Uint8Array): Uint8Array;\n apply_batch(txId: WasmU64, store: string, ops: Array<BatchOp>): WasmBatchOutcome[];\n /** One byte per op: baselineExists for puts, deleted for deletes. */\n apply_batch_packed(txId: WasmU64, store: string, ops: Uint8Array): Uint8Array;\n scan(txId: WasmU64, store: string, range: unknown): unknown;\n open_scan_cursor(txId: WasmU64, store: string, range: unknown, keysOnly: boolean): number;\n scan_cursor_next(\n cursorId: number,\n maxRows: number,\n maxBytes: number\n ): {\n packet: Uint8Array;\n rowCount: number;\n exhausted: boolean;\n };\n close_scan_cursor(cursorId: number): void;\n changes_since(txId: WasmU64, options?: unknown): unknown;\n get_schema_version(): WasmU64;\n export_snapshot(): Uint8Array;\n list_store_configs(): unknown;\n import_snapshot(data: Uint8Array): WasmU64;\n import_snapshot_into(target: WasmEngine, data: Uint8Array): WasmU64;\n reset(): WasmU64;\n list_stores(): unknown;\n set_schema_version(txId: WasmU64, version: WasmU64): void;\n stats(): unknown;\n set_failpoint(failpoint: string | null): void;\n};\nexport type WasmModule = {\n default: (\n options?:\n | string\n | URL\n | Request\n | BufferSource\n | WebAssembly.Module\n | {\n module_or_path?:\n string | URL | Request | BufferSource | WebAssembly.Module | Promise<Response> | Response;\n }\n ) => Promise<unknown>;\n deleteDB(name: string): Promise<void>;\n prepareRebuildTarget(name: string): Promise<{\n generationName: string;\n }>;\n /**\n * Publishes only if the active generation matches `expectedCurrent`.\n * `null` requires no active generation. The written control file is\n * flushed and verified before resolving.\n */\n swapActiveGeneration(name: string, generationName: string, expectedCurrent: string | null): Promise<void>;\n /** Active generation, or null for legacy storage. Corrupt control state needs legacy files for fallback. */\n readActiveGeneration(name: string): Promise<string | null>;\n cleanupInactiveEntries(name: string): Promise<void>;\n dbDirectorySize(name: string): Promise<number>;\n WasmEngine: new () => WasmEngine;\n};\ntype WasmU64 = bigint;\nexport interface WorkerPersistenceBridge {\n persisted(): Promise<boolean>;\n persist(): Promise<boolean>;\n close(): void;\n}\nexport interface DbWorkerOptions {\n loadWasm?: () => Promise<WasmModule>;\n persistence?: WorkerPersistenceBridge;\n}\nfunction toWasmU64(value: number | bigint): WasmU64 {\n return BigInt(value);\n}\nfunction fromWasmU64(value: number | bigint): number {\n const number = typeof value === 'bigint' ? Number(value) : value;\n if (!Number.isSafeInteger(number) || number < 0) {\n throw remoteError('SerializationError', 'WASM integer exceeds the JavaScript safe integer range');\n }\n return number;\n}\nfunction fromOptionalWasmU64(value: number | bigint | null | undefined): number | null {\n return value === null || value === undefined ? null : fromWasmU64(value);\n}\nfunction toWasmPutOptions(options: PutOptions): unknown {\n return options.ttl === undefined ? options : { ...options, ttl: toWasmU64(options.ttl) };\n}\nfunction toWasmRange(range: Range): Range {\n assertValidScanRange(range);\n const normalized: Range = {};\n if (range.gt !== undefined) {\n normalized.gt = range.gt;\n }\n if (range.gte !== undefined) {\n normalized.gte = range.gte;\n }\n if (range.lt !== undefined) {\n normalized.lt = range.lt;\n }\n if (range.lte !== undefined) {\n normalized.lte = range.lte;\n }\n if (range.reverse !== undefined) {\n normalized.reverse = range.reverse;\n }\n if (range.limit !== undefined) {\n normalized.limit = range.limit;\n }\n return normalized;\n}\ninterface TrackedKeyChange {\n key: Uint8Array;\n baselineExists: boolean;\n finalKind: DbChange['kind'];\n}\ninterface TrackedStoreChanges {\n touched: boolean;\n /** Latest store-level change; every tracked key change happened after it. */\n storeLevel: 'clear' | 'drop' | null;\n keys: Map<string, TrackedKeyChange>;\n}\ntype TrackedTxnChanges = Map<string, TrackedStoreChanges>;\ninterface IndexBoundCache {\n txId: number;\n def: NormalizedIndexDef;\n reverse: boolean;\n gt?: Uint8Array;\n gte?: Uint8Array;\n lt?: Uint8Array;\n lte?: Uint8Array;\n physical: Range;\n}\n// Published maps stay immutable. Create/drop gives the transaction a private\n// copy, which commit publishes.\ntype StoreCompressionSnapshot =\n | { owned: false; values: ReadonlyMap<string, CompressionOption> }\n | { owned: true; values: Map<string, CompressionOption> };\ntype MaintenanceOperation = 'compact' | 'rebuild' | 'import';\nconst EMPTY_RANGE: Range = {};\nconst EMPTY_VALUE = new Uint8Array(0);\nconst MAX_ENGINE_KEY_BYTES = 1024;\nconst MAX_PACKED_BYTES = 0xffff_ffff;\nconst INDEX_PUT_BATCH_ROWS = 64;\nconst INDEX_PUT_BATCH_BYTES = 4 * 1024 * 1024;\n// Same ceiling as compression.ts. Uncompressed writes reject here and skip the encoder.\nconst MAX_PLAIN_STORE_VALUE_BYTES = 8 * 1024 * 1024;\nconst INDEX_SCAN_PAGE_ROWS = 256;\nconst INDEX_SCAN_PAGE_BYTES = 8 * 1024 * 1024 + 18 + MAX_ENGINE_KEY_BYTES + 12;\nconst INDEX_SCAN_RAW_CHUNK_ROWS = 512;\nconst RECONCILE_DOCUMENT_CACHE_BYTES = 4 * 1024 * 1024;\nconst RECONCILE_DOCUMENT_CACHE_ROWS = 4096;\nconst HEX_BYTE_STRINGS = Array.from({ length: 256 }, (_value, byte) => byte.toString(16).padStart(2, '0'));\nconst COMPRESSED_READ_CONCURRENCY = 8;\nfunction getOrInsert<K, V>(map: Map<K, V>, key: K, create: () => V): V {\n const existing = map.get(key);\n if (existing !== undefined) {\n return existing;\n }\n const created = create();\n map.set(key, created);\n return created;\n}\nconst PERSISTENCE_BRIDGE_INIT = 'moyodb:persistence-bridge:init';\nconst PERSISTENCE_BRIDGE_REQUEST = 'moyodb:persistence-bridge:request';\nconst PERSISTENCE_BRIDGE_RESPONSE = 'moyodb:persistence-bridge:response';\ntype PersistenceBridgeOperation = 'persist' | 'persisted';\ninterface PersistenceBridgeRequest {\n type: typeof PERSISTENCE_BRIDGE_REQUEST;\n id: number;\n op: PersistenceBridgeOperation;\n}\ninterface PersistenceBridgeResponse {\n type: typeof PERSISTENCE_BRIDGE_RESPONSE;\n id: number;\n granted: boolean;\n}\nfunction isPersistenceBridgeResponse(value: unknown): value is PersistenceBridgeResponse {\n return (\n isRecord(value) &&\n value.type === PERSISTENCE_BRIDGE_RESPONSE &&\n typeof value.id === 'number' &&\n typeof value.granted === 'boolean'\n );\n}\nclass MainThreadPersistenceBridge implements WorkerPersistenceBridge {\n private port: MessagePort | null = null;\n private nextRequestId = 1;\n private pending = new Map<\n number,\n {\n resolve: (value: boolean) => void;\n }\n >();\n private readyResolve: ((port: MessagePort | null) => void) | null = null;\n private ready: Promise<MessagePort | null>;\n constructor() {\n this.ready = new Promise((resolve) => {\n this.readyResolve = resolve;\n });\n self.addEventListener('message', this.handleInitMessage as EventListener);\n }\n async persisted(): Promise<boolean> {\n return this.request('persisted');\n }\n async persist(): Promise<boolean> {\n return this.request('persist');\n }\n close(): void {\n self.removeEventListener('message', this.handleInitMessage as EventListener);\n if (this.readyResolve) {\n this.readyResolve(null);\n this.readyResolve = null;\n }\n if (this.port) {\n this.port.onmessage = null;\n this.port.close();\n this.port = null;\n }\n for (const pending of this.pending.values()) {\n pending.resolve(false);\n }\n this.pending.clear();\n }\n private async request(op: PersistenceBridgeOperation): Promise<boolean> {\n const port = await this.ready;\n if (!port || this.port !== port) {\n return false;\n }\n return new Promise<boolean>((resolve) => {\n const id = this.nextRequestId;\n this.nextRequestId += 1;\n this.pending.set(id, { resolve });\n const request: PersistenceBridgeRequest = {\n type: PERSISTENCE_BRIDGE_REQUEST,\n id,\n op\n };\n try {\n port.postMessage(request);\n } catch {\n this.pending.delete(id);\n resolve(false);\n }\n });\n }\n private handleInitMessage = (event: MessageEvent<unknown>) => {\n if (event.origin !== '' && event.origin !== self.location.origin) {\n return;\n }\n const data = event.data as {\n type?: string;\n } | null;\n if (data?.type !== PERSISTENCE_BRIDGE_INIT) {\n return;\n }\n if (event.ports.length === 0) {\n return;\n }\n const port = event.ports[0];\n if (this.port) {\n port.close();\n return;\n }\n this.port = port;\n this.port.onmessage = this.handleResponse;\n this.port.start();\n self.removeEventListener('message', this.handleInitMessage as EventListener);\n this.readyResolve?.(port);\n this.readyResolve = null;\n };\n private handleResponse = (event: MessageEvent<unknown>) => {\n const data = event.data;\n if (!isPersistenceBridgeResponse(data)) {\n return;\n }\n const pending = this.pending.get(data.id);\n if (!pending) {\n return;\n }\n this.pending.delete(data.id);\n pending.resolve(Boolean(data.granted));\n };\n}\nasync function estimateOriginStorage(): Promise<{\n usage: number;\n quota: number;\n}> {\n const storage = navigator.storage;\n if (typeof storage.estimate !== 'function') {\n return { usage: 0, quota: 0 };\n }\n const estimate = await storage.estimate();\n return {\n usage: estimate.usage ?? 0,\n quota: estimate.quota ?? 0\n };\n}\nfunction bytesToHex(bytes: Uint8Array): string {\n let out = '';\n for (let index = 0; index < bytes.byteLength; index += 1) {\n out += HEX_BYTE_STRINGS[bytes[index]];\n }\n return out;\n}\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.byteLength !== right.byteLength) {\n return false;\n }\n for (let index = 0; index < left.byteLength; index += 1) {\n if (left[index] !== right[index]) {\n return false;\n }\n }\n return true;\n}\nfunction copyRange(range: Range): Range {\n const copy = toWasmRange(range);\n for (const bound of ['gt', 'gte', 'lt', 'lte'] as const) {\n const value = copy[bound];\n if (value !== undefined) {\n copy[bound] = value.slice();\n }\n }\n return copy;\n}\nfunction rangesEqual(left: Range, right: Range): boolean {\n for (const bound of ['gt', 'gte', 'lt', 'lte'] as const) {\n const a = left[bound];\n const b = right[bound];\n if (a === undefined ? b !== undefined : b === undefined || !bytesEqual(a, b)) {\n return false;\n }\n }\n return left.reverse === right.reverse && left.limit === right.limit;\n}\nfunction sameBound(cached: Uint8Array | undefined, next: Uint8Array | undefined): boolean {\n if (cached === undefined || next === undefined) {\n return cached === next;\n }\n return bytesEqual(cached, next);\n}\nfunction copyBound(value: Uint8Array | undefined): Uint8Array | undefined {\n return value === undefined ? undefined : value.slice();\n}\nfunction compoundEntryKeyLength(logicalKey: Uint8Array, primaryKey: Uint8Array): number {\n return escapedPartLength(logicalKey) + escapedPartLength(primaryKey);\n}\nfunction escapedPartLength(part: Uint8Array): number {\n let length = 2;\n for (let index = 0; index < part.length; index += 1) {\n length += part[index] === 0 ? 2 : 1;\n }\n return length;\n}\nfunction limitPlainStoreValue(value: Uint8Array): Uint8Array {\n if (value.byteLength > MAX_PLAIN_STORE_VALUE_BYTES) {\n const error = new Error(\n `stored value has ${value.byteLength} bytes, exceeding the ${MAX_PLAIN_STORE_VALUE_BYTES} byte limit`\n );\n error.name = 'ValueTooLargeError';\n throw error;\n }\n return value;\n}\n\nfunction normalizeWasmBytes(value: Uint8Array | ArrayBuffer | ArrayLike<number>): Uint8Array {\n if (value instanceof Uint8Array) {\n return value.byteOffset === 0 && value.byteLength === value.buffer.byteLength ? value : value.slice();\n }\n return new Uint8Array(value);\n}\nfunction errorName(error: unknown): string | null {\n if (!isRecord(error)) {\n return null;\n }\n const candidate = error.name ?? error.code;\n return typeof candidate === 'string' ? candidate : null;\n}\nfunction isNamedError(error: unknown, name: string): boolean {\n return errorName(error) === name;\n}\nconst INDEX_SNAPSHOT_TRAILER_MAGIC = utf8Encode('BDBIDX1');\nconst indexSnapshotDecoder = new TextDecoder('utf-8', { fatal: true });\nfunction wrapSnapshotWithIndexDefinitions(snapshot: Uint8Array, defs: ReadonlyArray<NormalizedIndexDef>): Uint8Array {\n if (defs.length === 0) {\n return snapshot;\n }\n const manifest = utf8Encode(JSON.stringify(toPublicIndexDefinitions(defs)));\n const lengthBuffer = new ArrayBuffer(4);\n new DataView(lengthBuffer).setUint32(0, manifest.byteLength, true);\n const out = new Uint8Array(snapshot.byteLength + manifest.byteLength + 4 + INDEX_SNAPSHOT_TRAILER_MAGIC.byteLength);\n let offset = 0;\n out.set(snapshot, offset);\n offset += snapshot.byteLength;\n out.set(manifest, offset);\n offset += manifest.byteLength;\n out.set(new Uint8Array(lengthBuffer), offset);\n offset += 4;\n out.set(INDEX_SNAPSHOT_TRAILER_MAGIC, offset);\n return out;\n}\nfunction unwrapSnapshotWithIndexDefinitions(data: Uint8Array): {\n snapshot: Uint8Array;\n indexes: NormalizedIndexDef[];\n} {\n const magicLength = INDEX_SNAPSHOT_TRAILER_MAGIC.byteLength;\n if (data.byteLength < magicLength + 4) {\n return { snapshot: data, indexes: [] };\n }\n const magicOffset = data.byteLength - magicLength;\n if (!bytesEqual(data.subarray(magicOffset), INDEX_SNAPSHOT_TRAILER_MAGIC)) {\n return { snapshot: data, indexes: [] };\n }\n const lengthOffset = magicOffset - 4;\n if (lengthOffset < 0) {\n return { snapshot: data, indexes: [] };\n }\n const manifestLength = new DataView(data.buffer, data.byteOffset + lengthOffset, 4).getUint32(0, true);\n const manifestOffset = lengthOffset - manifestLength;\n if (manifestOffset < 0) {\n throw remoteError('CorruptionError', 'invalid snapshot index trailer length');\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(indexSnapshotDecoder.decode(data.subarray(manifestOffset, lengthOffset)));\n } catch (error) {\n throw remoteError('CorruptionError', `invalid snapshot index trailer: ${String(error)}`);\n }\n return {\n snapshot: data.subarray(0, manifestOffset),\n indexes: normalizeIndexDefinitions(parsed)\n };\n}\nfunction lifecycleEventChannel(dbName: string): BroadcastChannel {\n return new BroadcastChannel(`db:${dbName}:events`);\n}\nfunction broadcastLifecycleEvent(dbName: string, type: 'owner_changed' | 'db_closed' | 'db_deleted') {\n const channel = lifecycleEventChannel(dbName);\n try {\n channel.postMessage({ type, dbName, txid: null });\n } finally {\n channel.close();\n }\n}\nclass OwnershipLease {\n private releaseResolver: (() => void) | null = null;\n private requestPromise: Promise<unknown> | null = null;\n private held = false;\n async acquire(dbName: string, ownerWaitMs: number): Promise<void> {\n const holdPromise = new Promise<void>((resolve) => {\n this.releaseResolver = resolve;\n });\n const lockName = `db:${dbName}:owner`;\n if (ownerWaitMs === 0) {\n let acquiredResolve: ((value: boolean) => void) | null = null;\n const acquiredPromise = new Promise<boolean>((resolve) => {\n acquiredResolve = resolve;\n });\n const request = navigator.locks.request(\n lockName,\n { mode: 'exclusive', ifAvailable: true },\n async (lock) => {\n if (!lock) {\n acquiredResolve?.(false);\n return false;\n }\n this.held = true;\n acquiredResolve?.(true);\n await holdPromise;\n return true;\n }\n );\n const acquired = await acquiredPromise;\n if (!acquired) {\n throw remoteError('DatabaseBusyError', `database ${dbName} is already owned by another tab`);\n }\n this.requestPromise = request;\n return;\n }\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), clampTimerDelayMs(ownerWaitMs));\n let acquiredResolve: (() => void) | null = null;\n const acquiredPromise = new Promise<void>((resolve) => {\n acquiredResolve = resolve;\n });\n this.requestPromise = navigator.locks.request(\n lockName,\n { mode: 'exclusive', signal: controller.signal },\n async (_lock) => {\n clearTimeout(timeout);\n this.held = true;\n acquiredResolve?.();\n await holdPromise;\n return true;\n }\n );\n try {\n await Promise.race([acquiredPromise, this.requestPromise]);\n } catch {\n if (!this.held) {\n throw remoteError('DatabaseBusyError', `timed out waiting for ownership of ${dbName}`);\n }\n }\n }\n async release(): Promise<void> {\n if (!this.held) {\n return;\n }\n this.releaseResolver?.();\n try {\n await this.requestPromise;\n } finally {\n this.releaseResolver = null;\n this.requestPromise = null;\n this.held = false;\n }\n }\n}\nexport class DbWorker implements WorkerApi {\n private dbName: string | null = null;\n private engine: WasmEngine | null = null;\n private events: BroadcastChannel | null = null;\n private lease: OwnershipLease | null = null;\n private wasmReady: Promise<WasmModule> | null = null;\n private persistenceBridge: WorkerPersistenceBridge;\n private txChanges = new Map<number, TrackedTxnChanges>();\n private txModes = new Map<number, TxMode>();\n private primaryCursors = new Map<\n number,\n { engineId: number; txId: number; ownsTx: boolean; store: string; range: Range; callerTxId?: number }\n >();\n private nextPrimaryCursorId = 1;\n /**\n * Shared committed schema at begin. Reconciliation replaces the array;\n * it never mutates the shared schema.\n */\n private txIndexSchemas = new Map<number, NormalizedIndexDef[]>();\n private indexesBySchema = new WeakMap<NormalizedIndexDef[], Map<string, NormalizedIndexDef[]>>();\n /** Readonly scans reuse a resolved index; readwrite scans recheck so TTL staging still runs. */\n private readonlyIndexCache = new Map<number, Map<string, Map<string, NormalizedIndexDef>>>();\n private indexBoundCache: IndexBoundCache | null = null;\n private txEnsuredRawStores = new Map<number, Set<string>>();\n private txIndexSchemaChanged = new Set<number>();\n private txStoreCompression = new Map<number, StoreCompressionSnapshot>();\n private committedIndexes: NormalizedIndexDef[] | null = null;\n private committedStoreCompression: ReadonlyMap<string, CompressionOption> | null = null;\n private openOptions: WorkerOpenRequest['options'] | null = null;\n private maintenanceOperation: MaintenanceOperation | null = null;\n constructor(private readonly options: DbWorkerOptions = {}) {\n this.persistenceBridge = options.persistence ?? new MainThreadPersistenceBridge();\n }\n async open(request: WorkerOpenRequest): Promise<void> {\n if (this.engine) {\n return;\n }\n assertSecureContext();\n assertCapabilities();\n this.dbName = request.dbName;\n this.events = new BroadcastChannel(`db:${request.dbName}:events`);\n this.lease = new OwnershipLease();\n let engine: WasmEngine | null = null;\n try {\n await this.lease.acquire(request.dbName, request.options.ownerWaitMs);\n const wasm = await this.loadWasm();\n engine = new wasm.WasmEngine();\n await engine.open(request.dbName, {\n create_if_missing: request.options.createIfMissing,\n cache_pages: request.options.cachePages\n });\n if (request.options.changeFeed) {\n applyChangeFeedPolicy(engine, request.options.changeFeed);\n }\n if (request.options.debugFailpoint) {\n engine.set_failpoint(request.options.debugFailpoint);\n }\n this.engine = engine;\n this.openOptions = request.options;\n this.clearRuntimeCaches();\n this.maintenanceOperation = null;\n this.events.postMessage({ type: 'owner_changed', dbName: request.dbName, txid: null });\n } catch (err) {\n await this.cleanupAfterFailedOpen(engine);\n throw remapError(err);\n }\n }\n async close(): Promise<void> {\n this.ensureNotInMaintenance();\n const dbName = this.dbName;\n this.clearRuntimeCaches();\n try {\n this.engine?.close();\n } catch (err) {\n throw remapError(err);\n } finally {\n this.engine = null;\n if (dbName && this.events) {\n this.events.postMessage({ type: 'db_closed', dbName, txid: null });\n }\n this.events?.close();\n this.events = null;\n if (dbName && this.lease) {\n await this.lease.release();\n }\n if (dbName) {\n broadcastLifecycleEvent(dbName, 'owner_changed');\n }\n this.disposePersistenceBridge();\n this.lease = null;\n this.dbName = null;\n this.openOptions = null;\n this.maintenanceOperation = null;\n }\n }\n async destroy(): Promise<void> {\n this.ensureNotInMaintenance();\n const dbName = this.dbName;\n if (!dbName) {\n return;\n }\n let failure: unknown = null;\n try {\n this.rollbackAllTransactions();\n // Skip the checkpoint because the database files will be deleted.\n this.engine?.abandon();\n const wasm = await this.loadWasm();\n await wasm.deleteDB(dbName);\n broadcastLifecycleEvent(dbName, 'db_deleted');\n } catch (err) {\n failure = err;\n } finally {\n this.engine = null;\n this.clearRuntimeCaches();\n this.events?.close();\n this.events = null;\n if (this.lease) {\n try {\n await this.lease.release();\n } catch (err) {\n if (failure === null) {\n failure = err;\n }\n }\n }\n broadcastLifecycleEvent(dbName, 'owner_changed');\n this.disposePersistenceBridge();\n this.lease = null;\n this.dbName = null;\n this.openOptions = null;\n this.maintenanceOperation = null;\n }\n if (failure !== null) {\n throw remapError(failure);\n }\n }\n async deleteDB(dbName: string): Promise<void> {\n assertSecureContext();\n assertCapabilities();\n const lease = new OwnershipLease();\n let failure: unknown = null;\n let acquired = false;\n try {\n await lease.acquire(dbName, 0);\n acquired = true;\n const wasm = await this.loadWasm();\n await wasm.deleteDB(dbName);\n broadcastLifecycleEvent(dbName, 'db_deleted');\n } catch (err) {\n failure = err;\n } finally {\n try {\n await lease.release();\n } catch (err) {\n if (failure === null) {\n failure = err;\n }\n }\n if (acquired) {\n broadcastLifecycleEvent(dbName, 'owner_changed');\n }\n }\n if (failure !== null) {\n throw remapError(failure);\n }\n }\n begin(mode: TxMode): Promise<number> {\n this.recoverEngineIfNeeded();\n const indexSchema = this.loadCommittedIndexSchema();\n const storeCompression = this.loadCommittedStoreCompression();\n const txId = fromWasmU64(this.withEngine((engine) => engine.begin_tx(mode)));\n this.txChanges.set(txId, new Map<string, TrackedStoreChanges>());\n this.txModes.set(txId, mode);\n this.txIndexSchemas.set(txId, indexSchema);\n this.txStoreCompression.set(txId, { owned: false, values: storeCompression });\n return Promise.resolve(txId);\n }\n commit(txId: number): Promise<number> {\n const tracked = this.txChanges.get(txId) ?? new Map<string, TrackedStoreChanges>();\n const indexOverride = this.txIndexSchemaChanged.has(txId) ? this.txIndexSchemas.get(txId) : undefined;\n const storeCompressionSnapshot = this.txStoreCompression.get(txId);\n const txMode = this.txModes.get(txId);\n let txid: number;\n try {\n txid = fromWasmU64(this.withEngine((engine) => engine.commit_tx(toWasmU64(txId))));\n } catch (err) {\n // A failed public commit consumes its handle, but some engine errors\n // retain the transaction. Release it before clearing the SDK state.\n try {\n if (this.engine && !this.engine.needs_recovery()) {\n this.withEngine((engine) => engine.rollback_tx(toWasmU64(txId)));\n }\n } catch {}\n this.cleanupTxState(txId);\n const recovery = this.recoverEngineIfNeeded();\n // Report a recovered durable commit as success. Injected failures\n // model a crash. RecoveryRequiredError refers to an earlier failed\n // operation, so its recovery report cannot confirm this commit.\n if (\n !recovery?.pendingCommitted ||\n recovery.pendingTxid === null ||\n isNamedError(err, 'RecoveryRequiredError') ||\n isNamedError(err, 'InjectedFailureError')\n ) {\n throw err;\n }\n txid = recovery.pendingTxid;\n }\n if (indexOverride) {\n this.committedIndexes = cloneNormalizedIndexDefinitions(indexOverride);\n }\n if (txMode === 'readwrite' && storeCompressionSnapshot) {\n this.committedStoreCompression = storeCompressionSnapshot.values;\n }\n this.cleanupTxState(txId);\n if (this.dbName && this.events) {\n const event: CommitAppliedEvent = {\n type: 'commit_applied',\n dbName: this.dbName,\n txid,\n stores: this.finalizeTrackedChanges(tracked)\n };\n this.events.postMessage(event);\n }\n return Promise.resolve(txid);\n }\n rollback(txId: number): Promise<void> {\n try {\n this.withEngine((engine) => engine.rollback_tx(toWasmU64(txId)));\n } finally {\n this.cleanupTxState(txId);\n }\n return Promise.resolve();\n }\n async autocommit(mode: TxMode, command: AutocommitCommand, args: unknown[]): Promise<unknown> {\n const txId = await this.begin(mode);\n const method = this[command] as unknown as (...methodArgs: unknown[]) => Promise<unknown>;\n let result: unknown;\n try {\n result = await method.apply(this, [txId, ...args]);\n } catch (error) {\n try {\n await this.rollback(txId);\n } catch {}\n throw error;\n }\n if (mode === 'readwrite') {\n await this.commit(txId);\n } else {\n await this.rollback(txId);\n }\n return result;\n }\n createStore(txId: number, name: string, options: CreateStoreOptions = {}): Promise<void> {\n const compression = isInternalStoreName(name) ? false : (options.compression ?? 'snappy');\n this.txEnsuredRawStores.get(txId)?.delete(name);\n this.withEngine((engine) => engine.create_store(toWasmU64(txId), name, { compression }));\n this.recordStoreCompressionCreate(txId, name, compression);\n this.ensureInternalStoresForStore(txId, name);\n this.markStoreTouched(txId, name);\n return Promise.resolve();\n }\n dropStore(txId: number, name: string): Promise<void> {\n const defs = this.indexesForStoreInTx(txId, name);\n this.txEnsuredRawStores.get(txId)?.delete(name);\n this.withEngine((engine) => engine.drop_store(toWasmU64(txId), name));\n this.recordStoreCompressionDrop(txId, name);\n for (const def of defs) {\n this.dropRawStoreIfExists(txId, def.internalStore);\n }\n this.recordStoreLevelChange(txId, name, 'drop');\n return Promise.resolve();\n }\n clearStore(txId: number, name: string): Promise<void> {\n const defs = this.indexesForStoreInTx(txId, name);\n this.txEnsuredRawStores.get(txId)?.delete(name);\n this.withEngine((engine) => engine.clear_store(toWasmU64(txId), name));\n for (const def of defs) {\n this.clearRawStoreIfExists(txId, def.internalStore);\n }\n this.recordStoreLevelChange(txId, name, 'clear');\n return Promise.resolve();\n }\n async get(txId: number, store: string, key: Uint8Array): Promise<Uint8Array | null> {\n return this.readStoreValue(txId, store, key);\n }\n async getMany(txId: number, store: string, keys: Array<Uint8Array>): Promise<Array<Uint8Array | null>> {\n const values = this.withEngine((engine) => engine.get_many(toWasmU64(txId), store, keys));\n const compressed = !isInternalStoreName(store) && this.storeCompressionForTx(txId, store) !== false;\n // Normalize all borrowed views before a decoder can suspend. Values\n // waiting for a decoder must also retain stable buffers.\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index];\n if (value !== null) {\n values[index] = normalizeWasmBytes(value);\n }\n }\n return compressed ? this.decodeStoreValues(txId, store, values) : values;\n }\n async getManyPacked(\n txId: number,\n store: string,\n packedKeys: Uint8Array\n ): Promise<PackedOptionalValuesV1 | Array<Uint8Array | null>> {\n const packed = normalizeWasmBytes(\n this.withEngine((engine) => engine.get_many_packed(toWasmU64(txId), store, packedKeys))\n );\n if (isInternalStoreName(store) || this.storeCompressionForTx(txId, store) === false) {\n // The protocol accepts the engine packet directly.\n return packedOptionalValues(packed);\n }\n // Decoders retain views of this private packet, including while queued.\n return this.decodeStoreValues(txId, store, unpackPackedOptionalValues(packed));\n }\n has(txId: number, store: string, key: Uint8Array): Promise<boolean> {\n return Promise.resolve(this.withEngine((engine) => engine.has(toWasmU64(txId), store, key)));\n }\n async put(\n txId: number,\n store: string,\n key: Uint8Array,\n value: Uint8Array,\n options: PutOptions = {}\n ): Promise<void> {\n await this.putEntry(txId, store, key, value, options);\n }\n private async putEntry(\n txId: number,\n store: string,\n key: Uint8Array,\n value: Uint8Array,\n options: PutOptions,\n knownDefs?: readonly NormalizedIndexDef[],\n knownCompression?: CompressionOption\n ): Promise<void> {\n const defs = knownDefs ?? this.indexesForStoreInTx(txId, store);\n const compression = knownCompression ?? this.storeCompressionForTx(txId, store);\n if (defs.length === 0) {\n const preparedValue = this.prepareStoredValue(store, value, compression);\n const storedValue = preparedValue instanceof Uint8Array ? preparedValue : await preparedValue;\n const baselineExists = this.withEngine((engine) =>\n engine.put(toWasmU64(txId), store, key, storedValue, toWasmPutOptions(options))\n );\n this.recordPutChange(txId, store, key, baselineExists);\n return;\n }\n await this.putIndexedMany(txId, store, [key, value], defs, options);\n }\n async putMany(\n txId: number,\n store: string,\n entries: Array<[Uint8Array, Uint8Array]>,\n options: PutOptions = {}\n ): Promise<void> {\n if (entries.length === 0) {\n return;\n }\n const defs = this.indexesForStoreInTx(txId, store);\n if (defs.length === 0) {\n const storedEntries = await this.encodeEntriesForWrite(txId, store, entries);\n let baselines: boolean[];\n try {\n baselines = this.withEngine((engine) =>\n engine.put_many(toWasmU64(txId), store, storedEntries, toWasmPutOptions(options))\n );\n } catch (error) {\n const partial = partialBooleanOutcomes(error);\n this.recordPutChanges(txId, store, entries, partial);\n throw error;\n }\n if (baselines.length !== entries.length) {\n throw outcomeCountMismatch('put_many', baselines.length, entries.length);\n }\n this.recordPutChanges(txId, store, entries, baselines);\n return;\n }\n const items = new Array<Uint8Array>(entries.length * 2);\n for (let index = 0; index < entries.length; index += 1) {\n items[index * 2] = entries[index][0];\n items[index * 2 + 1] = entries[index][1];\n }\n await this.putIndexedMany(txId, store, items, defs, options);\n }\n async putManyPacked(\n txId: number,\n store: string,\n packedEntries: Uint8Array,\n options: PutOptions = {}\n ): Promise<void> {\n const defs = this.indexesForStoreInTx(txId, store);\n if (defs.length !== 0) {\n const items = unpackPackedBinaryList(packedEntries);\n if (items.length % 2 !== 0) {\n throw remoteError('WorkerProtocolError', 'packed putMany payload has an odd item count');\n }\n await this.putIndexedMany(txId, store, items, defs, options);\n return;\n }\n const compression = this.storeCompressionForTx(txId, store);\n const items = compression === false ? null : unpackPackedBinaryList(packedEntries);\n if (items !== null && items.length % 2 !== 0) {\n throw remoteError('WorkerProtocolError', 'packed putMany payload has an odd item count');\n }\n const keys =\n items === null\n ? unpackPackedBinaryPairKeys(packedEntries)\n : items.filter((_item, index) => index % 2 === 0);\n if (keys.length === 0) {\n return;\n }\n const storedEntries =\n items === null ? packedEntries : await this.encodePackedEntriesForWrite(txId, store, items, keys);\n let baselines: Uint8Array;\n try {\n baselines = this.withEngine((engine) =>\n engine.put_many_packed(toWasmU64(txId), store, storedEntries, toWasmPutOptions(options))\n );\n } catch (error) {\n const partial = partialBooleanOutcomes(error);\n this.recordPutKeyChanges(txId, store, keys, partial);\n throw error;\n }\n if (baselines.length !== keys.length) {\n throw outcomeCountMismatch('put_many_packed', baselines.length, keys.length);\n }\n this.recordPutKeyChanges(txId, store, keys, baselines);\n }\n async delete(txId: number, store: string, key: Uint8Array): Promise<boolean> {\n const defs = this.indexesForStoreInTx(txId, store);\n // Load the previous document only when its index keys must be removed.\n const oldValue = defs.length === 0 ? null : await this.readStoreValue(txId, store, key);\n const oldKeyFor = oldValue === null ? null : createIndexKeyExtractor(oldValue);\n const oldLogicalKeys = oldKeyFor === null ? [] : defs.map((def) => ({ def, logicalKey: oldKeyFor(def) }));\n const deleted = this.withEngine((engine) => engine.delete(toWasmU64(txId), store, key));\n if (!deleted) {\n this.recordDeleteChange(txId, store, key, false);\n return false;\n }\n for (const entry of oldLogicalKeys) {\n if (entry.logicalKey !== null) {\n this.deleteIndexEntryIfPresent(txId, entry.def, entry.logicalKey, key);\n }\n }\n this.recordDeleteChange(txId, store, key, true);\n return true;\n }\n async deleteMany(txId: number, store: string, keys: Array<Uint8Array>): Promise<void> {\n if (keys.length === 0) {\n return;\n }\n const defs = this.indexesForStoreInTx(txId, store);\n if (defs.length === 0) {\n let deleted: boolean[];\n try {\n deleted = this.withEngine((engine) => engine.delete_many(toWasmU64(txId), store, keys));\n } catch (error) {\n const partial = partialBooleanOutcomes(error);\n for (let i = 0; i < partial.length && i < keys.length; i += 1) {\n this.recordDeleteChange(txId, store, keys[i], partial[i]);\n }\n throw error;\n }\n if (deleted.length !== keys.length) {\n throw outcomeCountMismatch('delete_many', deleted.length, keys.length);\n }\n for (let i = 0; i < keys.length; i += 1) {\n this.recordDeleteChange(txId, store, keys[i], deleted[i]);\n }\n return;\n }\n for (const key of keys) {\n await this.delete(txId, store, key);\n }\n }\n async deleteManyPacked(txId: number, store: string, packedKeys: Uint8Array): Promise<void> {\n const defs = this.indexesForStoreInTx(txId, store);\n const keys = unpackPackedBinaryList(packedKeys);\n if (keys.length === 0) {\n return;\n }\n if (defs.length !== 0) {\n await this.deleteMany(txId, store, keys);\n return;\n }\n let deleted: Uint8Array;\n try {\n deleted = this.withEngine((engine) => engine.delete_many_packed(toWasmU64(txId), store, packedKeys));\n } catch (error) {\n const partial = partialBooleanOutcomes(error);\n for (let i = 0; i < partial.length && i < keys.length; i += 1) {\n this.recordDeleteChange(txId, store, keys[i], partial[i]);\n }\n throw error;\n }\n if (deleted.length !== keys.length) {\n throw outcomeCountMismatch('delete_many_packed', deleted.length, keys.length);\n }\n for (let i = 0; i < keys.length; i += 1) {\n this.recordDeleteChange(txId, store, keys[i], deleted[i] === 1);\n }\n }\n async applyBatch(txId: number, store: string, ops: Array<BatchOp>): Promise<void> {\n if (ops.length === 0) {\n return;\n }\n const defs = this.indexesForStoreInTx(txId, store);\n if (defs.length === 0) {\n const storedOps = await this.encodeBatchOpsForWrite(txId, store, ops);\n let outcomes: WasmBatchOutcome[];\n try {\n outcomes = this.withEngine((engine) => engine.apply_batch(toWasmU64(txId), store, storedOps));\n } catch (error) {\n this.recordBatchOutcomes(txId, store, ops, partialBatchOutcomes(error));\n throw error;\n }\n if (outcomes.length !== ops.length) {\n throw outcomeCountMismatch('apply_batch', outcomes.length, ops.length);\n }\n this.recordBatchOutcomes(txId, store, ops, outcomes);\n return;\n }\n for (const op of ops) {\n if (op.kind === 'put') {\n await this.put(txId, store, op.key, op.value);\n } else {\n await this.delete(txId, store, op.key);\n }\n }\n }\n async applyBatchPacked(txId: number, store: string, packedOps: Uint8Array): Promise<void> {\n const defs = this.indexesForStoreInTx(txId, store);\n if (defs.length !== 0 || this.storeCompressionForTx(txId, store) !== false) {\n const ops = unpackPackedBatchOps(packedOps);\n if (ops.length === 0) {\n return;\n }\n await this.applyBatch(txId, store, ops);\n return;\n }\n const ops = unpackPackedBatchOpKeys(packedOps);\n if (ops.length === 0) {\n return;\n }\n let flags: Uint8Array;\n try {\n flags = this.withEngine((engine) => engine.apply_batch_packed(toWasmU64(txId), store, packedOps));\n } catch (error) {\n this.recordBatchOutcomes(txId, store, ops, partialBatchOutcomes(error));\n throw error;\n }\n if (flags.length !== ops.length) {\n throw outcomeCountMismatch('apply_batch_packed', flags.length, ops.length);\n }\n for (let i = 0; i < ops.length; i += 1) {\n const op = ops[i];\n if (op.kind === 'put') {\n this.recordPutChange(txId, store, op.key, flags[i] === 1);\n } else {\n this.recordDeleteChange(txId, store, op.key, flags[i] === 1);\n }\n }\n }\n async scan(txId: number, store: string, range: Range): Promise<ScanItem[]> {\n return this.readStoreScan(txId, store, range);\n }\n async scanPage(request: WorkerScanPageRequest): Promise<WorkerScanPage> {\n if (\n !Number.isSafeInteger(request.maxRows) ||\n request.maxRows <= 0 ||\n request.maxRows > MAX_PACKED_BYTES ||\n !Number.isSafeInteger(request.maxBytes) ||\n request.maxBytes < 4 ||\n request.maxBytes > MAX_PACKED_BYTES\n ) {\n throw remoteError(\n 'InvalidRangeError',\n 'scan page budgets must be positive u32 integers; maxBytes must be at least 4'\n );\n }\n let cursorId = request.cursorId;\n let cursor = cursorId === undefined ? undefined : this.primaryCursors.get(cursorId);\n if (cursorId !== undefined) {\n if (!cursor) {\n throw remoteError('TransactionClosedError', 'scan cursor is closed');\n }\n if (\n cursor.store !== request.store ||\n cursor.callerTxId !== request.txId ||\n !rangesEqual(cursor.range, request.range ?? EMPTY_RANGE)\n ) {\n throw remoteError('InvalidRangeError', 'scan continuation does not match the cursor');\n }\n } else {\n const ownsTx = request.txId === undefined;\n const txId = request.txId ?? (await this.begin('readonly'));\n const range = copyRange(request.range ?? EMPTY_RANGE);\n let engineId: number;\n try {\n engineId = this.withEngine((engine) =>\n engine.open_scan_cursor(toWasmU64(txId), request.store, toWasmRange(range), false)\n );\n } catch (error) {\n if (ownsTx) {\n try {\n await this.rollback(txId);\n } catch {}\n }\n throw error;\n }\n cursorId = this.nextPrimaryCursorId++;\n cursor = { engineId, txId, ownsTx, store: request.store, range, callerTxId: request.txId };\n this.primaryCursors.set(cursorId, cursor);\n }\n try {\n const page = this.withEngine((engine) =>\n engine.scan_cursor_next(cursor.engineId, request.maxRows, request.maxBytes)\n );\n const packet = normalizeWasmBytes(page.packet);\n const rowCount =\n packet.byteLength < 4 ? -1 : new DataView(packet.buffer, packet.byteOffset, 4).getUint32(0, true);\n if (rowCount !== page.rowCount || rowCount > request.maxRows || packet.byteLength > request.maxBytes) {\n throw remoteError('CorruptionError', 'scan cursor returned an invalid page budget or count');\n }\n const compressed = this.storeCompressionForTx(cursor.txId, cursor.store) !== false;\n const rows = compressed ? unpackPackedScanRows(packet) : null;\n let bytes = packet.byteLength;\n if (rows !== null) {\n bytes = 4;\n for (const row of rows) {\n row.value = await decodeStoreValueRecord(row.value, { strict: true });\n bytes += 8 + row.key.byteLength + row.value.byteLength;\n if (bytes > request.maxBytes) {\n throw remoteError('ValueTooLargeError', 'decoded scan page exceeds maxBytes');\n }\n }\n }\n if (page.exhausted) {\n await this.closeCursor(cursorId!);\n }\n return {\n rows: rows ?? (packedScanRows(packet) as unknown as ScanItem[]),\n done: page.exhausted,\n bytes,\n ...(page.exhausted ? {} : { cursorId })\n };\n } catch (error) {\n try {\n await this.closeCursor(cursorId!);\n } catch {}\n throw error;\n }\n }\n async closeCursor(cursorId: number): Promise<void> {\n const cursor = this.primaryCursors.get(cursorId);\n if (!cursor) {\n return;\n }\n this.primaryCursors.delete(cursorId);\n try {\n this.withEngine((engine) => engine.close_scan_cursor(cursor.engineId));\n } finally {\n if (cursor.ownsTx) {\n await this.rollback(cursor.txId);\n }\n }\n }\n async getByIndex(txId: number, store: string, indexName: string, key: Uint8Array): Promise<Uint8Array | null> {\n const def = this.resolveIndexDefinition(txId, store, indexName);\n const page = await this.loadVisibleIndexPage(txId, def, { gte: key, lte: key }, null, 1);\n return page.rows.length === 0 ? null : page.rows[0].value;\n }\n async scanByIndex(txId: number, store: string, indexName: string, range: Range = {}): Promise<ScanItem[]> {\n assertValidScanRange(range);\n const def = this.resolveIndexDefinition(txId, store, indexName);\n const rows: ScanItem[] = [];\n let remaining = range.limit ?? Number.POSITIVE_INFINITY;\n if (remaining <= 0) {\n return rows;\n }\n const physical = this.physicalIndexRange(txId, def, range);\n let cursor: Uint8Array | null = null;\n while (remaining > 0) {\n const page = await this.loadVisibleIndexPage(\n txId,\n def,\n range,\n cursor,\n Math.min(remaining, INDEX_SCAN_PAGE_ROWS),\n INDEX_SCAN_PAGE_BYTES,\n physical\n );\n rows.push(...page.rows);\n remaining -= page.rows.length;\n if (page.cursor === null) {\n break;\n }\n cursor = page.cursor;\n }\n return rows;\n }\n async scanByIndexPage(\n txId: number,\n store: string,\n indexName: string,\n range: Range,\n cursor: Uint8Array | null,\n limit: number,\n maxBytes: number = INDEX_SCAN_PAGE_BYTES\n ): Promise<IndexScanPage> {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw remoteError('InvalidRangeError', 'index scan page limit must be a positive integer');\n }\n if (!Number.isSafeInteger(maxBytes) || maxBytes < 4 || maxBytes > MAX_PACKED_BYTES) {\n throw remoteError('InvalidRangeError', 'index scan page maxBytes must be a u32 integer of at least 4');\n }\n const def = this.resolveIndexDefinition(txId, store, indexName);\n return this.loadVisibleIndexPage(\n txId,\n def,\n range,\n cursor,\n limit,\n maxBytes,\n this.physicalIndexRange(txId, def, range)\n );\n }\n getIndexes(txId?: number): Promise<IndexDef[]> {\n return Promise.resolve(\n toPublicIndexDefinitions(txId === undefined ? this.loadCommittedIndexSchema() : this.indexSchemaForTx(txId))\n );\n }\n async reconcileIndexes(txId: number, indexes: IndexDef[]): Promise<void> {\n const target = normalizeIndexDefinitions(indexes);\n this.ensureRawStore(txId, INDEX_METADATA_STORE);\n const current = this.readIndexSchemaInTx(txId);\n const targetStores = new Set(target.map((def) => def.internalStore));\n for (const def of current) {\n if (!targetStores.has(def.internalStore)) {\n this.dropRawStoreIfExists(txId, def.internalStore);\n }\n }\n this.clearRawStoreIfExists(txId, INDEX_METADATA_STORE);\n let documentStore: string | null = null;\n let cachedBytes = 0;\n let sourceRows: ScanItem[] | null = null;\n const canRefreshVisibility = typeof this.engine?.has_many === 'function';\n const documents = new Map<string, { bytes: Uint8Array; inputBytes: number; document: unknown }>();\n for (const def of target) {\n if (documentStore !== def.store) {\n documents.clear();\n cachedBytes = 0;\n sourceRows = null;\n documentStore = def.store;\n }\n this.ensureRawStore(txId, def.internalStore);\n this.clearRawStoreIfExists(txId, def.internalStore);\n if (this.rawStoreExistsInTx(txId, def.store)) {\n let rows: ScanItem[];\n if (sourceRows !== null) {\n // The transaction lane keeps source keys and bytes stable.\n // Refresh TTL visibility and stage expiry before validating\n // this index, using one timestamp for all cached rows.\n const visible = this.withEngine((engine) =>\n engine.has_many!(\n toWasmU64(txId),\n def.store,\n sourceRows!.map((row) => row.key)\n )\n );\n if (visible.length !== sourceRows.length) {\n throw outcomeCountMismatch('has_many', visible.length, sourceRows.length);\n }\n rows = sourceRows.filter((_row, index) => visible[index]);\n } else {\n // Full scans refresh visibility when caching is unavailable.\n rows = await this.readStoreScan(txId, def.store, EMPTY_RANGE);\n if (canRefreshVisibility && rows.length <= RECONCILE_DOCUMENT_CACHE_ROWS) {\n let inputBytes = 0;\n for (const row of rows) {\n inputBytes += row.key.byteLength + row.value.byteLength;\n if (inputBytes > RECONCILE_DOCUMENT_CACHE_BYTES) {\n break;\n }\n }\n if (inputBytes <= RECONCILE_DOCUMENT_CACHE_BYTES) {\n // Source rows and the document cache share owned value buffers.\n sourceRows = rows;\n }\n }\n }\n for (const row of rows) {\n const token = bytesToHex(row.key);\n const cached = documents.get(token);\n let document: unknown;\n if (cached && (cached.bytes === row.value || bytesEqual(cached.bytes, row.value))) {\n document = cached.document;\n cached.bytes = row.value;\n } else {\n document = decodeIndexedDocument(row.value);\n const previousBytes = cached?.inputBytes ?? 0;\n const inputBytes = row.key.byteLength + row.value.byteLength;\n if (\n (cached || documents.size < RECONCILE_DOCUMENT_CACHE_ROWS) &&\n cachedBytes - previousBytes + inputBytes <= RECONCILE_DOCUMENT_CACHE_BYTES\n ) {\n documents.set(token, { bytes: row.value, inputBytes, document });\n cachedBytes += inputBytes - previousBytes;\n } else if (cached) {\n documents.delete(token);\n cachedBytes -= previousBytes;\n }\n }\n const logicalKey = extractLogicalIndexKeyFromDocument(def, document);\n if (logicalKey === null) {\n continue;\n }\n await this.assertUniqueIndexAvailability(txId, def, logicalKey, row.key);\n this.putIndexEntry(txId, def, this.buildIndexEntryKey(def, logicalKey, row.key), EMPTY_VALUE);\n }\n }\n this.putRawValue(\n txId,\n INDEX_METADATA_STORE,\n encodeIndexMetadataKey(def.store, def.name),\n encodeIndexMetadataValue(def)\n );\n }\n this.txIndexSchemas.set(txId, cloneNormalizedIndexDefinitions(target));\n this.txIndexSchemaChanged.add(txId);\n }\n listStores(): Promise<string[]> {\n return Promise.resolve(this.currentStoreNames());\n }\n getVersion(): Promise<number> {\n return Promise.resolve(fromWasmU64(this.withEngine((engine) => engine.get_schema_version())));\n }\n async changesSince(txId: number, options: ChangeFeedOptions = {}): Promise<ChangeFeed> {\n const visibleStores = options.stores?.filter((store) => !isInternalStoreName(store));\n const engineOptions: ChangeFeedOptions = {\n ...options,\n stores: visibleStores ? [...visibleStores] : undefined,\n limit: visibleStores ? options.limit : undefined\n };\n const feed = this.withEngine((engine) =>\n engine.changes_since(toWasmU64(txId), engineOptions)\n ) as WasmChangeFeed;\n const allowedStores = visibleStores ? new Set(visibleStores) : null;\n const changes: ChangeFeed['changes'] = [];\n for (const change of feed.changes) {\n if (isInternalStoreName(change.store)) {\n continue;\n }\n if (allowedStores && !allowedStores.has(change.store)) {\n continue;\n }\n const key =\n options.limit === undefined || changes.length < options.limit ? normalizeWasmBytes(change.key) : null;\n let value: Uint8Array | undefined;\n if (change.value !== undefined) {\n // Validate returned public records beyond the output limit\n // so their corruption errors still reach the caller.\n value = await this.decodeStoreValueForFeed(change.store, normalizeWasmBytes(change.value));\n }\n if (key === null) {\n continue;\n }\n changes.push({\n txId: fromWasmU64(change.txId),\n store: change.store,\n key,\n kind: change.kind,\n value\n });\n }\n return {\n latestTxId: fromWasmU64(feed.latestTxId),\n changes\n };\n }\n setSchemaVersion(txId: number, version: number): Promise<void> {\n this.withEngine((engine) => engine.set_schema_version(toWasmU64(txId), toWasmU64(version)));\n return Promise.resolve();\n }\n async exportSnapshot(options: ExportSnapshotOptions = {}): Promise<Uint8Array> {\n const defs = cloneNormalizedIndexDefinitions(this.loadCommittedIndexSchema());\n const bytes = this.withEngine((engine) => engine.export_snapshot());\n const wrapped = wrapSnapshotWithIndexDefinitions(normalizeWasmBytes(bytes), defs);\n return await wrapSnapshotWithCompression(wrapped, options.compression ?? false);\n }\n async importSnapshot(data: Uint8Array): Promise<void> {\n this.ensureNotInMaintenance();\n const decompressed = await unwrapSnapshotCompression(data);\n const parsed = unwrapSnapshotWithIndexDefinitions(decompressed);\n await this.runGenerationOperation('import', parsed);\n }\n async reset(): Promise<void> {\n const dbName = this.dbName;\n if (!dbName) {\n throw remoteError('InternalError', 'engine is not open');\n }\n const defs = cloneNormalizedIndexDefinitions(this.loadCommittedIndexSchema());\n this.rollbackAllTransactions();\n const stores: StoreChangeSet[] = this.currentStoreNames().map((store) => ({\n store,\n changes: [{ key: new Uint8Array(0), kind: 'clear' }]\n }));\n const txid = fromWasmU64(this.withEngine((engine) => engine.reset()));\n this.committedIndexes = [];\n await this.applyCommittedIndexSchema(defs);\n if (this.events) {\n const event: CommitAppliedEvent = {\n type: 'commit_applied',\n dbName,\n txid,\n stores\n };\n this.events.postMessage(event);\n }\n }\n async compact(): Promise<CompactionResult> {\n return this.runGenerationOperation('compact');\n }\n async rebuild(): Promise<CompactionResult> {\n return this.runGenerationOperation('rebuild');\n }\n stats(): Promise<DbStats> {\n const stats = this.withEngine((engine) => engine.stats()) as WasmDbStats;\n return Promise.resolve({\n ...stats,\n db_id: typeof stats.db_id === 'bigint' ? Number(stats.db_id) : stats.db_id,\n catalog_root_page_id: fromWasmU64(stats.catalog_root_page_id),\n next_page_id: fromWasmU64(stats.next_page_id),\n last_committed_txid: fromWasmU64(stats.last_committed_txid),\n last_replayed_wal_offset: fromWasmU64(stats.last_replayed_wal_offset),\n manifest_len: fromWasmU64(stats.manifest_len),\n main_len: fromWasmU64(stats.main_len),\n wal_len: fromWasmU64(stats.wal_len),\n health: normalizeEngineHealth(stats.health),\n store_count: this.currentStoreNames().length\n });\n }\n async storageInfo(): Promise<StorageInfo> {\n const [dbSize, estimate, persisted] = await Promise.all([\n this.dbDirectorySize(),\n estimateOriginStorage(),\n this.persistenceBridge.persisted()\n ]);\n return {\n dbSize,\n originUsage: estimate.usage,\n originQuota: estimate.quota,\n persisted\n };\n }\n async requestPersistence(): Promise<boolean> {\n return this.persistenceBridge.persist();\n }\n setFailpoint(failpoint: DebugFailpoint): Promise<void> {\n this.withEngine((engine) => engine.set_failpoint(failpoint));\n return Promise.resolve();\n }\n private requireDbName(): string {\n if (!this.dbName) {\n throw remoteError('InternalError', 'engine is not open');\n }\n return this.dbName;\n }\n private ensureNotInMaintenance(): void {\n if (!this.maintenanceOperation) {\n return;\n }\n const dbName = this.dbName ?? 'database';\n throw remoteError('DatabaseBusyError', `database ${dbName} is busy: ${this.maintenanceOperation} in progress`);\n }\n private currentCachePages(): number {\n return this.openOptions?.cachePages ?? 256;\n }\n private async dbDirectorySize(): Promise<number> {\n const wasm = await this.loadWasm();\n return wasm.dbDirectorySize(this.requireDbName());\n }\n private async applyCommittedIndexSchema(defs: ReadonlyArray<NormalizedIndexDef>): Promise<void> {\n const normalized = cloneNormalizedIndexDefinitions(defs);\n if (normalized.length === 0) {\n this.committedIndexes = [];\n return;\n }\n const txId = fromWasmU64(\n this.withEngine((engine) => engine.begin_tx('readwrite'), { allowDuringMaintenance: true })\n );\n this.txChanges.set(txId, new Map());\n this.txModes.set(txId, 'readwrite');\n this.txStoreCompression.set(txId, { owned: false, values: this.loadCommittedStoreCompression() });\n try {\n await this.reconcileIndexes(txId, toPublicIndexDefinitions(normalized));\n fromWasmU64(\n this.withEngine((engine) => engine.commit_tx(toWasmU64(txId)), { allowDuringMaintenance: true })\n );\n this.committedIndexes = cloneNormalizedIndexDefinitions(normalized);\n } catch (error) {\n try {\n this.withEngine((engine) => engine.rollback_tx(toWasmU64(txId)), { allowDuringMaintenance: true });\n } catch {}\n throw error;\n } finally {\n this.cleanupTxState(txId);\n }\n }\n /**\n * Publishes a fresh generation only if the active generation has not changed.\n * A failed swap may have reached storage; read the control file before cleanup.\n * After publication, abandon the old engine to avoid a checkpoint into inactive files.\n */\n private async runGenerationOperation(\n operation: MaintenanceOperation,\n imported?: { snapshot: Uint8Array; indexes: NormalizedIndexDef[] }\n ): Promise<CompactionResult> {\n const dbName = this.requireDbName();\n if (this.maintenanceOperation) {\n throw remoteError(\n 'DatabaseBusyError',\n `database ${dbName} is busy: ${this.maintenanceOperation} in progress`\n );\n }\n this.maintenanceOperation = operation;\n const start = performance.now();\n let wasm: WasmModule | null = null;\n let rebuiltEngine: WasmEngine | null = null;\n let generationName: string | null = null;\n let published = false;\n try {\n wasm = await this.loadWasm();\n const sizeBefore = await wasm.dbDirectorySize(dbName);\n const defs = cloneNormalizedIndexDefinitions(imported?.indexes ?? this.loadCommittedIndexSchema());\n this.rollbackAllTransactions({ allowDuringMaintenance: true });\n const expectedGeneration = await wasm.readActiveGeneration(dbName);\n generationName = (await wasm.prepareRebuildTarget(dbName)).generationName;\n rebuiltEngine = new wasm.WasmEngine();\n await rebuiltEngine.openGeneration(dbName, generationName, {\n create_if_missing: true,\n cache_pages: this.currentCachePages()\n });\n const target = rebuiltEngine;\n this.withEngine(\n (engine) =>\n imported\n ? fromWasmU64(engine.import_snapshot_into(target, imported.snapshot))\n : operation === 'rebuild'\n ? engine.compact_into_skipping_stores(target, [\n ...defs.map((def) => def.internalStore),\n INDEX_METADATA_STORE\n ])\n : engine.compact_into(target),\n { allowDuringMaintenance: true }\n );\n if ((operation === 'rebuild' || imported) && defs.length > 0) {\n // Regenerate managed indexes before activating the target generation.\n const previousEngine = this.engine;\n const previousMaintenance = this.maintenanceOperation;\n this.engine = target;\n this.maintenanceOperation = null;\n try {\n this.committedIndexes = [];\n this.committedStoreCompression = null;\n await this.applyCommittedIndexSchema(defs);\n } finally {\n this.engine = previousEngine;\n this.maintenanceOperation = previousMaintenance;\n this.committedStoreCompression = null;\n }\n }\n try {\n await wasm.swapActiveGeneration(dbName, generationName, expectedGeneration);\n published = true;\n } catch (swapError) {\n published = (await readActiveGenerationOrNull(wasm, dbName)) === generationName;\n if (!published) {\n throw swapError;\n }\n }\n const previousEngine = this.engine;\n this.engine = rebuiltEngine;\n rebuiltEngine = null;\n this.committedIndexes = defs;\n this.committedStoreCompression = null;\n try {\n previousEngine?.abandon();\n } catch {}\n try {\n await wasm.cleanupInactiveEntries(dbName);\n } catch {}\n const sizeAfter = imported ? sizeBefore : await wasm.dbDirectorySize(dbName);\n return {\n sizeBefore,\n sizeAfter,\n reclaimedBytes: Math.max(0, sizeBefore - sizeAfter),\n durationMs: performance.now() - start\n };\n } catch (error) {\n if (!published) {\n this.committedIndexes = null;\n this.committedStoreCompression = null;\n try {\n rebuiltEngine?.abandon();\n } catch {}\n if (generationName !== null && wasm !== null) {\n // Cleanup requires proof that the target generation is inactive.\n const active = await readActiveGenerationOrNull(wasm, dbName);\n if (active !== undefined && active !== generationName) {\n try {\n await wasm.cleanupInactiveEntries(dbName);\n } catch {}\n }\n }\n }\n throw remapError(error);\n } finally {\n this.maintenanceOperation = null;\n }\n }\n /**\n * Returns null when no recovery is needed. A recovery attempt invalidates\n * all open transactions, even if recovery fails.\n */\n private recoverEngineIfNeeded(): { pendingTxid: number | null; pendingCommitted: boolean } | null {\n const engine = this.engine;\n if (!engine || !engine.needs_recovery()) {\n return null;\n }\n let report: WasmRecoveryReport;\n try {\n report = engine.recover();\n } catch (error) {\n throw remoteError(\n 'RecoveryRequiredError',\n `database ${this.dbName ?? ''} needs recovery and recovery failed: ${remapError(error).message}`\n );\n } finally {\n // Engine recovery discards transactions before storage I/O can fail.\n this.clearRuntimeCaches();\n }\n return {\n pendingTxid: fromOptionalWasmU64(report.pendingTxid),\n pendingCommitted: report.pendingCommitted === true\n };\n }\n private cleanupTxState(txId: number): void {\n for (const [cursorId, cursor] of this.primaryCursors) {\n if (cursor.txId === txId) {\n this.primaryCursors.delete(cursorId);\n try {\n this.engine?.close_scan_cursor(cursor.engineId);\n } catch {}\n }\n }\n this.txChanges.delete(txId);\n this.txModes.delete(txId);\n this.txIndexSchemas.delete(txId);\n this.readonlyIndexCache.delete(txId);\n this.txEnsuredRawStores.delete(txId);\n this.txIndexSchemaChanged.delete(txId);\n this.txStoreCompression.delete(txId);\n if (this.indexBoundCache?.txId === txId) {\n this.indexBoundCache = null;\n }\n }\n private getOrCreateTrackedTxn(txId: number): TrackedTxnChanges {\n return getOrInsert(this.txChanges, txId, () => new Map<string, TrackedStoreChanges>());\n }\n private getOrCreateTrackedStore(txId: number, store: string): TrackedStoreChanges {\n return getOrInsert(this.getOrCreateTrackedTxn(txId), store, () => ({\n touched: false,\n storeLevel: null,\n keys: new Map()\n }));\n }\n private recordStoreLevelChange(txId: number, store: string, kind: 'clear' | 'drop'): void {\n if (isInternalStoreName(store)) {\n return;\n }\n const trackedStore = this.getOrCreateTrackedStore(txId, store);\n trackedStore.touched = true;\n trackedStore.storeLevel = kind;\n // The clear/drop event replaces earlier key changes.\n trackedStore.keys.clear();\n }\n private recordPutChange(txId: number, store: string, key: Uint8Array, baselineExists: boolean): void {\n this.recordKeyChange(txId, store, key, baselineExists, 'put');\n }\n private recordPutChanges(\n txId: number,\n store: string,\n entries: Array<[Uint8Array, Uint8Array]>,\n baselines: boolean[]\n ): void {\n if (isInternalStoreName(store)) {\n return;\n }\n const trackedStore = this.getOrCreateTrackedStore(txId, store);\n trackedStore.touched = true;\n const count = Math.min(entries.length, baselines.length);\n for (let i = 0; i < count; i += 1) {\n this.setTrackedKeyChange(trackedStore, entries[i][0], baselines[i], 'put');\n }\n }\n private recordPutKeyChanges(\n txId: number,\n store: string,\n keys: Uint8Array[],\n baselines: ArrayLike<boolean | number>\n ): void {\n if (isInternalStoreName(store)) {\n return;\n }\n const trackedStore = this.getOrCreateTrackedStore(txId, store);\n trackedStore.touched = true;\n const count = Math.min(keys.length, baselines.length);\n for (let i = 0; i < count; i += 1) {\n this.setTrackedKeyChange(trackedStore, keys[i], baselines[i] === true || baselines[i] === 1, 'put');\n }\n }\n private recordDeleteChange(txId: number, store: string, key: Uint8Array, deleted: boolean): void {\n if (deleted) {\n this.recordKeyChange(txId, store, key, true, 'delete');\n }\n }\n private recordKeyChange(\n txId: number,\n store: string,\n key: Uint8Array,\n baselineExists: boolean,\n finalKind: DbChange['kind']\n ): void {\n if (isInternalStoreName(store)) {\n return;\n }\n const trackedStore = this.getOrCreateTrackedStore(txId, store);\n trackedStore.touched = true;\n this.setTrackedKeyChange(trackedStore, key, baselineExists, finalKind);\n }\n private setTrackedKeyChange(\n trackedStore: TrackedStoreChanges,\n key: Uint8Array,\n baselineExists: boolean,\n finalKind: DbChange['kind']\n ): void {\n const keyId = bytesToHex(key);\n const existing = trackedStore.keys.get(keyId);\n trackedStore.keys.set(keyId, {\n key: existing?.key ?? key.slice(),\n baselineExists: existing?.baselineExists ?? baselineExists,\n finalKind\n });\n }\n private markStoreTouched(txId: number, store: string): void {\n if (isInternalStoreName(store)) {\n return;\n }\n this.getOrCreateTrackedStore(txId, store).touched = true;\n }\n private recordBatchOutcomes(\n txId: number,\n store: string,\n ops: ReadonlyArray<BatchOp | PackedBatchOpKey>,\n outcomes: Array<WasmBatchOutcome>\n ): void {\n for (let i = 0; i < outcomes.length && i < ops.length; i += 1) {\n const op = ops[i];\n const outcome = outcomes[i];\n if (op.kind === 'put' && outcome.kind === 'put') {\n this.recordPutChange(txId, store, op.key, outcome.baselineExists);\n } else if (op.kind === 'delete' && outcome.kind === 'delete') {\n this.recordDeleteChange(txId, store, op.key, outcome.deleted);\n }\n }\n }\n private finalizeTrackedChanges(tracked: TrackedTxnChanges): StoreChangeSet[] {\n const stores: StoreChangeSet[] = [];\n for (const [store, trackedStore] of tracked) {\n if (!trackedStore.touched || isInternalStoreName(store)) {\n continue;\n }\n const changes: DbChange[] = [];\n if (trackedStore.storeLevel !== null) {\n changes.push({ key: new Uint8Array(0), kind: trackedStore.storeLevel });\n }\n for (const change of trackedStore.keys.values()) {\n if (change.finalKind === 'delete' && !change.baselineExists) {\n continue;\n }\n changes.push({\n key: change.key,\n kind: change.finalKind\n });\n }\n stores.push({ store, changes });\n }\n return stores;\n }\n private rollbackAllTransactions(\n options: {\n allowDuringMaintenance?: boolean;\n } = {}\n ): void {\n if (!this.engine || this.txChanges.size === 0) {\n this.clearTxCaches();\n return;\n }\n const txIds = Array.from(this.txChanges.keys());\n for (const txId of txIds) {\n try {\n this.withEngine((engine) => engine.rollback_tx(toWasmU64(txId)), options);\n } finally {\n this.cleanupTxState(txId);\n }\n }\n }\n private currentStoreNames(): string[] {\n return this.allRawStoreNames().filter((store) => !isInternalStoreName(store));\n }\n private allRawStoreNames(): string[] {\n return this.withEngine((engine) => engine.list_stores()) as string[];\n }\n private loadCommittedStoreCompression(): ReadonlyMap<string, CompressionOption> {\n if (this.committedStoreCompression) {\n return this.committedStoreCompression;\n }\n const rows = this.withEngine((engine) => engine.list_store_configs()) as Array<{\n name: string;\n flags: number | bigint;\n }>;\n const loaded = new Map<string, CompressionOption>();\n for (const row of rows) {\n if (typeof row.name !== 'string') {\n throw remoteError('CorruptionError', 'invalid store config row: missing name');\n }\n const flags = typeof row.flags === 'bigint' ? Number(row.flags) : row.flags;\n if (typeof flags !== 'number' || !Number.isSafeInteger(flags) || flags < 0) {\n throw remoteError('CorruptionError', `invalid store flags for ${row.name}`);\n }\n loaded.set(row.name, compressionFromStoreFlags(flags));\n }\n this.committedStoreCompression = loaded;\n return loaded;\n }\n private ensureTxStoreCompression(txId: number): Map<string, CompressionOption> {\n const snapshot = this.txStoreCompression.get(txId);\n if (snapshot?.owned) {\n return snapshot.values;\n }\n const values = new Map(snapshot?.values);\n this.txStoreCompression.set(txId, { owned: true, values });\n return values;\n }\n private recordStoreCompressionCreate(txId: number, store: string, compression: CompressionOption): void {\n if (isInternalStoreName(store)) {\n return;\n }\n this.ensureTxStoreCompression(txId).set(store, compression);\n }\n private recordStoreCompressionDrop(txId: number, store: string): void {\n if (isInternalStoreName(store)) {\n return;\n }\n this.ensureTxStoreCompression(txId).delete(store);\n }\n private storeCompressionForTx(txId: number, store: string): CompressionOption {\n if (isInternalStoreName(store)) {\n return false;\n }\n const snapshot = this.txStoreCompression.get(txId);\n if (snapshot) {\n return snapshot.values.get(store) ?? false;\n }\n return this.loadCommittedStoreCompression().get(store) ?? false;\n }\n private async encodeEntriesForWrite(\n txId: number,\n store: string,\n entries: Array<[Uint8Array, Uint8Array]>\n ): Promise<Array<[Uint8Array, Uint8Array]>> {\n if (isInternalStoreName(store)) {\n return entries;\n }\n const compression = this.storeCompressionForTx(txId, store);\n if (compression === false) {\n return entries;\n }\n const storedEntries: Array<[Uint8Array, Uint8Array]> = [];\n for (const [key, value] of entries) {\n storedEntries.push([key, await encodeStoreValueRecord(value, compression)]);\n }\n return storedEntries;\n }\n private async encodePackedEntriesForWrite(\n txId: number,\n store: string,\n items: Uint8Array[],\n keys: Uint8Array[]\n ): Promise<Uint8Array> {\n const records = new Array<PreparedPutValue>(items.length / 2);\n for (let index = 0; index < records.length; index += 1) {\n const value = this.preparePutValue(txId, store, items[index * 2 + 1]);\n records[index] = value instanceof Promise ? await value : value;\n }\n return this.packPreparedPutEntries(keys, records);\n }\n private preparePutValue(txId: number, store: string, value: Uint8Array): PreparedPutValue | Promise<Uint8Array> {\n const compression = this.storeCompressionForTx(txId, store);\n return compression === 'snappy' || compression === false\n ? prepareFastStoreValueRecord(value, compression)\n : encodeStoreValueRecord(value, compression);\n }\n private packPreparedPutEntries(keys: Uint8Array[], records: PreparedPutValue[]): Uint8Array {\n let total = 4 + keys.length * 8;\n for (let index = 0; index < keys.length; index += 1) {\n total += keys[index].byteLength + records[index].byteLength;\n if (total > MAX_PACKED_BYTES) {\n throw remoteError('WorkerProtocolError', 'compressed packed putMany exceeds the u32 byte limit');\n }\n }\n const bytes = new Uint8Array(total);\n const view = new DataView(bytes.buffer);\n view.setUint32(0, keys.length * 2, true);\n let offset = 4 + keys.length * 8;\n for (let index = 0; index < records.length; index += 1) {\n const key = keys[index];\n const record = records[index];\n view.setUint32(4 + index * 8, key.byteLength, true);\n view.setUint32(8 + index * 8, record.byteLength, true);\n bytes.set(key, offset);\n offset += key.byteLength;\n if (record instanceof Uint8Array) {\n bytes.set(record, offset);\n offset += record.byteLength;\n } else {\n offset = writePreparedStoreValueRecord(record, bytes, offset);\n }\n }\n return bytes;\n }\n private async putIndexedMany(\n txId: number,\n store: string,\n items: Uint8Array[],\n defs: readonly NormalizedIndexDef[],\n options: PutOptions\n ): Promise<void> {\n let keys: Uint8Array[] = [];\n let values: PreparedPutValue[] = [];\n let indexOps: IndexedPutOp[][] = [];\n let bytes = 4;\n const pendingPrimaries = new Set<string>();\n const pendingUniqueKeys = new Set<string>();\n const flush = (): void => {\n if (keys.length === 0) {\n return;\n }\n const batchKeys = keys;\n const batchValues = values;\n const batchOps = indexOps;\n // Detach the plan so a failed flush cannot be retried by the error handler.\n keys = [];\n values = [];\n indexOps = [];\n bytes = 4;\n pendingPrimaries.clear();\n pendingUniqueKeys.clear();\n const packet = this.packPreparedPutEntries(batchKeys, batchValues);\n let baselines: Uint8Array;\n try {\n baselines = this.withEngine((engine) =>\n engine.put_many_indexed_packed(toWasmU64(txId), store, packet, batchOps, toWasmPutOptions(options))\n );\n } catch (error) {\n const partial = partialBooleanOutcomes(error);\n if (partial.length > 0) {\n this.recordPutKeyChanges(txId, store, batchKeys, partial);\n }\n throw error;\n }\n if (baselines.length !== batchKeys.length) {\n throw remoteError(\n 'InternalError',\n `put_many_indexed_packed outcome count mismatch: ${baselines.length} != ${batchKeys.length}`\n );\n }\n this.recordPutKeyChanges(txId, store, batchKeys, baselines);\n };\n for (let index = 0; index < items.length / 2; index += 1) {\n const key = items[index * 2];\n const value = items[index * 2 + 1];\n const primaryToken = bytesToHex(key);\n if (pendingPrimaries.has(primaryToken)) {\n flush();\n }\n try {\n const oldValue = await this.readStoreValue(txId, store, key);\n const oldKeyFor = oldValue === null ? null : createIndexKeyExtractor(oldValue);\n const newKeyFor = createIndexKeyExtractor(value);\n const plans = defs.map((def) => ({\n def,\n oldLogicalKey: oldKeyFor === null ? null : oldKeyFor(def),\n newLogicalKey: newKeyFor(def),\n newPhysicalKey: null as Uint8Array | null\n }));\n if (\n plans.some(\n (plan) =>\n plan.def.unique &&\n plan.newLogicalKey !== null &&\n pendingUniqueKeys.has(`${plan.def.internalStore}:${bytesToHex(plan.newLogicalKey)}`)\n )\n ) {\n // Reused unique keys must observe all earlier primary and index writes.\n flush();\n index -= 1;\n continue;\n }\n this.ensureInternalStoresForDefinitions(txId, defs);\n for (const plan of plans) {\n if (plan.newLogicalKey === null) {\n continue;\n }\n plan.newPhysicalKey = this.buildIndexEntryKey(plan.def, plan.newLogicalKey, key);\n if (plan.oldLogicalKey === null || !bytesEqual(plan.oldLogicalKey, plan.newLogicalKey)) {\n await this.assertUniqueIndexAvailability(txId, plan.def, plan.newLogicalKey, key);\n }\n }\n const preparedValue = this.preparePutValue(txId, store, value);\n const storedValue = preparedValue instanceof Promise ? await preparedValue : preparedValue;\n const ops: IndexedPutOp[] = [];\n for (const plan of plans) {\n if (\n plan.oldLogicalKey !== null &&\n (plan.newLogicalKey === null || !bytesEqual(plan.oldLogicalKey, plan.newLogicalKey))\n ) {\n ops.push({\n store: plan.def.internalStore,\n kind: 'delete',\n key: encodeIndexEntryKey(plan.oldLogicalKey, key)\n });\n }\n }\n for (const plan of plans) {\n if (plan.newPhysicalKey !== null) {\n ops.push({ store: plan.def.internalStore, kind: 'put', key: plan.newPhysicalKey });\n }\n if (plan.def.unique) {\n for (const logicalKey of [plan.oldLogicalKey, plan.newLogicalKey]) {\n if (logicalKey !== null) {\n pendingUniqueKeys.add(`${plan.def.internalStore}:${bytesToHex(logicalKey)}`);\n }\n }\n }\n }\n keys.push(key);\n values.push(storedValue);\n indexOps.push(ops);\n bytes += 8 + key.byteLength + storedValue.byteLength;\n for (const op of ops) {\n bytes += op.key.byteLength;\n }\n pendingPrimaries.add(primaryToken);\n } catch (error) {\n flush();\n throw error;\n }\n if (options.ttl !== undefined || keys.length >= INDEX_PUT_BATCH_ROWS || bytes >= INDEX_PUT_BATCH_BYTES) {\n flush();\n }\n }\n flush();\n }\n private async encodeBatchOpsForWrite(txId: number, store: string, ops: Array<BatchOp>): Promise<Array<BatchOp>> {\n if (isInternalStoreName(store)) {\n return ops;\n }\n const compression = this.storeCompressionForTx(txId, store);\n if (compression === false) {\n return ops;\n }\n const storedOps: Array<BatchOp> = [];\n for (const op of ops) {\n storedOps.push(\n op.kind === 'put'\n ? { kind: 'put', key: op.key, value: await encodeStoreValueRecord(op.value, compression) }\n : op\n );\n }\n return storedOps;\n }\n private prepareStoredValue(\n store: string,\n value: Uint8Array,\n compression: CompressionOption\n ): Uint8Array | Promise<Uint8Array> {\n if (isInternalStoreName(store)) {\n return value;\n }\n if (compression === false) {\n return limitPlainStoreValue(value);\n }\n return encodeStoreValueRecord(value, compression);\n }\n private async decodeStoreValueForFeed(store: string, value: Uint8Array): Promise<Uint8Array> {\n if (isInternalStoreName(store)) {\n return value;\n }\n const compression = this.loadCommittedStoreCompression().get(store) ?? false;\n return decodeStoreValueRecord(value, { strict: compression !== false });\n }\n private async readStoreValue(\n txId: number,\n store: string,\n key: Uint8Array,\n knownCompression?: CompressionOption\n ): Promise<Uint8Array | null> {\n const value = this.readRawValue(txId, store, key);\n if (value === null || isInternalStoreName(store)) {\n return value;\n }\n const compression = knownCompression ?? this.storeCompressionForTx(txId, store);\n if (compression === false) {\n return value;\n }\n return await decodeStoreValueRecord(value, { strict: true });\n }\n private async readStoreScan(txId: number, store: string, range: Range): Promise<ScanItem[]> {\n const rows = this.readRawScan(txId, store, range);\n if (isInternalStoreName(store) || this.storeCompressionForTx(txId, store) === false) {\n return rows;\n }\n const values = rows.map((row) => row.value);\n await this.decodeStoreValues(txId, store, values);\n for (let index = 0; index < rows.length; index += 1) {\n rows[index].value = values[index];\n }\n return rows;\n }\n private async decodeStoreValues(\n _txId: number,\n _store: string,\n values: Array<Uint8Array | null>\n ): Promise<Array<Uint8Array | null>> {\n const state = { next: 0, failed: false, failure: undefined as unknown };\n const decodeNext = async (): Promise<void> => {\n while (!state.failed && state.next < values.length) {\n const index = state.next++;\n const value = values[index];\n if (value === null) {\n continue;\n }\n try {\n values[index] = await decodeStoreValueRecord(value, { strict: true });\n } catch (error) {\n if (!state.failed) {\n state.failed = true;\n state.failure = error;\n }\n }\n }\n };\n // Drain active decoders before reporting the first observed failure.\n await Promise.all(Array.from({ length: Math.min(COMPRESSED_READ_CONCURRENCY, values.length) }, decodeNext));\n if (state.failed) {\n throw state.failure;\n }\n return values;\n }\n private indexesForStoreInTx(txId: number, store: string): NormalizedIndexDef[] {\n // Cache by immutable schema array so readers keep their original lookup\n // after another transaction publishes a replacement.\n const schema = this.indexSchemaForTx(txId);\n let byStore = this.indexesBySchema.get(schema);\n if (!byStore) {\n byStore = new Map<string, NormalizedIndexDef[]>();\n for (const def of schema) {\n const defs = byStore.get(def.store);\n if (defs) {\n defs.push(def);\n } else {\n byStore.set(def.store, [def]);\n }\n }\n this.indexesBySchema.set(schema, byStore);\n }\n return byStore.get(store) ?? [];\n }\n private resolveIndexDefinition(txId: number, store: string, indexName: string): NormalizedIndexDef {\n // Readwrite existence checks also stage expired mutations. Readonly\n // snapshots do not, so later scans of the same index can reuse the def.\n if (this.txModes.get(txId) === 'readonly') {\n const byStore = this.readonlyIndexCache.get(txId)?.get(store);\n if (byStore) {\n const cached = byStore.get(indexName);\n if (cached) {\n return cached;\n }\n const def = findIndexDefinition(this.indexesForStoreInTx(txId, store), store, indexName);\n if (!def) {\n throw remoteError('IndexNotFoundError', `index not found: ${store}.${indexName}`);\n }\n byStore.set(indexName, def);\n return def;\n }\n }\n if (!this.rawStoreExistsInTx(txId, store)) {\n throw remoteError('StoreNotFoundError', `store not found: ${store}`);\n }\n const def = findIndexDefinition(this.indexesForStoreInTx(txId, store), store, indexName);\n if (!def) {\n throw remoteError('IndexNotFoundError', `index not found: ${store}.${indexName}`);\n }\n if (this.txModes.get(txId) === 'readonly') {\n const byStore = getOrInsert(this.readonlyIndexCache, txId, () => new Map());\n getOrInsert(byStore, store, () => new Map()).set(indexName, def);\n }\n return def;\n }\n private physicalIndexRange(txId: number, def: NormalizedIndexDef, range: Range): Range {\n assertValidScanRange(range);\n const reverse = range.reverse === true;\n const cached = this.indexBoundCache;\n if (\n cached !== null &&\n cached.txId === txId &&\n cached.def === def &&\n cached.reverse === reverse &&\n sameBound(cached.gt, range.gt) &&\n sameBound(cached.gte, range.gte) &&\n sameBound(cached.lt, range.lt) &&\n sameBound(cached.lte, range.lte)\n ) {\n return cached.physical;\n }\n const { limit: _ignored, ...withoutLimit } = range;\n const physical = indexRangeToPhysicalRange(withoutLimit);\n this.indexBoundCache = {\n txId,\n def,\n reverse,\n gt: copyBound(range.gt),\n gte: copyBound(range.gte),\n lt: copyBound(range.lt),\n lte: copyBound(range.lte),\n physical\n };\n return physical;\n }\n private indexSchemaForTx(txId: number): NormalizedIndexDef[] {\n const override = this.txIndexSchemas.get(txId);\n if (override) {\n return override;\n }\n if (this.committedIndexes) {\n return this.committedIndexes;\n }\n const loaded = this.readIndexSchemaInTx(txId);\n this.committedIndexes = cloneNormalizedIndexDefinitions(loaded);\n return this.committedIndexes;\n }\n private loadCommittedIndexSchema(): NormalizedIndexDef[] {\n if (this.committedIndexes) {\n return this.committedIndexes;\n }\n const txId = fromWasmU64(this.withEngine((engine) => engine.begin_tx('readonly')));\n try {\n const loaded = this.readIndexSchemaInTx(txId);\n this.committedIndexes = cloneNormalizedIndexDefinitions(loaded);\n return this.committedIndexes;\n } finally {\n this.withEngine((engine) => engine.rollback_tx(toWasmU64(txId)));\n }\n }\n private readIndexSchemaInTx(txId: number): NormalizedIndexDef[] {\n if (!this.rawStoreExistsInTx(txId, INDEX_METADATA_STORE)) {\n return [];\n }\n const rows = this.readRawScan(txId, INDEX_METADATA_STORE, EMPTY_RANGE);\n const defs = rows.map((row) => decodeIndexMetadataValue(row.value));\n defs.sort(compareNormalizedIndexDefinitions);\n return defs;\n }\n private rawStoreExistsInTx(txId: number, store: string): boolean {\n try {\n this.readRawScan(txId, store, { limit: 0 });\n return true;\n } catch (error) {\n if (isNamedError(error, 'StoreNotFoundError')) {\n return false;\n }\n throw error;\n }\n }\n private ensureRawStore(txId: number, store: string): void {\n const cacheable = this.txModes.get(txId) === 'readwrite';\n if (cacheable && this.txEnsuredRawStores.get(txId)?.has(store)) {\n return;\n }\n this.ignoreNamedError('StoreExistsError', () => {\n this.withEngine((engine) => engine.create_store(toWasmU64(txId), store));\n });\n if (cacheable) {\n getOrInsert(this.txEnsuredRawStores, txId, () => new Set<string>()).add(store);\n }\n }\n private clearRawStoreIfExists(txId: number, store: string): void {\n try {\n this.withEngine((engine) => engine.clear_store(toWasmU64(txId), store));\n } catch (error) {\n if (!isNamedError(error, 'StoreNotFoundError')) {\n throw error;\n }\n this.txEnsuredRawStores.get(txId)?.delete(store);\n }\n }\n private dropRawStoreIfExists(txId: number, store: string): void {\n this.txEnsuredRawStores.get(txId)?.delete(store);\n this.ignoreNamedError('StoreNotFoundError', () => {\n this.withEngine((engine) => engine.drop_store(toWasmU64(txId), store));\n });\n }\n private ensureInternalStoresForDefinitions(txId: number, defs: ReadonlyArray<NormalizedIndexDef>): void {\n for (const def of defs) {\n this.ensureRawStore(txId, def.internalStore);\n }\n }\n private ensureInternalStoresForStore(txId: number, store: string): void {\n this.ensureInternalStoresForDefinitions(txId, this.indexesForStoreInTx(txId, store));\n }\n private readRawValue(txId: number, store: string, key: Uint8Array): Uint8Array | null {\n const value = this.withEngine((engine) => engine.get(toWasmU64(txId), store, key));\n return value === null ? null : normalizeWasmBytes(value);\n }\n private readRawScan(txId: number, store: string, range: Range): ScanItem[] {\n const rows = this.withEngine((engine) => engine.scan(toWasmU64(txId), store, toWasmRange(range))) as ScanItem[];\n // The binding returns a fresh array and row objects, so normalization\n // can update them without affecting another caller.\n for (const row of rows) {\n row.key = normalizeWasmBytes(row.key);\n row.value = normalizeWasmBytes(row.value);\n }\n return rows;\n }\n private readIndexKeyScan(txId: number, store: string, range: Range): ScanItem[] {\n if (\n typeof this.engine?.open_scan_cursor !== 'function' ||\n typeof this.engine?.scan_cursor_next !== 'function' ||\n typeof this.engine?.close_scan_cursor !== 'function'\n ) {\n return this.readRawScan(txId, store, range);\n }\n const maxRows = range.limit ?? INDEX_SCAN_RAW_CHUNK_ROWS;\n const maxBytes = 4 + maxRows * (8 + MAX_ENGINE_KEY_BYTES);\n const cursorId = this.withEngine((engine) =>\n engine.open_scan_cursor(toWasmU64(txId), store, toWasmRange(range), true)\n );\n try {\n const page = this.withEngine((engine) => engine.scan_cursor_next(cursorId, maxRows, maxBytes));\n const packet = normalizeWasmBytes(page.packet);\n const rows = unpackPackedScanRows(packet);\n if (\n rows.length !== page.rowCount ||\n rows.length > maxRows ||\n packet.byteLength > maxBytes ||\n rows.some((row) => row.value.byteLength !== 0)\n ) {\n throw remoteError('CorruptionError', 'index key cursor returned an invalid page');\n }\n return rows;\n } finally {\n this.withEngine((engine) => engine.close_scan_cursor(cursorId));\n }\n }\n private putRawValue(txId: number, store: string, key: Uint8Array, value: Uint8Array): void {\n this.withEngine((engine) => engine.put(toWasmU64(txId), store, key, value));\n }\n private putIndexEntry(txId: number, def: NormalizedIndexDef, physicalKey: Uint8Array, value: Uint8Array): void {\n if (typeof this.engine?.put_index_entry_checked === 'function') {\n const primaryKey = decodeIndexEntryKey(physicalKey).primaryKey;\n const state = this.readNativeValueState(txId, def.store, primaryKey);\n if (state?.revisionKnown) {\n this.withEngine((engine) =>\n engine.put_index_entry_checked!(\n toWasmU64(txId),\n def.store,\n def.internalStore,\n primaryKey,\n physicalKey,\n state.revisionEpoch,\n state.revisionOrdinal\n )\n );\n return;\n }\n }\n this.putRawValue(txId, def.internalStore, physicalKey, value);\n }\n private readNativeValueState(txId: number, store: string, key: Uint8Array): NativeValueState | null {\n if (typeof this.engine?.get_many_value_states !== 'function') {\n return null;\n }\n try {\n const keys = new Uint8Array(8 + key.byteLength);\n const keyView = new DataView(keys.buffer);\n keyView.setUint32(0, 1, true);\n keyView.setUint32(4, key.byteLength, true);\n keys.set(key, 8);\n const packet = normalizeWasmBytes(\n this.withEngine((engine) => engine.get_many_value_states!(toWasmU64(txId), store, keys))\n );\n return this.decodeNativeValueStates(packet, 1)?.[0] ?? null;\n } catch {\n return null;\n }\n }\n private packNativeKeys(keys: Uint8Array[]): Uint8Array {\n let total = 4 + keys.length * 4;\n for (const key of keys) {\n total += key.byteLength;\n }\n const packet = new Uint8Array(total);\n const view = new DataView(packet.buffer);\n view.setUint32(0, keys.length, true);\n let offset = 4 + keys.length * 4;\n for (let index = 0; index < keys.length; index += 1) {\n const key = keys[index];\n view.setUint32(4 + index * 4, key.byteLength, true);\n packet.set(key, offset);\n offset += key.byteLength;\n }\n return packet;\n }\n private decodeNativeValueStates(packet: Uint8Array, count: number): NativeValueState[] | null {\n if (packet.byteLength !== 4 + count * 32) {\n return null;\n }\n const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);\n if (view.getUint32(0, true) !== count) {\n return null;\n }\n const states = new Array<NativeValueState>(count);\n for (let index = 0; index < count; index += 1) {\n const offset = 4 + index * 32;\n const flags = view.getUint32(offset, true);\n const revisionEpoch = view.getBigUint64(offset + 12, true);\n const revisionOrdinal = view.getBigUint64(offset + 20, true);\n if (\n (flags & ~7) !== 0 ||\n (flags & 3) === 3 ||\n ((flags & 4) !== 0 && ((flags & 3) === 0 || revisionEpoch === 0n || revisionOrdinal === 0n))\n ) {\n return null;\n }\n states[index] = {\n live: (flags & 1) !== 0,\n expired: (flags & 2) !== 0,\n revisionKnown: (flags & 4) !== 0,\n expiresAt: view.getBigUint64(offset + 4, true),\n revisionEpoch,\n revisionOrdinal,\n maxValueBytes: view.getUint32(offset + 28, true)\n };\n }\n return states;\n }\n private inspectIndexedValue(\n txId: number,\n def: NormalizedIndexDef,\n physicalKey: Uint8Array,\n primaryKey: Uint8Array\n ): 'missing' | 'trusted' | 'unknown' {\n const primary = this.readNativeValueState(txId, def.store, primaryKey);\n if (primary === null) {\n return 'unknown';\n }\n if (!primary.live) {\n if (primary.expired && this.txModes.get(txId) === 'readwrite') {\n const live = this.withEngine((engine) => engine.has(toWasmU64(txId), def.store, primaryKey));\n if (live) {\n return 'unknown';\n }\n }\n return 'missing';\n }\n if (!primary.revisionKnown) {\n return 'unknown';\n }\n const index = this.readNativeValueState(txId, def.internalStore, physicalKey);\n // Native managed writes copy the primary revision. Raw writes receive a new revision.\n return index?.live &&\n index.revisionKnown &&\n index.revisionEpoch === primary.revisionEpoch &&\n index.revisionOrdinal === primary.revisionOrdinal\n ? 'trusted'\n : 'unknown';\n }\n private deleteIndexEntryIfPresent(\n txId: number,\n def: NormalizedIndexDef,\n logicalKey: Uint8Array,\n primaryKey: Uint8Array\n ): void {\n const physicalKey = this.buildIndexEntryKey(def, logicalKey, primaryKey);\n this.ignoreNamedError('StoreNotFoundError', () => {\n this.withEngine((engine) => engine.delete(toWasmU64(txId), def.internalStore, physicalKey));\n });\n }\n private buildIndexEntryKey(def: NormalizedIndexDef, logicalKey: Uint8Array, primaryKey: Uint8Array): Uint8Array {\n const physicalKey = encodeIndexEntryKey(logicalKey, primaryKey);\n if (physicalKey.byteLength > MAX_ENGINE_KEY_BYTES) {\n throw remoteError('KeyTooLargeError', `index key too large for ${def.store}.${def.name}`);\n }\n return physicalKey;\n }\n private assertIndexEntryKeySize(def: NormalizedIndexDef, logicalKey: Uint8Array, primaryKey: Uint8Array): void {\n if (compoundEntryKeyLength(logicalKey, primaryKey) > MAX_ENGINE_KEY_BYTES) {\n throw remoteError('KeyTooLargeError', `index key too large for ${def.store}.${def.name}`);\n }\n }\n private async assertUniqueIndexAvailability(\n txId: number,\n def: NormalizedIndexDef,\n logicalKey: Uint8Array,\n primaryKey: Uint8Array,\n knownCompression?: CompressionOption\n ): Promise<void> {\n if (!def.unique) {\n return;\n }\n const physical = indexKeyExactRange(logicalKey);\n let cursor: Uint8Array | null = null;\n let chunkLimit = 1;\n for (;;) {\n const range: Range = { ...physical, limit: chunkLimit };\n if (cursor !== null) {\n range.gt = cursor;\n delete range.gte;\n }\n // Stop at the first live conflict. Grow bounded chunks only while\n // skipping stale rows so unrelated tail errors stay unobserved.\n const rows = this.readIndexKeyScan(txId, def.internalStore, range);\n for (const row of rows) {\n cursor = row.key;\n const decoded = decodeIndexEntryKey(row.key);\n if (bytesEqual(decoded.primaryKey, primaryKey)) {\n continue;\n }\n const state = this.inspectIndexedValue(txId, def, row.key, decoded.primaryKey);\n if (state === 'missing') {\n this.cleanupStaleIndexRow(txId, def, row.key);\n continue;\n }\n if (state === 'trusted') {\n throw remoteError(\n 'UniqueIndexConstraintError',\n `unique index constraint violation on ${def.store}.${def.name}`\n );\n }\n // Keep TTL cleanup and document errors in index row order.\n const value = await this.readStoreValue(txId, def.store, decoded.primaryKey, knownCompression);\n if (value === null) {\n this.cleanupStaleIndexRow(txId, def, row.key);\n continue;\n }\n const currentLogicalKey = extractLogicalIndexKey(def, value);\n if (currentLogicalKey === null || !bytesEqual(currentLogicalKey, logicalKey)) {\n this.cleanupStaleIndexRow(txId, def, row.key);\n continue;\n }\n throw remoteError(\n 'UniqueIndexConstraintError',\n `unique index constraint violation on ${def.store}.${def.name}`\n );\n }\n if (rows.length < chunkLimit) {\n return;\n }\n chunkLimit = Math.min(INDEX_SCAN_RAW_CHUNK_ROWS, chunkLimit * 2);\n }\n }\n /**\n * Resumes after a physical index key in the scan direction. Bounded raw\n * chunks prevent stale entries from forcing the whole range into memory.\n * The output limit counts only live rows.\n */\n private async loadVisibleIndexPage(\n txId: number,\n def: NormalizedIndexDef,\n range: Range,\n cursor: Uint8Array | null,\n limit: number,\n maxBytes: number = INDEX_SCAN_PAGE_BYTES,\n physicalRange?: Range\n ): Promise<IndexScanPage> {\n const { limit: _ignored, ...withoutLimit } = range;\n const physical = physicalRange ?? indexRangeToPhysicalRange(withoutLimit);\n const reverse = physical.reverse === true;\n const compression = this.storeCompressionForTx(txId, def.store);\n let resumeAfter = cursor;\n const visible: ScanItem[] = [];\n let outputBytes = 4;\n // Start with the requested row count. Grow wholly stale chunks\n // geometrically to avoid one scan per expired row at small limits.\n let staleChunkFloor = 1;\n for (;;) {\n const chunkLimit = Math.min(INDEX_SCAN_RAW_CHUNK_ROWS, Math.max(limit - visible.length, staleChunkFloor));\n const chunkRange: Range = { ...physical, limit: chunkLimit };\n if (resumeAfter !== null) {\n if (reverse) {\n delete chunkRange.lte;\n chunkRange.lt = resumeAfter;\n } else {\n delete chunkRange.gte;\n chunkRange.gt = resumeAfter;\n }\n }\n let rawRows: ScanItem[];\n try {\n rawRows = this.readIndexKeyScan(txId, def.internalStore, chunkRange);\n } catch (error) {\n if (isNamedError(error, 'StoreNotFoundError')) {\n return { rows: [], cursor: null };\n }\n throw error;\n }\n const visibleBefore = visible.length;\n let batchStart = 0;\n let batchEnd = 0;\n let batch: ReturnType<DbWorker['readIndexPrimaryValues']> = null;\n for (let index = 0; index < rawRows.length; index += 1) {\n if (index === batchEnd) {\n batchStart = index;\n batch = this.readIndexPrimaryValues(\n txId,\n def,\n rawRows,\n index,\n Math.min(rawRows.length, index + limit - visible.length),\n maxBytes - outputBytes\n );\n batchEnd = index + (batch?.entries.length ?? 1);\n if (batch && compression !== false) {\n this.stabilizeWasmValues(batch.values);\n }\n }\n const row = rawRows[index];\n const resolved = batch\n ? await this.resolveVisibleIndexedValue(\n txId,\n def,\n row.key,\n batch.entries[index - batchStart],\n batch.values[index - batchStart],\n batch.trusted[index - batchStart],\n compression,\n true\n )\n : await this.visibleIndexedRow(txId, def, row.key, compression);\n if (batch !== null) {\n batch.values[index - batchStart] = null;\n }\n if (!resolved) {\n resumeAfter = row.key;\n continue;\n }\n const nextBytes = outputBytes + 8 + resolved.key.byteLength + resolved.value.byteLength;\n if (nextBytes > maxBytes) {\n if (visible.length === 0) {\n throw remoteError('ValueTooLargeError', 'indexed scan row exceeds maxBytes');\n }\n if (resumeAfter === null) {\n throw remoteError('InternalError', 'indexed scan lost its continuation key');\n }\n // The next page must retry this live row.\n return { rows: visible, cursor: resumeAfter.slice() };\n }\n visible.push(resolved);\n outputBytes = nextBytes;\n resumeAfter = row.key;\n if (visible.length >= limit) {\n // readRawScan already detached this key from the engine buffer.\n return { rows: visible, cursor: row.key };\n }\n }\n if (rawRows.length < chunkLimit) {\n return { rows: visible, cursor: null };\n }\n staleChunkFloor =\n visible.length === visibleBefore ? Math.min(INDEX_SCAN_RAW_CHUNK_ROWS, chunkLimit * 2) : 1;\n }\n }\n private readIndexPrimaryValues(\n txId: number,\n def: NormalizedIndexDef,\n rows: ScanItem[],\n start: number,\n end: number,\n remainingBytes: number\n ): { entries: DecodedIndexEntryKey[]; values: Array<Uint8Array | null>; trusted: boolean[] } | null {\n if (\n this.txModes.get(txId) !== 'readonly' ||\n end - start <= 1 ||\n (typeof this.engine?.get_many_value_sizes !== 'function' &&\n typeof this.engine?.get_many_value_states !== 'function')\n ) {\n return null;\n }\n let entries: DecodedIndexEntryKey[];\n let values: Array<Uint8Array | null>;\n let trusted: boolean[];\n let loaded: Array<Uint8Array | null>;\n let selectedIndices: number[];\n try {\n entries = rows.slice(start, end).map((row) => decodeIndexEntryKey(row.key));\n const packedKeys = this.packNativeKeys(entries.map((entry) => entry.primaryKey));\n let primaryStates: NativeValueState[] | null = null;\n let indexStates: NativeValueState[] | null = null;\n let sizes: Uint32Array;\n if (typeof this.engine?.get_many_value_states === 'function') {\n primaryStates = this.decodeNativeValueStates(\n normalizeWasmBytes(\n this.withEngine((engine) =>\n engine.get_many_value_states!(toWasmU64(txId), def.store, packedKeys)\n )\n ),\n entries.length\n );\n if (primaryStates === null) {\n return null;\n }\n sizes = Uint32Array.from(primaryStates, (state) =>\n state.live ? state.maxValueBytes : MAX_PACKED_BYTES\n );\n if (primaryStates.some((state) => state.live && state.revisionKnown)) {\n const indexKeys = this.packNativeKeys(rows.slice(start, end).map((row) => row.key));\n indexStates = this.decodeNativeValueStates(\n normalizeWasmBytes(\n this.withEngine((engine) =>\n engine.get_many_value_states!(toWasmU64(txId), def.internalStore, indexKeys)\n )\n ),\n entries.length\n );\n if (indexStates === null) {\n return null;\n }\n }\n } else {\n sizes = this.withEngine((engine) =>\n engine.get_many_value_sizes!(toWasmU64(txId), def.store, packedKeys)\n );\n }\n if (sizes.length !== entries.length) {\n return null;\n }\n let selected = 0;\n for (const entry of entries) {\n const size = sizes[selected];\n if (!Number.isSafeInteger(size) || size < 0 || size > MAX_PACKED_BYTES) {\n return null;\n }\n const required = size === MAX_PACKED_BYTES ? 0 : 8 + entry.primaryKey.byteLength + size;\n if (required > remainingBytes) {\n break;\n }\n remainingBytes -= required;\n selected += 1;\n }\n if (selected <= 1) {\n return null;\n }\n // Native sizes bound body reads. Each document still requires index validation.\n entries.length = selected;\n trusted = new Array<boolean>(selected).fill(false);\n const selectedKeys: Uint8Array[] = [];\n selectedIndices = [];\n values = new Array<Uint8Array | null>(selected).fill(null);\n for (let index = 0; index < selected; index += 1) {\n const primary = primaryStates?.[index];\n if (primary === undefined || primary.live) {\n selectedKeys.push(entries[index].primaryKey);\n selectedIndices.push(index);\n }\n const proof = indexStates?.[index];\n trusted[index] = Boolean(\n primary?.live &&\n primary.revisionKnown &&\n proof?.live &&\n proof.revisionKnown &&\n primary.revisionEpoch === proof.revisionEpoch &&\n primary.revisionOrdinal === proof.revisionOrdinal\n );\n }\n loaded =\n selectedKeys.length === 0\n ? []\n : this.withEngine((engine) => engine.get_many(toWasmU64(txId), def.store, selectedKeys));\n } catch {\n // Row order preserves an earlier document error if a later preflight or body read fails.\n return null;\n }\n if (loaded.length !== selectedIndices.length) {\n throw outcomeCountMismatch('get_many', loaded.length, selectedIndices.length);\n }\n for (let index = 0; index < loaded.length; index += 1) {\n values[selectedIndices[index]] = loaded[index];\n loaded[index] = null;\n }\n return { entries, values, trusted };\n }\n private stabilizeWasmValues(values: Array<Uint8Array | null>): void {\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index];\n if (value !== null) {\n values[index] = normalizeWasmBytes(value);\n }\n }\n }\n private visibleIndexedRow(\n txId: number,\n def: NormalizedIndexDef,\n physicalKey: Uint8Array,\n compression: CompressionOption\n ): ScanItem | null | Promise<ScanItem | null> {\n const decoded = decodeIndexEntryKey(physicalKey);\n const state = this.inspectIndexedValue(txId, def, physicalKey, decoded.primaryKey);\n if (state === 'missing') {\n this.cleanupStaleIndexRow(txId, def, physicalKey);\n return null;\n }\n const value = this.readRawValue(txId, def.store, decoded.primaryKey);\n return this.resolveVisibleIndexedValue(\n txId,\n def,\n physicalKey,\n decoded,\n value,\n state === 'trusted',\n compression,\n true\n );\n }\n private resolveVisibleIndexedValue(\n txId: number,\n def: NormalizedIndexDef,\n physicalKey: Uint8Array,\n decoded: DecodedIndexEntryKey,\n rawValue: Uint8Array | null,\n trusted: boolean = false,\n compression: CompressionOption,\n stable: boolean\n ): ScanItem | null | Promise<ScanItem | null> {\n if (rawValue === null) {\n this.cleanupStaleIndexRow(txId, def, physicalKey);\n return null;\n }\n const bytes = stable ? rawValue : normalizeWasmBytes(rawValue);\n if (compression === false) {\n return this.finishVisibleIndexedValue(txId, def, physicalKey, decoded, bytes, trusted);\n }\n return decodeStoreValueRecord(bytes, { strict: true }).then((value) =>\n this.finishVisibleIndexedValue(txId, def, physicalKey, decoded, value, trusted)\n );\n }\n private finishVisibleIndexedValue(\n txId: number,\n def: NormalizedIndexDef,\n physicalKey: Uint8Array,\n decoded: DecodedIndexEntryKey,\n value: Uint8Array,\n trusted: boolean\n ): ScanItem | null {\n if (!trusted) {\n const currentLogicalKey = extractLogicalIndexKey(def, value);\n if (currentLogicalKey === null || !bytesEqual(currentLogicalKey, decoded.logicalKey)) {\n this.cleanupStaleIndexRow(txId, def, physicalKey);\n return null;\n }\n }\n return {\n key: decoded.primaryKey,\n value\n };\n }\n private cleanupStaleIndexRow(txId: number, def: NormalizedIndexDef, physicalKey: Uint8Array): void {\n if (this.txModes.get(txId) !== 'readwrite') {\n return;\n }\n try {\n this.withEngine((engine) => engine.delete(toWasmU64(txId), def.internalStore, physicalKey));\n } catch {}\n }\n private async loadWasm(): Promise<WasmModule> {\n if (!this.wasmReady) {\n this.wasmReady = this.options.loadWasm\n ? this.options.loadWasm()\n : (async () => {\n // Absolute URLs stay outside Vite's ?import transform, which rejects JS in /public.\n const moduleUrl = new URL('/engine/moyodb_engine.js', import.meta.url).href;\n const wasmUrl = new URL('/engine/moyodb_engine_bg.wasm', import.meta.url).href;\n const wasmModule = (await import(\n /* @vite-ignore */\n moduleUrl\n )) as WasmModule;\n await wasmModule.default({ module_or_path: wasmUrl });\n return wasmModule;\n })();\n }\n return this.wasmReady;\n }\n private withEngine<T>(\n fn: (engine: NonNullable<DbWorker['engine']>) => T,\n options: {\n allowDuringMaintenance?: boolean;\n } = {}\n ): T {\n if (this.maintenanceOperation && !options.allowDuringMaintenance) {\n this.ensureNotInMaintenance();\n }\n if (!this.engine) {\n throw remoteError('InternalError', 'engine is not open');\n }\n try {\n return fn(this.engine);\n } catch (err) {\n throw remapError(err);\n }\n }\n private ignoreNamedError(name: string, fn: () => void): void {\n try {\n fn();\n } catch (error) {\n if (isNamedError(error, name)) {\n return;\n }\n throw error;\n }\n }\n private clearTxCaches(): void {\n this.primaryCursors.clear();\n this.txChanges.clear();\n this.txModes.clear();\n this.txIndexSchemas.clear();\n this.readonlyIndexCache.clear();\n this.indexBoundCache = null;\n this.txEnsuredRawStores.clear();\n this.txIndexSchemaChanged.clear();\n this.txStoreCompression.clear();\n }\n private clearRuntimeCaches(): void {\n this.clearTxCaches();\n this.committedIndexes = null;\n this.committedStoreCompression = null;\n }\n private async cleanupAfterFailedOpen(engine: WasmEngine | null): Promise<void> {\n try {\n engine?.abandon();\n } catch {}\n this.engine = null;\n this.clearRuntimeCaches();\n this.events?.close();\n this.events = null;\n if (this.lease) {\n try {\n await this.lease.release();\n } catch {}\n }\n this.lease = null;\n this.disposePersistenceBridge();\n this.dbName = null;\n this.openOptions = null;\n this.maintenanceOperation = null;\n }\n private disposePersistenceBridge(): void {\n this.persistenceBridge.close();\n }\n}\nfunction assertCapabilities(): void {\n if (typeof navigator.storage.getDirectory !== 'function') {\n throw remoteError('UnsupportedPlatformError', 'navigator.storage.getDirectory is unavailable');\n }\n if (typeof BroadcastChannel === 'undefined') {\n throw remoteError('UnsupportedPlatformError', 'BroadcastChannel is unavailable');\n }\n // Real database handle acquisition validates storage access. A shared\n // probe file adds I/O and can lock out otherwise independent databases.\n if (\n typeof FileSystemFileHandle === 'undefined' ||\n typeof FileSystemFileHandle.prototype.createSyncAccessHandle !== 'function'\n ) {\n throw remoteError('UnsupportedPlatformError', 'createSyncAccessHandle is unavailable');\n }\n}\nfunction assertSecureContext() {\n if (!self.isSecureContext) {\n throw remoteError('UnsupportedPlatformError', 'moyodb requires a secure context (HTTPS)');\n }\n}\nfunction remoteError(code: string, message: string): Error {\n const error = new Error(message);\n error.name = code;\n Object.defineProperty(error, 'code', {\n value: code,\n enumerable: true,\n configurable: true\n });\n return error;\n}\nfunction applyChangeFeedPolicy(engine: WasmEngine, settings: Required<ChangeFeedSettings>): void {\n const current = engine.change_feed_policy();\n const currentRetain = fromOptionalWasmU64(current.retainTxids);\n if (current.enabled === settings.enabled && (!settings.enabled || currentRetain === settings.retainTxids)) {\n return;\n }\n const txId = engine.begin_tx('readwrite');\n try {\n engine.set_change_feed_policy(txId, { enabled: settings.enabled, retainTxids: settings.retainTxids });\n engine.commit_tx(txId);\n } catch (error) {\n try {\n engine.rollback_tx(txId);\n } catch {}\n throw remapError(error);\n }\n}\n/** Active generation, null for legacy storage, undefined if reading fails. */\nasync function readActiveGenerationOrNull(wasm: WasmModule, dbName: string): Promise<string | null | undefined> {\n try {\n return await wasm.readActiveGeneration(dbName);\n } catch {\n return undefined;\n }\n}\nfunction normalizeEngineHealth(health: WasmEngineHealth): EngineHealth {\n if (health.state === 'recoveryRequired') {\n return {\n state: 'recoveryRequired',\n reason: health.reason,\n pendingTxid: fromOptionalWasmU64(health.pendingTxid)\n };\n }\n return { state: health.state };\n}\nfunction outcomeCountMismatch(operation: string, actual: number, expected: number): Error {\n return remoteError('InternalError', `${operation} outcome count mismatch: ${actual} != ${expected}`);\n}\nfunction partialBooleanOutcomes(error: unknown): boolean[] {\n if (!isRecord(error) || !Array.isArray(error.partial)) {\n return [];\n }\n return error.partial.filter((value): value is boolean => typeof value === 'boolean');\n}\nfunction partialBatchOutcomes(error: unknown): WasmBatchOutcome[] {\n if (!isRecord(error) || !Array.isArray(error.partial)) {\n return [];\n }\n return error.partial.filter((value): value is WasmBatchOutcome => {\n if (!isRecord(value) || typeof value.kind !== 'string') {\n return false;\n }\n return (\n (value.kind === 'put' && typeof value.baselineExists === 'boolean') ||\n (value.kind === 'delete' && typeof value.deleted === 'boolean')\n );\n });\n}\nfunction remapError(err: unknown): Error {\n if (err instanceof Error) {\n return err;\n }\n if (isRecord(err)) {\n const code = typeof err.code === 'string' ? err.code : typeof err.name === 'string' ? err.name : 'Error';\n const message = typeof err.message === 'string' ? err.message : 'Unknown error';\n const error = remoteError(code, message);\n if ('partial' in err) {\n Object.defineProperty(error, 'partial', {\n value: err.partial,\n enumerable: true,\n configurable: true\n });\n }\n return error;\n }\n return remoteError('Error', String(err));\n}\n","import { DbWorker, exposeWorkerApi } from './worker';\nimport type { WorkerServerScope } from './worker-server';\nimport { isRecord } from './internal';\n\nconst api = new DbWorker();\nlet server = exposeWorkerApi(api);\nlet connected = false;\n\nself.addEventListener('message', (event: MessageEvent<unknown>) => {\n if (event.origin !== '' && event.origin !== self.location.origin) {\n return;\n }\n if (!isRecord(event.data) || event.data.type !== 'moyodb:worker-port:init' || !event.ports[0]) {\n return;\n }\n const port = event.ports[0];\n if (connected) {\n port.close();\n return;\n }\n connected = true;\n server.close();\n const scope: WorkerServerScope = {\n location: { origin: self.location.origin },\n postMessage: (message, transfer) => port.postMessage(message, transfer ?? []),\n addEventListener: (type, listener) => port.addEventListener(type, listener),\n removeEventListener: (type, listener) => port.removeEventListener(type, listener)\n };\n server = exposeWorkerApi(api, scope);\n port.start();\n});\n"],"mappings":"AAAA,SAAgB,EAAS,EAAkD,CACvE,OAAyB,OAAO,GAAU,YAAnC,CACX,CAEA,SAAgB,EAAyB,EAAc,EAAuB,CAI1E,OAHI,EAAO,EACA,GAEJ,IAAO,EAClB,CAQA,SAAgB,EAAkB,EAAyB,CAIvD,MAHI,CAAC,OAAO,SAAS,CAAO,GAAK,GAAW,EACjC,EAEJ,EAAA,WAA+B,WAAqB,CAC/D,CCjBA,MAEa,EAA2B,kCAM3B,EAAkB,yaAyC/B,EAqCM,kBAAyB,IAAI,IAAY,CAtB3C,MACA,UACA,MACA,MACA,UACA,SACA,aACA,aACA,OACA,aACA,cACA,cACA,YACA,YAS2C,CA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