@earendil-works/pi-durable 1.5.0 → 1.5.1

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.
Files changed (201) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +17 -4
  3. package/dist/codemode/codemode.d.ts +2 -1
  4. package/dist/codemode/codemode.d.ts.map +1 -1
  5. package/dist/codemode/codemode.js +1 -37
  6. package/dist/codemode/codemode.js.map +1 -1
  7. package/dist/codemode/models.d.ts +2 -1
  8. package/dist/codemode/models.d.ts.map +1 -1
  9. package/dist/codemode/models.js.map +1 -1
  10. package/dist/documents.d.ts +1 -1
  11. package/dist/documents.d.ts.map +1 -1
  12. package/dist/documents.js +1 -1
  13. package/dist/documents.js.map +1 -1
  14. package/dist/entries.d.ts +1 -1
  15. package/dist/entries.d.ts.map +1 -1
  16. package/dist/entries.js.map +1 -1
  17. package/dist/env/index.d.ts +1 -1
  18. package/dist/env/index.d.ts.map +1 -1
  19. package/dist/env/index.js.map +1 -1
  20. package/dist/env/node-watch.d.ts +1 -1
  21. package/dist/env/node-watch.d.ts.map +1 -1
  22. package/dist/env/node-watch.js.map +1 -1
  23. package/dist/env/node.d.ts +1 -1
  24. package/dist/env/node.d.ts.map +1 -1
  25. package/dist/env/node.js.map +1 -1
  26. package/dist/harness/agent.d.ts.map +1 -1
  27. package/dist/harness/agent.js +27 -1
  28. package/dist/harness/agent.js.map +1 -1
  29. package/dist/harness/compaction.d.ts +8 -3
  30. package/dist/harness/compaction.d.ts.map +1 -1
  31. package/dist/harness/compaction.js +21 -9
  32. package/dist/harness/compaction.js.map +1 -1
  33. package/dist/harness/context.d.ts +1 -1
  34. package/dist/harness/context.d.ts.map +1 -1
  35. package/dist/harness/context.js.map +1 -1
  36. package/dist/harness/define.d.ts +1 -1
  37. package/dist/harness/define.d.ts.map +1 -1
  38. package/dist/harness/define.js.map +1 -1
  39. package/dist/harness/generation.d.ts +1 -1
  40. package/dist/harness/generation.d.ts.map +1 -1
  41. package/dist/harness/generation.js +6 -4
  42. package/dist/harness/generation.js.map +1 -1
  43. package/dist/harness/harness.d.ts +1 -1
  44. package/dist/harness/harness.d.ts.map +1 -1
  45. package/dist/harness/harness.js.map +1 -1
  46. package/dist/harness/inbox.d.ts +2 -1
  47. package/dist/harness/inbox.d.ts.map +1 -1
  48. package/dist/harness/inbox.js +1 -1
  49. package/dist/harness/inbox.js.map +1 -1
  50. package/dist/harness/json.d.ts +1 -1
  51. package/dist/harness/json.d.ts.map +1 -1
  52. package/dist/harness/json.js.map +1 -1
  53. package/dist/harness/live.d.ts +2 -1
  54. package/dist/harness/live.d.ts.map +1 -1
  55. package/dist/harness/live.js.map +1 -1
  56. package/dist/harness/partial-changes.d.ts +1 -1
  57. package/dist/harness/partial-changes.d.ts.map +1 -1
  58. package/dist/harness/partial-changes.js +1 -0
  59. package/dist/harness/partial-changes.js.map +1 -1
  60. package/dist/harness/prompt.d.ts +1 -1
  61. package/dist/harness/prompt.d.ts.map +1 -1
  62. package/dist/harness/prompt.js.map +1 -1
  63. package/dist/harness/provider.d.ts +1 -1
  64. package/dist/harness/provider.d.ts.map +1 -1
  65. package/dist/harness/provider.js.map +1 -1
  66. package/dist/harness/registry-reader.d.ts +1 -1
  67. package/dist/harness/registry-reader.d.ts.map +1 -1
  68. package/dist/harness/registry-reader.js.map +1 -1
  69. package/dist/harness/scheduler.d.ts +2 -1
  70. package/dist/harness/scheduler.d.ts.map +1 -1
  71. package/dist/harness/scheduler.js +42 -13
  72. package/dist/harness/scheduler.js.map +1 -1
  73. package/dist/harness/submissions.d.ts +1 -1
  74. package/dist/harness/submissions.d.ts.map +1 -1
  75. package/dist/harness/submissions.js +1 -1
  76. package/dist/harness/submissions.js.map +1 -1
  77. package/dist/harness/task-graph.d.ts +3 -1
  78. package/dist/harness/task-graph.d.ts.map +1 -1
  79. package/dist/harness/task-graph.js +1 -1
  80. package/dist/harness/task-graph.js.map +1 -1
  81. package/dist/harness/tool.d.ts +1 -1
  82. package/dist/harness/tool.d.ts.map +1 -1
  83. package/dist/harness/tool.js +1 -1
  84. package/dist/harness/tool.js.map +1 -1
  85. package/dist/harness/transcript.d.ts +1 -1
  86. package/dist/harness/transcript.d.ts.map +1 -1
  87. package/dist/harness/transcript.js.map +1 -1
  88. package/dist/harness/types.d.ts +21 -4
  89. package/dist/harness/types.d.ts.map +1 -1
  90. package/dist/harness/types.js.map +1 -1
  91. package/dist/harness/usage.d.ts +2 -1
  92. package/dist/harness/usage.d.ts.map +1 -1
  93. package/dist/harness/usage.js +1 -1
  94. package/dist/harness/usage.js.map +1 -1
  95. package/dist/harness/util.d.ts +1 -1
  96. package/dist/harness/util.d.ts.map +1 -1
  97. package/dist/harness/util.js.map +1 -1
  98. package/dist/harness/view.d.ts +2 -1
  99. package/dist/harness/view.d.ts.map +1 -1
  100. package/dist/harness/view.js +1 -1
  101. package/dist/harness/view.js.map +1 -1
  102. package/dist/index.d.ts +1 -1
  103. package/dist/index.d.ts.map +1 -1
  104. package/dist/index.js.map +1 -1
  105. package/dist/session/cached-storage.d.ts +2 -1
  106. package/dist/session/cached-storage.d.ts.map +1 -1
  107. package/dist/session/cached-storage.js.map +1 -1
  108. package/dist/session/forks.d.ts +1 -1
  109. package/dist/session/forks.d.ts.map +1 -1
  110. package/dist/session/forks.js.map +1 -1
  111. package/dist/session/keys.d.ts +2 -1
  112. package/dist/session/keys.d.ts.map +1 -1
  113. package/dist/session/keys.js.map +1 -1
  114. package/dist/session/session.d.ts +3 -1
  115. package/dist/session/session.d.ts.map +1 -1
  116. package/dist/session/session.js +1 -1
  117. package/dist/session/session.js.map +1 -1
  118. package/dist/session/transaction.d.ts +4 -3
  119. package/dist/session/transaction.d.ts.map +1 -1
  120. package/dist/session/transaction.js +3 -3
  121. package/dist/session/transaction.js.map +1 -1
  122. package/dist/session/writer.d.ts +1 -1
  123. package/dist/session/writer.d.ts.map +1 -1
  124. package/dist/session/writer.js.map +1 -1
  125. package/dist/storage/indexeddb.d.ts +2 -1
  126. package/dist/storage/indexeddb.d.ts.map +1 -1
  127. package/dist/storage/indexeddb.js.map +1 -1
  128. package/dist/storage/jsonl/index.d.ts +1 -1
  129. package/dist/storage/jsonl/index.d.ts.map +1 -1
  130. package/dist/storage/jsonl/index.js +1 -1
  131. package/dist/storage/jsonl/index.js.map +1 -1
  132. package/dist/storage/jsonl/node.d.ts +3 -3
  133. package/dist/storage/jsonl/node.d.ts.map +1 -1
  134. package/dist/storage/jsonl/node.js +2 -2
  135. package/dist/storage/jsonl/node.js.map +1 -1
  136. package/dist/storage/jsonl/storage.d.ts +32 -3
  137. package/dist/storage/jsonl/storage.d.ts.map +1 -1
  138. package/dist/storage/jsonl/storage.js +70 -19
  139. package/dist/storage/jsonl/storage.js.map +1 -1
  140. package/dist/storage/memory.d.ts +2 -1
  141. package/dist/storage/memory.d.ts.map +1 -1
  142. package/dist/storage/memory.js.map +1 -1
  143. package/dist/storage/sqlite/commit.d.ts +52 -0
  144. package/dist/storage/sqlite/commit.d.ts.map +1 -0
  145. package/dist/storage/sqlite/commit.js +371 -0
  146. package/dist/storage/sqlite/commit.js.map +1 -0
  147. package/dist/storage/sqlite/rows.d.ts +33 -0
  148. package/dist/storage/sqlite/rows.d.ts.map +1 -0
  149. package/dist/storage/sqlite/rows.js +53 -0
  150. package/dist/storage/sqlite/rows.js.map +1 -0
  151. package/dist/storage/sqlite/statements.d.ts +13 -0
  152. package/dist/storage/sqlite/statements.d.ts.map +1 -0
  153. package/dist/storage/sqlite/statements.js +88 -0
  154. package/dist/storage/sqlite/statements.js.map +1 -0
  155. package/dist/storage/sqlite/storage.d.ts +12 -11
  156. package/dist/storage/sqlite/storage.d.ts.map +1 -1
  157. package/dist/storage/sqlite/storage.js +44 -259
  158. package/dist/storage/sqlite/storage.js.map +1 -1
  159. package/dist/storage/store/commit.d.ts +2 -2
  160. package/dist/storage/store/commit.d.ts.map +1 -1
  161. package/dist/storage/store/commit.js +1 -1
  162. package/dist/storage/store/commit.js.map +1 -1
  163. package/dist/storage/store/documents.d.ts +1 -1
  164. package/dist/storage/store/documents.d.ts.map +1 -1
  165. package/dist/storage/store/documents.js +1 -1
  166. package/dist/storage/store/documents.js.map +1 -1
  167. package/dist/storage/store/queries.d.ts +2 -2
  168. package/dist/storage/store/queries.d.ts.map +1 -1
  169. package/dist/storage/store/queries.js.map +1 -1
  170. package/dist/storage/store/storage.d.ts +3 -2
  171. package/dist/storage/store/storage.d.ts.map +1 -1
  172. package/dist/storage/store/storage.js +1 -1
  173. package/dist/storage/store/storage.js.map +1 -1
  174. package/dist/storage/store/tables.d.ts +31 -31
  175. package/dist/storage/store/tables.d.ts.map +1 -1
  176. package/dist/storage/store/tables.js +1 -1
  177. package/dist/storage/store/tables.js.map +1 -1
  178. package/dist/testing/commit-writes.d.ts +1 -1
  179. package/dist/testing/commit-writes.d.ts.map +1 -1
  180. package/dist/testing/commit-writes.js.map +1 -1
  181. package/dist/testing/env-conformance.js.map +1 -1
  182. package/dist/testing/storage-benchmark.js.map +1 -1
  183. package/dist/testing/storage-conformance.js.map +1 -1
  184. package/dist/tool-search/tool-search.d.ts +2 -2
  185. package/dist/tool-search/tool-search.d.ts.map +1 -1
  186. package/dist/tool-search/tool-search.js +18 -6
  187. package/dist/tool-search/tool-search.js.map +1 -1
  188. package/dist/tools/bash.d.ts +1 -1
  189. package/dist/tools/bash.d.ts.map +1 -1
  190. package/dist/tools/bash.js.map +1 -1
  191. package/dist/tools/file-mutation-queue.d.ts +1 -1
  192. package/dist/tools/file-mutation-queue.d.ts.map +1 -1
  193. package/dist/tools/file-mutation-queue.js.map +1 -1
  194. package/dist/tools/path-utils.d.ts +1 -1
  195. package/dist/tools/path-utils.d.ts.map +1 -1
  196. package/dist/tools/path-utils.js.map +1 -1
  197. package/dist/tools/read.js.map +1 -1
  198. package/dist/types.d.ts +6 -2
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/types.js.map +1 -1
  201. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"storage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AAC;QACF,CAAC;IACF,CAAC;IAEO,UAAU;QACjB,IAAI,IAAI,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7D,CAAC;CACD","sourcesContent":["import type { Context, JsonValue } from \"@earendil-works/chord\";\nimport { apply, type Op } from \"@earendil-works/chord/delta\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteValue } from \"@earendil-works/chord/sqlite\";\nimport { StorageRequestError } from \"../../errors.ts\";\nimport { idFromNumber, seqFromNumber } from \"../../ids.ts\";\nimport type {\n\tCommitResult,\n\tConversationId,\n\tConversationQuery,\n\tConversationRecord,\n\tCursor,\n\tDocumentAddress,\n\tDocumentContent,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentPoint,\n\tDocumentQuery,\n\tDocumentRecord,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tId,\n\tJsonObject,\n\tPage,\n\tScanOrder,\n\tSeq,\n\tStorage,\n\tStorageWrite,\n\tStoredDocument,\n\tSubmissionId,\n\tSubmissionQuery,\n\tSubmissionRecord,\n\tTaskId,\n\tTaskQuery,\n\tTaskRecord,\n} from \"../../types.ts\";\nimport { nextCursor, type ScanStart, scanStart } from \"../scan.ts\";\nimport { applySqliteMigrationsForSchema } from \"./migrations.ts\";\nimport { createSqliteSchema, type SqliteSchema } from \"./schema.ts\";\n\ntype StoredTask = TaskRecord<JsonValue, JsonValue, JsonValue>;\ntype TableName = \"conversation\" | \"entry\" | \"task\" | \"submission\" | \"document\";\ntype RecordIdRow = { readonly record_type: TableName };\ntype JsonRow = { readonly record: string };\ntype EntryJsonRow = { readonly record: string; readonly commit_seq: number };\ntype RevisionRow = {\n\treadonly seq: number;\n\treadonly kind: DocumentContent[\"kind\"];\n\treadonly version: number;\n\treadonly content: string;\n};\ntype IdRow = { readonly id: number };\ntype MetadataRow = { readonly next_id: string; readonly next_seq: number };\ntype DocumentAction = {\n\tcreate?: DocumentCreate;\n\tcopy?: Extract<StorageWrite, { readonly type: \"document.copy\" }>[\"source\"];\n\tcontent?: DocumentContent;\n\tretire: boolean;\n};\ntype ScopeColumns = {\n\treadonly scopeKind: DocumentRecord[\"scope\"][\"kind\"];\n\treadonly ownerId: number;\n};\n\nexport type SqliteStorageOptions = {\n\t/**\n\t * Prefix for every table and index in the durable schema. It must be a SQLite identifier and must not use\n\t * SQLite's reserved `sqlite_` prefix. Existing data is not migrated when this changes.\n\t */\n\treadonly prefix?: string;\n};\n\nconst parseJson = <T>(value: string): T => JSON.parse(value) as T;\nconst encodeJson = (value: unknown): string => JSON.stringify(value) as string;\n// Some SQLite bindings replace lone UTF-16 surrogates. JSON encoding keeps indexed identities lossless.\nconst encodeIndexedString = (value: string): string => JSON.stringify(value);\n\nconst cursorId = <I extends Id<string>>(cursor: Cursor | undefined): I | undefined => {\n\tconst after = cursor?.after;\n\tif (after === undefined) return undefined;\n\tif (typeof after !== \"number\" || !Number.isSafeInteger(after))\n\t\tthrow new StorageRequestError(\"Invalid storage cursor\");\n\treturn idFromNumber<I>(after);\n};\n\nconst page = <T extends { readonly id: Id<string> }>(\n\tvalues: readonly T[],\n\tlimit: number,\n\torder: ScanOrder = \"ascending\",\n): Page<T, Cursor> => {\n\tconst items = values.slice(0, limit);\n\tif (values.length <= limit) return { items };\n\treturn { items, next: nextCursor(items.at(-1)!.id, order) };\n};\n\n/** The ID condition, its parameter, and the `ORDER BY` direction of a table scan. */\nconst scanSql = (start: ScanStart): { readonly clause: string; readonly param: number; readonly direction: string } =>\n\tstart.order === \"ascending\"\n\t\t? { clause: \"id > ?\", param: start.after ?? -1, direction: \"ASC\" }\n\t\t: { clause: \"id < ?\", param: start.after ?? Number.MAX_SAFE_INTEGER, direction: \"DESC\" };\n\nconst scopeColumns = (scope: DocumentRecord[\"scope\"]): ScopeColumns => {\n\tswitch (scope.kind) {\n\t\tcase \"session\":\n\t\t\treturn { scopeKind: \"session\", ownerId: 0 };\n\t\tcase \"conversation\":\n\t\t\treturn { scopeKind: \"conversation\", ownerId: scope.conversationId };\n\t\tcase \"task\":\n\t\t\treturn { scopeKind: \"task\", ownerId: scope.taskId };\n\t}\n};\n\nconst addressParts = (address: DocumentAddress | DocumentCreate | DocumentRecord) => {\n\tconst scope = scopeColumns(address.scope);\n\treturn {\n\t\tkind: encodeIndexedString(address.kind),\n\t\t...scope,\n\t\tfamily: address.key === undefined ? 0 : 1,\n\t\tkeyValue: encodeIndexedString(address.key ?? \"\"),\n\t};\n};\n\nconst addressKey = (address: DocumentAddress | DocumentCreate | DocumentRecord): string => {\n\tconst parts = addressParts(address);\n\treturn JSON.stringify([parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue]);\n};\n\nconst isAliveAt = (record: DocumentRecord, at: DocumentPoint): boolean => {\n\tif (at === \"current\") return record.retiredAt === undefined;\n\treturn record.createdAt <= at && (record.retiredAt === undefined || at < record.retiredAt);\n};\n\nconst isCurrentOnly = (record: DocumentRecord): boolean =>\n\trecord.scope.kind !== \"conversation\" || record.history === \"latest\";\n\nconst writeId = (write: StorageWrite): Id<string> | undefined => {\n\tswitch (write.type) {\n\t\tcase \"conversation\":\n\t\tcase \"entry\":\n\t\tcase \"task\":\n\t\tcase \"submission\":\n\t\t\treturn write.value.id;\n\t\tcase \"document.create\":\n\t\tcase \"document.copy\":\n\t\t\treturn write.record.id;\n\t\tcase \"document.change\":\n\t\tcase \"document.retire\":\n\t\t\treturn undefined;\n\t}\n};\n\n/** Whether a database call of the checks failed, whatever it threw or rejected with. */\ntype CheckCalls = { failed: boolean };\n\n/**\n * `executor`, setting `calls.failed` when one of its calls throws, synchronously (a synchronous driver) or by\n * rejecting, with any value: then a failing check is the database's, not one of Durable's own.\n */\nfunction watchCalls(executor: SqliteExecutor, calls: CheckCalls): SqliteExecutor {\n\tconst watched = async <T>(call: () => Promise<T>): Promise<T> => {\n\t\ttry {\n\t\t\treturn await call();\n\t\t} catch (error) {\n\t\t\tcalls.failed = true;\n\t\t\tthrow error;\n\t\t}\n\t};\n\treturn {\n\t\texec: (sql) => watched(() => executor.exec(sql)),\n\t\trun: (sql, ...params) => watched(() => executor.run(sql, ...params)),\n\t\trunCounted: (sql, ...params) => watched(() => executor.runCounted(sql, ...params)),\n\t\tget: (sql, ...params) => watched(() => executor.get(sql, ...params)),\n\t\tall: (sql, ...params) => watched(() => executor.all(sql, ...params)),\n\t};\n}\n\n/** Portable SQLite implementation of the Pico storage contract. */\nexport class SqliteStorage implements Storage {\n\tprivate readonly db: SqliteDatabase;\n\tprivate readonly schema: SqliteSchema;\n\tprivate nextId: number;\n\tprivate closed = false;\n\tprivate closing: Promise<void> | undefined;\n\tprivate admittedReads = 0;\n\tprivate readsDrained: (() => void) | undefined;\n\n\tprivate constructor(db: SqliteDatabase, schema: SqliteSchema, nextId: number) {\n\t\tthis.db = db;\n\t\tthis.schema = schema;\n\t\tthis.nextId = nextId;\n\t}\n\n\t/** Initialize storage over an owned SQLite database facade. */\n\tstatic async open(db: SqliteDatabase, options: SqliteStorageOptions = {}): Promise<SqliteStorage> {\n\t\ttry {\n\t\t\tconst schema = createSqliteSchema(options.prefix);\n\t\t\tawait applySqliteMigrationsForSchema(db, schema);\n\t\t\tconst metadata = await db.get<MetadataRow>(\n\t\t\t\t`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`,\n\t\t\t);\n\t\t\tif (metadata === undefined) throw new Error(\"Durable SQLite metadata is missing\");\n\t\t\treturn new SqliteStorage(db, schema, Number(metadata.next_id));\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait db.close();\n\t\t\t} catch {\n\t\t\t\t// Preserve the initialization failure.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Commit `batches` in one SQL transaction, each with its own seq. Each batch is checked before it writes anything,\n\t * against the state the earlier ones left, and the first one refused ends the batch: the transaction commits the ones\n\t * before it. No savepoints, which Durable Objects do not allow: the checks run before the writes instead.\n\t */\n\tasync commit(\n\t\tbatches: readonly (readonly StorageWrite[])[],\n\t\treceive: (index: number, seq: Seq) => void,\n\t\t_context: Context,\n\t): Promise<CommitResult> {\n\t\tthis.assertOpen();\n\t\tconst seqs: Seq[] = [];\n\t\tlet refused: { readonly error: unknown } | undefined;\n\t\tlet candidateNextId = this.nextId;\n\t\tawait this.db.transaction(async (transaction) => {\n\t\t\tconst metadata = await this.readMetadata(transaction);\n\t\t\tlet next = metadata.next_seq;\n\t\t\t// Whether a database call of a batch's checks failed: then the failure is an unknown outcome, not a refusal.\n\t\t\tconst calls: CheckCalls = { failed: false };\n\t\t\tconst checked = watchCalls(transaction, calls);\n\t\t\tfor (const writes of batches) {\n\t\t\t\tlet documentActions: Map<DocumentId, DocumentAction>;\n\t\t\t\t// Only Durable's own checks refuse a batch, before it wrote anything: the ones before it stand. A failure of\n\t\t\t\t// the database rejects the call, and rolls back the batches before it with the transaction.\n\t\t\t\tcalls.failed = false;\n\t\t\t\ttry {\n\t\t\t\t\tdocumentActions = this.prepareDocumentActions(writes);\n\t\t\t\t\tawait this.checkBatch(checked, writes, documentActions);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (calls.failed) throw error;\n\t\t\t\t\trefused = { error };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst seq = seqFromNumber(next++);\n\t\t\t\tawait this.applyBatch(transaction, writes, documentActions, seq);\n\t\t\t\tseqs.push(seq);\n\t\t\t\tcandidateNextId = Math.max(candidateNextId, this.candidateNextId(writes));\n\t\t\t}\n\t\t\tif (seqs.length > 0) {\n\t\t\t\tawait this.writeMetadata(transaction, Math.max(Number(metadata.next_id), candidateNextId), next);\n\t\t\t}\n\t\t});\n\t\tthis.nextId = Math.max(this.nextId, candidateNextId);\n\t\t// `COMMIT` returned: the stored batches are durable.\n\t\tfor (const [index, seq] of seqs.entries()) receive(index, seq);\n\t\treturn refused === undefined ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error };\n\t}\n\n\tprivate async readMetadata(executor: SqliteExecutor): Promise<MetadataRow> {\n\t\tconst metadata = await executor.get<MetadataRow>(\n\t\t\t`SELECT next_id, next_seq FROM ${this.schema.tables.durableMetadata} WHERE singleton = 1`,\n\t\t);\n\t\tif (metadata === undefined) throw new Error(\"Durable SQLite metadata is missing\");\n\t\treturn metadata;\n\t}\n\n\tprivate async writeMetadata(executor: SqliteExecutor, nextId: number, nextSeq: number): Promise<void> {\n\t\tawait executor.run(\n\t\t\t`UPDATE ${this.schema.tables.durableMetadata} SET next_id = ?, next_seq = ? WHERE singleton = 1`,\n\t\t\tString(nextId),\n\t\t\tnextSeq,\n\t\t);\n\t}\n\n\t/** Durable's own checks of one batch, copy resolution included, before it writes anything. */\n\tprivate async checkBatch(\n\t\texecutor: SqliteExecutor,\n\t\twrites: readonly StorageWrite[],\n\t\tdocumentActions: Map<DocumentId, DocumentAction>,\n\t): Promise<void> {\n\t\tawait this.checkGlobalIds(executor, writes);\n\t\tawait this.checkDocumentActions(executor, documentActions);\n\t\tawait this.resolveCopies(executor, documentActions);\n\t}\n\n\tprivate async applyBatch(\n\t\texecutor: SqliteExecutor,\n\t\twrites: readonly StorageWrite[],\n\t\tdocumentActions: ReadonlyMap<DocumentId, DocumentAction>,\n\t\tseq: Seq,\n\t): Promise<void> {\n\t\tfor (const write of writes) await this.applyTableWrite(executor, write, seq);\n\t\tawait this.applyDocumentActions(executor, documentActions, seq);\n\t}\n\n\tasync mintId<I extends Id<string>>(): Promise<I> {\n\t\tthis.assertOpen();\n\t\tif (!Number.isSafeInteger(this.nextId)) throw new Error(\"ID space is exhausted\");\n\t\treturn idFromNumber<I>(this.nextId++);\n\t}\n\n\tasync conversation(id: ConversationId, _context: Context): Promise<ConversationRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.conversations} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<ConversationRecord>(row.record);\n\t}\n\n\tasync scanConversations(\n\t\tquery: ConversationQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<ConversationRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst scan = scanSql(start);\n\t\tconst clauses = [scan.clause];\n\t\tconst params: SqliteValue[] = [scan.param];\n\t\tif (query.ownerConversationId !== undefined) {\n\t\t\tclauses.push(\"owner_conversation_id = ?\");\n\t\t\tparams.push(query.ownerConversationId);\n\t\t}\n\t\tif (query.ownerTaskId !== undefined) {\n\t\t\tclauses.push(\"owner_task_id = ?\");\n\t\t\tparams.push(query.ownerTaskId);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.conversations} WHERE ${clauses.join(\" AND \")} ORDER BY id ${scan.direction} LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<ConversationRecord>(row.record)),\n\t\t\tlimit,\n\t\t\tstart.order,\n\t\t);\n\t}\n\n\tentry(id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tentry(\n\t\tconversationId: ConversationId,\n\t\tid: EntryId,\n\t\tcontext: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tentry(\n\t\tidOrConversationId: EntryId | ConversationId,\n\t\tidOrContext: EntryId | Context,\n\t\tcontext?: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined> {\n\t\treturn this.admitRead(() => this.readEntry(idOrConversationId, idOrContext, context));\n\t}\n\n\tfindLatestHeadMarker(\n\t\tconversationId: ConversationId,\n\t\tatOrBeforeEntryId: EntryId | undefined,\n\t\t_context: Context,\n\t): Promise<(EntryRecord & { readonly head: EntryId }) | undefined> {\n\t\treturn this.admitRead(() => this.readLatestHeadMarker(conversationId, atOrBeforeEntryId));\n\t}\n\n\tscanEntries(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\treturn this.admitRead(() => this.readEntries(query, limit, cursor));\n\t}\n\n\tprivate async readEntry(\n\t\tidOrConversationId: EntryId | ConversationId,\n\t\tidOrContext: EntryId | Context,\n\t\tcontext?: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined> {\n\t\tconst id =\n\t\t\tcontext === undefined\n\t\t\t\t? idFromNumber<EntryId>(idOrConversationId)\n\t\t\t\t: typeof idOrContext === \"number\"\n\t\t\t\t\t? idFromNumber<EntryId>(idOrContext)\n\t\t\t\t\t: undefined;\n\t\tif (id === undefined) throw new StorageRequestError(\"Storage.entry() requires an entry ID\");\n\t\tlet conversation: ConversationRecord | undefined;\n\t\tif (context !== undefined) {\n\t\t\tconst conversationId = idFromNumber<ConversationId>(idOrConversationId);\n\t\t\tconversation = await this.readConversation(conversationId);\n\t\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\t}\n\t\tconst row = await this.db.get<EntryJsonRow>(\n\t\t\t`SELECT record, commit_seq FROM ${this.schema.tables.entries} WHERE id = ?`,\n\t\t\tid,\n\t\t);\n\t\tif (row === undefined) return undefined;\n\t\tconst entry = parseJson<EntryRecord>(row.record);\n\t\tif (conversation !== undefined) {\n\t\t\tlet upperEntryId = Number.POSITIVE_INFINITY;\n\t\t\twhile (conversation.id !== entry.conversationId) {\n\t\t\t\tif (conversation.parent === undefined) return undefined;\n\t\t\t\tupperEntryId = Math.min(upperEntryId, conversation.parent.at);\n\t\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t\t}\n\t\t\tif (entry.id > upperEntryId) return undefined;\n\t\t}\n\t\treturn { entry, commitSeq: seqFromNumber(row.commit_seq) };\n\t}\n\n\tprivate async readLatestHeadMarker(\n\t\tconversationId: ConversationId,\n\t\tatOrBeforeEntryId: EntryId | undefined,\n\t): Promise<(EntryRecord & { readonly head: EntryId }) | undefined> {\n\t\tlet conversation = await this.readConversation(conversationId);\n\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\tlet upper: number | undefined = atOrBeforeEntryId;\n\t\twhile (true) {\n\t\t\tconst row =\n\t\t\t\tupper === undefined\n\t\t\t\t\t? await this.db.get<JsonRow>(\n\t\t\t\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL ORDER BY id DESC LIMIT 1`,\n\t\t\t\t\t\t\tconversation.id,\n\t\t\t\t\t\t)\n\t\t\t\t\t: await this.db.get<JsonRow>(\n\t\t\t\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL AND id <= ? ORDER BY id DESC LIMIT 1`,\n\t\t\t\t\t\t\tconversation.id,\n\t\t\t\t\t\t\tupper,\n\t\t\t\t\t\t);\n\t\t\tif (row !== undefined) return parseJson<EntryRecord & { readonly head: EntryId }>(row.record);\n\t\t\tif (conversation.parent === undefined) return undefined;\n\t\t\tupper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);\n\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t}\n\t}\n\n\tprivate async readEntries(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tconst { order, after } = scanStart(query.order, cursor, \"descending\");\n\t\tif (order === \"ascending\") return this.readEntriesAscending(query, limit, after);\n\t\tlet conversation = await this.readConversation(query.conversationId);\n\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${query.conversationId}`);\n\t\tlet upper: number | undefined = query.maxEntryId;\n\t\tif (after !== undefined) upper = Math.min(upper ?? Number.MAX_SAFE_INTEGER, after - 1);\n\t\tconst values: EntryRecord[] = [];\n\t\twhile (true) {\n\t\t\tconst clauses = [\"conversation_id = ?\"];\n\t\t\tconst params: SqliteValue[] = [conversation.id];\n\t\t\tif (query.minEntryId !== undefined) {\n\t\t\t\tclauses.push(\"id >= ?\");\n\t\t\t\tparams.push(query.minEntryId);\n\t\t\t}\n\t\t\tif (upper !== undefined) {\n\t\t\t\tclauses.push(\"id <= ?\");\n\t\t\t\tparams.push(upper);\n\t\t\t}\n\t\t\tparams.push(limit + 1 - values.length);\n\t\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE ${clauses.join(\" AND \")} ORDER BY id DESC LIMIT ?`,\n\t\t\t\t...params,\n\t\t\t);\n\t\t\tvalues.push(...rows.map((row) => parseJson<EntryRecord>(row.record)));\n\t\t\tif (values.length > limit || conversation.parent === undefined) break;\n\t\t\tupper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);\n\t\t\tif (query.minEntryId !== undefined && upper < query.minEntryId) break;\n\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t}\n\t\treturn page(values, limit, \"descending\");\n\t}\n\n\t/** Oldest first: the fork chain's segments from the root conversation forward, each up to its fork point. */\n\tprivate async readEntriesAscending(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tafter: number | undefined,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tconst segments: { readonly conversationId: ConversationId; readonly upper: number | undefined }[] = [];\n\t\tlet conversation = await this.readConversation(query.conversationId);\n\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${query.conversationId}`);\n\t\tlet upper: number | undefined = query.maxEntryId;\n\t\twhile (true) {\n\t\t\tsegments.push({ conversationId: conversation.id, upper });\n\t\t\tif (conversation.parent === undefined) break;\n\t\t\tupper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);\n\t\t\tif (query.minEntryId !== undefined && upper < query.minEntryId) break;\n\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t}\n\t\tlet lower: number | undefined = query.minEntryId;\n\t\tif (after !== undefined) lower = Math.max(lower ?? after + 1, after + 1);\n\t\tconst values: EntryRecord[] = [];\n\t\tfor (const segment of segments.reverse()) {\n\t\t\tconst clauses = [\"conversation_id = ?\"];\n\t\t\tconst params: SqliteValue[] = [segment.conversationId];\n\t\t\tif (lower !== undefined) {\n\t\t\t\tclauses.push(\"id >= ?\");\n\t\t\t\tparams.push(lower);\n\t\t\t}\n\t\t\tif (segment.upper !== undefined) {\n\t\t\t\tclauses.push(\"id <= ?\");\n\t\t\t\tparams.push(segment.upper);\n\t\t\t}\n\t\t\tparams.push(limit + 1 - values.length);\n\t\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE ${clauses.join(\" AND \")} ORDER BY id ASC LIMIT ?`,\n\t\t\t\t...params,\n\t\t\t);\n\t\t\tvalues.push(...rows.map((row) => parseJson<EntryRecord>(row.record)));\n\t\t\tif (values.length > limit) break;\n\t\t}\n\t\treturn page(values, limit, \"ascending\");\n\t}\n\n\tasync task(id: TaskId, _context: Context): Promise<StoredTask | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.tasks} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<StoredTask>(row.record);\n\t}\n\n\tasync scanTasks(\n\t\tquery: TaskQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<StoredTask, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst scan = scanSql(start);\n\t\tconst clauses = [scan.clause];\n\t\tconst params: SqliteValue[] = [scan.param];\n\t\tif (query.conversationId !== undefined) {\n\t\t\tclauses.push(\"conversation_id = ?\");\n\t\t\tparams.push(query.conversationId);\n\t\t}\n\t\tif (query.kind !== undefined) {\n\t\t\tclauses.push(\"kind = ?\");\n\t\t\tparams.push(encodeIndexedString(query.kind));\n\t\t}\n\t\tif (query.status !== undefined) {\n\t\t\tclauses.push(\"status = ?\");\n\t\t\tparams.push(query.status);\n\t\t}\n\t\tif (query.abortRequested !== undefined) {\n\t\t\tclauses.push(\"abort_requested = ?\");\n\t\t\tparams.push(query.abortRequested ? 1 : 0);\n\t\t}\n\t\tif (query.background !== undefined) {\n\t\t\tclauses.push(\"background = ?\");\n\t\t\tparams.push(query.background ? 1 : 0);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.tasks} WHERE ${clauses.join(\" AND \")} ORDER BY id ${scan.direction} LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<StoredTask>(row.record)),\n\t\t\tlimit,\n\t\t\tstart.order,\n\t\t);\n\t}\n\n\tasync submission(id: SubmissionId, _context: Context): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.submissions} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<SubmissionRecord>(row.record);\n\t}\n\n\tasync scanSubmissions(\n\t\tquery: SubmissionQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<SubmissionRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst scan = scanSql(start);\n\t\tconst clauses = [scan.clause];\n\t\tconst params: SqliteValue[] = [scan.param];\n\t\tif (query.conversationId !== undefined) {\n\t\t\tclauses.push(\"conversation_id = ?\");\n\t\t\tparams.push(query.conversationId);\n\t\t}\n\t\tif (query.status !== undefined) {\n\t\t\tclauses.push(\"status = ?\");\n\t\t\tparams.push(query.status);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.submissions} WHERE ${clauses.join(\" AND \")} ORDER BY id ${scan.direction} LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<SubmissionRecord>(row.record)),\n\t\t\tlimit,\n\t\t\tstart.order,\n\t\t);\n\t}\n\n\tasync submissionByRequest(\n\t\tconversationId: ConversationId,\n\t\trequestId: string,\n\t\t_context: Context,\n\t): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.submissions} WHERE conversation_id = ? AND request_id = ?`,\n\t\t\tconversationId,\n\t\t\tencodeIndexedString(requestId),\n\t\t);\n\t\treturn row === undefined ? undefined : parseJson<SubmissionRecord>(row.record);\n\t}\n\n\tasync findDocument(\n\t\taddress: DocumentAddress,\n\t\tat: DocumentPoint,\n\t\t_context: Context,\n\t): Promise<DocumentRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst parts = addressParts(address);\n\t\tconst sql =\n\t\t\tat === \"current\"\n\t\t\t\t? `SELECT record FROM ${this.schema.tables.documents}\n\t\t\t\t\tWHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?\n\t\t\t\t\tAND retired_at IS NULL ORDER BY created_at DESC LIMIT 1`\n\t\t\t\t: `SELECT record FROM ${this.schema.tables.documents}\n\t\t\t\t\tWHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?\n\t\t\t\t\tAND created_at <= ? AND (retired_at IS NULL OR retired_at > ?)\n\t\t\t\t\tORDER BY created_at DESC LIMIT 1`;\n\t\tconst params: SqliteValue[] = [parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue];\n\t\tif (at !== \"current\") params.push(at, at);\n\t\tconst row = await this.db.get<JsonRow>(sql, ...params);\n\t\treturn row === undefined ? undefined : parseJson<DocumentRecord>(row.record);\n\t}\n\n\tasync document(id: DocumentId, at: DocumentPoint, _context: Context): Promise<StoredDocument | undefined> {\n\t\tthis.assertOpen();\n\t\t// The record and revision queries must observe one committed state; a commit between them can replace the base.\n\t\treturn this.db.transaction((transaction) => this.materializeDocument(transaction, id, at));\n\t}\n\n\tasync scanDocuments(\n\t\tquery: DocumentQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<DocumentRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst scope = scopeColumns(query.scope);\n\t\tconst clauses = [\"scope_kind = ?\", \"owner_id = ?\", \"id > ?\"];\n\t\tconst params: SqliteValue[] = [scope.scopeKind, scope.ownerId, cursorId(cursor) ?? -1];\n\t\tif (query.kind !== undefined) {\n\t\t\tclauses.push(\"kind = ?\");\n\t\t\tparams.push(encodeIndexedString(query.kind));\n\t\t}\n\t\tif (query.at === \"current\") {\n\t\t\tclauses.push(\"retired_at IS NULL\");\n\t\t} else {\n\t\t\tclauses.push(\"created_at <= ?\", \"(retired_at IS NULL OR retired_at > ?)\");\n\t\t\tparams.push(query.at, query.at);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.documents} WHERE ${clauses.join(\" AND \")} ORDER BY id LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<DocumentRecord>(row.record)),\n\t\t\tlimit,\n\t\t);\n\t}\n\n\tclose(_context: Context): Promise<void> {\n\t\tif (this.closing === undefined) {\n\t\t\tthis.closed = true;\n\t\t\tthis.closing = this.closeDatabase();\n\t\t}\n\t\treturn this.closing;\n\t}\n\n\tprivate async closeDatabase(): Promise<void> {\n\t\tif (this.admittedReads > 0) {\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tthis.readsDrained = resolve;\n\t\t\t});\n\t\t}\n\t\tawait this.db.close();\n\t}\n\n\t/**\n\t * Run a read that issues several queries. Close waits for admitted reads, so their later queries never reach a\n\t * closed database. Single-query reads and transactions are already ordered before close by the database.\n\t */\n\tprivate async admitRead<T>(read: () => Promise<T>): Promise<T> {\n\t\tthis.assertOpen();\n\t\tthis.admittedReads++;\n\t\ttry {\n\t\t\treturn await read();\n\t\t} finally {\n\t\t\tif (--this.admittedReads === 0) this.readsDrained?.();\n\t\t}\n\t}\n\n\tprivate async readConversation(id: ConversationId): Promise<ConversationRecord | undefined> {\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.conversations} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<ConversationRecord>(row.record);\n\t}\n\n\tprivate async materializeDocument(\n\t\texecutor: SqliteExecutor,\n\t\tid: DocumentId,\n\t\tat: DocumentPoint,\n\t): Promise<StoredDocument | undefined> {\n\t\tconst row = await executor.get<JsonRow>(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id);\n\t\tif (row === undefined) return undefined;\n\t\tconst record = parseJson<DocumentRecord>(row.record);\n\t\tif (at !== \"current\" && isCurrentOnly(record)) {\n\t\t\tthrow new StorageRequestError(`Document ${id} does not retain historical content`);\n\t\t}\n\t\tif (!isAliveAt(record, at)) return undefined;\n\t\tconst upper = at === \"current\" ? Number.MAX_SAFE_INTEGER : at;\n\t\tconst base = await executor.get<RevisionRow>(\n\t\t\t`SELECT seq, kind, version, content FROM ${this.schema.tables.documentRevisions}\n\t\t\t\tWHERE document_id = ? AND kind = 'base' AND seq <= ? ORDER BY seq DESC LIMIT 1`,\n\t\t\tid,\n\t\t\tupper,\n\t\t);\n\t\tif (base === undefined) throw new Error(`Document ${id} is missing a required base`);\n\t\tlet value = parseJson<JsonObject>(base.content);\n\t\tconst tail = await executor.all<RevisionRow>(\n\t\t\t`SELECT seq, kind, version, content FROM ${this.schema.tables.documentRevisions}\n\t\t\t\tWHERE document_id = ? AND seq > ? AND seq <= ? ORDER BY seq`,\n\t\t\tid,\n\t\t\tbase.seq,\n\t\t\tupper,\n\t\t);\n\t\tfor (const revision of tail) {\n\t\t\tif (revision.kind !== \"delta\" || revision.version !== base.version) {\n\t\t\t\tthrow new Error(`Document ${id} crosses a stored version boundary without a base`);\n\t\t\t}\n\t\t\tvalue = apply(value, parseJson<readonly Op[]>(revision.content)) as JsonObject;\n\t\t}\n\t\treturn { record, version: base.version, value, deltasSinceBase: tail.length };\n\t}\n\n\tprivate candidateNextId(writes: readonly StorageWrite[]): number {\n\t\tlet nextId = this.nextId;\n\t\tfor (const write of writes) {\n\t\t\tconst id = writeId(write);\n\t\t\tif (id !== undefined) nextId = Math.max(nextId, id + 1);\n\t\t}\n\t\treturn nextId;\n\t}\n\n\tprivate async checkGlobalIds(executor: SqliteExecutor, writes: readonly StorageWrite[]): Promise<void> {\n\t\tconst claimed = new Map<Id<string>, TableName>();\n\t\tfor (const write of writes) {\n\t\t\tif (write.type === \"document.change\" || write.type === \"document.retire\") continue;\n\t\t\tconst document = write.type === \"document.create\" || write.type === \"document.copy\";\n\t\t\tconst table: TableName = document ? \"document\" : write.type;\n\t\t\tconst id = document ? write.record.id : write.value.id;\n\t\t\tconst existing = (\n\t\t\t\tawait executor.get<RecordIdRow>(`SELECT record_type FROM ${this.schema.tables.recordIds} WHERE id = ?`, id)\n\t\t\t)?.record_type;\n\t\t\tconst earlier = claimed.get(id);\n\t\t\tif (table === \"conversation\" || table === \"entry\" || table === \"document\") {\n\t\t\t\tif (existing !== undefined) throw new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined) throw new Error(`ID ${id} is written more than once`);\n\t\t\t} else {\n\t\t\t\tif (existing !== undefined && existing !== table)\n\t\t\t\t\tthrow new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined && earlier !== table) throw new Error(`ID ${id} is written as two record types`);\n\t\t\t}\n\t\t\tclaimed.set(id, table);\n\t\t}\n\t}\n\n\tprivate prepareDocumentActions(writes: readonly StorageWrite[]): Map<DocumentId, DocumentAction> {\n\t\tconst actions = new Map<DocumentId, DocumentAction>();\n\t\tfor (const write of writes) {\n\t\t\tif (\n\t\t\t\twrite.type !== \"document.create\" &&\n\t\t\t\twrite.type !== \"document.copy\" &&\n\t\t\t\twrite.type !== \"document.change\" &&\n\t\t\t\twrite.type !== \"document.retire\"\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst id = write.type === \"document.create\" || write.type === \"document.copy\" ? write.record.id : write.id;\n\t\t\tlet action = actions.get(id);\n\t\t\tif (action === undefined) {\n\t\t\t\taction = { retire: false };\n\t\t\t\tactions.set(id, action);\n\t\t\t}\n\t\t\tswitch (write.type) {\n\t\t\t\tcase \"document.create\":\n\t\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t\t}\n\t\t\t\t\taction.create = write.record;\n\t\t\t\t\taction.content = write.content;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"document.copy\":\n\t\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t\t}\n\t\t\t\t\taction.create = write.record;\n\t\t\t\t\taction.copy = write.source;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"document.change\":\n\t\t\t\t\tif (action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t\t}\n\t\t\t\t\taction.content = write.content;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"document.retire\":\n\t\t\t\t\tif (action.retire) throw new Error(`Document ${id} is retired more than once`);\n\t\t\t\t\taction.retire = true;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn actions;\n\t}\n\n\tprivate async checkDocumentActions(\n\t\texecutor: SqliteExecutor,\n\t\tactions: ReadonlyMap<DocumentId, DocumentAction>,\n\t): Promise<void> {\n\t\tconst liveCounts = new Map<string, number>();\n\t\tfor (const [id, action] of actions) {\n\t\t\tif (action.copy !== undefined && actions.has(action.copy.id)) {\n\t\t\t\tthrow new Error(`Document copy ${id} source is changed in the copy batch`);\n\t\t\t}\n\t\t\tconst row = await executor.get<JsonRow>(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id);\n\t\t\tconst existing = row === undefined ? undefined : parseJson<DocumentRecord>(row.record);\n\t\t\tif (action.create === undefined && existing === undefined) throw new Error(`Unknown document: ${id}`);\n\t\t\tif (action.create !== undefined && existing !== undefined) throw new Error(`Document ${id} already exists`);\n\t\t\tif (existing?.retiredAt !== undefined) throw new Error(`Document ${id} is retired`);\n\t\t\tif (action.content?.kind === \"delta\") {\n\t\t\t\tconst previous = await executor.get<{ readonly version: number }>(\n\t\t\t\t\t`SELECT version FROM ${this.schema.tables.documentRevisions} WHERE document_id = ? ORDER BY seq DESC LIMIT 1`,\n\t\t\t\t\tid,\n\t\t\t\t);\n\t\t\t\tif (previous === undefined) throw new Error(`Document ${id} delta has no base`);\n\t\t\t\tif (previous.version !== action.content.version) {\n\t\t\t\t\tthrow new Error(`Document ${id} version transition requires a base`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst record = action.create ?? existing!;\n\t\t\tconst key = addressKey(record);\n\t\t\tlet live = liveCounts.get(key);\n\t\t\tif (live === undefined) live = (await this.currentDocumentId(executor, record)) === undefined ? 0 : 1;\n\t\t\tif (action.retire && existing !== undefined) live--;\n\t\t\tif (action.create !== undefined && !action.retire) live++;\n\t\t\tliveCounts.set(key, live);\n\t\t}\n\t\tfor (const live of liveCounts.values()) {\n\t\t\tif (live > 1) throw new Error(\"Document address already has a current incarnation\");\n\t\t}\n\t}\n\n\tprivate async currentDocumentId(\n\t\texecutor: SqliteExecutor,\n\t\taddress: DocumentAddress | DocumentCreate | DocumentRecord,\n\t): Promise<DocumentId | undefined> {\n\t\tconst parts = addressParts(address);\n\t\tconst id = (\n\t\t\tawait executor.get<IdRow>(\n\t\t\t\t`SELECT id FROM ${this.schema.tables.documents}\n\t\t\t\tWHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ? AND retired_at IS NULL\n\t\t\t\tLIMIT 1`,\n\t\t\t\tparts.kind,\n\t\t\t\tparts.scopeKind,\n\t\t\t\tparts.ownerId,\n\t\t\t\tparts.family,\n\t\t\t\tparts.keyValue,\n\t\t\t)\n\t\t)?.id;\n\t\treturn id === undefined ? undefined : idFromNumber<DocumentId>(id);\n\t}\n\n\tprivate async applyTableWrite(executor: SqliteExecutor, write: StorageWrite, seq: Seq): Promise<void> {\n\t\tswitch (write.type) {\n\t\t\tcase \"conversation\":\n\t\t\t\tawait this.claimId(executor, write.value.id, \"conversation\");\n\t\t\t\tawait executor.run(\n\t\t\t\t\t`INSERT INTO ${this.schema.tables.conversations} (id, owner_conversation_id, owner_task_id, record) VALUES (?, ?, ?, ?)`,\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.owner?.conversationId ?? null,\n\t\t\t\t\twrite.value.owner?.taskId ?? null,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"entry\":\n\t\t\t\tawait this.claimId(executor, write.value.id, \"entry\");\n\t\t\t\tawait executor.run(\n\t\t\t\t\t`INSERT INTO ${this.schema.tables.entries} (id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?)`,\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\twrite.value.head ?? null,\n\t\t\t\t\tseq,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"task\":\n\t\t\t\tawait this.claimId(executor, write.value.id, \"task\");\n\t\t\t\tawait executor.run(\n\t\t\t\t\t`INSERT INTO ${this.schema.tables.tasks} (id, conversation_id, kind, status, abort_requested, background, record)\n\t\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?)\n\t\t\t\t\t\tON CONFLICT(id) DO UPDATE SET conversation_id = excluded.conversation_id, kind = excluded.kind,\n\t\t\t\t\t\tstatus = excluded.status, abort_requested = excluded.abort_requested,\n\t\t\t\t\t\tbackground = excluded.background, record = excluded.record`,\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\tencodeIndexedString(write.value.kind),\n\t\t\t\t\twrite.value.state.status,\n\t\t\t\t\twrite.value.abortRequested ? 1 : 0,\n\t\t\t\t\twrite.value.background ? 1 : 0,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"submission\":\n\t\t\t\tawait this.claimId(executor, write.value.id, \"submission\");\n\t\t\t\tawait executor.run(\n\t\t\t\t\t`INSERT INTO ${this.schema.tables.submissions} (id, conversation_id, request_id, status, record) VALUES (?, ?, ?, ?, ?)\n\t\t\t\t\t\tON CONFLICT(id) DO UPDATE SET conversation_id = excluded.conversation_id,\n\t\t\t\t\t\trequest_id = excluded.request_id, status = excluded.status, record = excluded.record`,\n\t\t\t\t\twrite.value.id,\n\t\t\t\t\twrite.value.conversationId,\n\t\t\t\t\twrite.value.requestId === undefined ? null : encodeIndexedString(write.value.requestId),\n\t\t\t\t\twrite.value.status,\n\t\t\t\t\tencodeJson(write.value),\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase \"document.create\":\n\t\t\tcase \"document.copy\":\n\t\t\tcase \"document.change\":\n\t\t\tcase \"document.retire\":\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate async claimId(executor: SqliteExecutor, id: Id<string>, table: TableName): Promise<void> {\n\t\tawait executor.run(\n\t\t\t`INSERT OR IGNORE INTO ${this.schema.tables.recordIds} (id, record_type) VALUES (?, ?)`,\n\t\t\tid,\n\t\t\ttable,\n\t\t);\n\t}\n\n\t/** Resolve each copy to a base of its source's state before this batch, which may not change the source. */\n\tprivate async resolveCopies(executor: SqliteExecutor, actions: Map<DocumentId, DocumentAction>): Promise<void> {\n\t\tfor (const [id, action] of actions) {\n\t\t\tif (action.copy === undefined) continue;\n\t\t\ttry {\n\t\t\t\tconst stored = await this.materializeDocument(executor, action.copy.id, action.copy.at);\n\t\t\t\tif (stored === undefined) throw new Error(`Fork source document ${action.copy.id} cannot be read`);\n\t\t\t\tconst create = action.create!;\n\t\t\t\tif (\n\t\t\t\t\tstored.record.scope.kind !== \"conversation\" ||\n\t\t\t\t\tcreate.scope.kind !== \"conversation\" ||\n\t\t\t\t\tstored.record.kind !== create.kind ||\n\t\t\t\t\tstored.record.key !== create.key ||\n\t\t\t\t\tstored.record.history !== create.history ||\n\t\t\t\t\tstored.record.fork !== create.fork\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Fork source document ${action.copy.id} does not match the copied record`);\n\t\t\t\t}\n\t\t\t\taction.content = { kind: \"base\", version: stored.version, value: stored.value };\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`Document copy ${id} was rejected`, { cause: error });\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async applyDocumentActions(\n\t\texecutor: SqliteExecutor,\n\t\tactions: ReadonlyMap<DocumentId, DocumentAction>,\n\t\tseq: Seq,\n\t): Promise<void> {\n\t\tfor (const [id, action] of actions) {\n\t\t\t// Copies are resolved to their content by `resolveCopies()`.\n\t\t\tconst content = action.content;\n\t\t\tlet record: DocumentRecord;\n\t\t\tif (action.create !== undefined) {\n\t\t\t\trecord = {\n\t\t\t\t\t...action.create,\n\t\t\t\t\tcreatedAt: seq,\n\t\t\t\t\t...(action.retire ? { retiredAt: seq } : {}),\n\t\t\t\t};\n\t\t\t\tconst parts = addressParts(record);\n\t\t\t\tawait this.claimId(executor, id, \"document\");\n\t\t\t\tawait executor.run(\n\t\t\t\t\t`INSERT INTO ${this.schema.tables.documents}\n\t\t\t\t\t\t(id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record)\n\t\t\t\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\t\t\t\tid,\n\t\t\t\t\tparts.kind,\n\t\t\t\t\tparts.family,\n\t\t\t\t\tparts.keyValue,\n\t\t\t\t\tparts.scopeKind,\n\t\t\t\t\tparts.ownerId,\n\t\t\t\t\tseq,\n\t\t\t\t\taction.retire ? seq : null,\n\t\t\t\t\tencodeJson(record),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst row = (await executor.get<JsonRow>(\n\t\t\t\t\t`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`,\n\t\t\t\t\tid,\n\t\t\t\t))!;\n\t\t\t\trecord = parseJson<DocumentRecord>(row.record);\n\t\t\t}\n\n\t\t\tif (content !== undefined) {\n\t\t\t\tif (content.kind === \"base\" && isCurrentOnly(record)) {\n\t\t\t\t\tawait executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id);\n\t\t\t\t}\n\t\t\t\tconst encodedContent = content.kind === \"base\" ? encodeJson(content.value) : encodeJson(content.ops);\n\t\t\t\tawait executor.run(\n\t\t\t\t\t`INSERT INTO ${this.schema.tables.documentRevisions} (document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?)`,\n\t\t\t\t\tid,\n\t\t\t\t\tseq,\n\t\t\t\t\tcontent.kind,\n\t\t\t\t\tcontent.version,\n\t\t\t\t\tencodedContent,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (action.retire) {\n\t\t\t\tif (action.create === undefined) {\n\t\t\t\t\trecord = { ...record, retiredAt: seq };\n\t\t\t\t\tawait executor.run(\n\t\t\t\t\t\t`UPDATE ${this.schema.tables.documents} SET retired_at = ?, record = ? WHERE id = ?`,\n\t\t\t\t\t\tseq,\n\t\t\t\t\t\tencodeJson(record),\n\t\t\t\t\t\tid,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (isCurrentOnly(record)) {\n\t\t\t\t\tawait executor.run(`DELETE FROM ${this.schema.tables.documentRevisions} WHERE document_id = ?`, id);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate assertOpen(): void {\n\t\tif (this.closed) throw new Error(\"SqliteStorage is closed\");\n\t}\n}\n"]}
1
+ {"version":3,"file":"storage.js","sourceRoot":"","sources":["../../../src/storage/sqlite/storage.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAW,MAAM,6BAA6B,CAAC;AAG7D,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AA+B3D,OAAO,EAAE,UAAU,EAAkB,SAAS,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,OAAO,EAAuB,aAAa,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAC/G,OAAO,EAAE,8BAA8B,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,aAAa,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACtG,OAAO,EAAE,kBAAkB,EAAqB,MAAM,aAAa,CAAC;AAqBpE,MAAM,QAAQ,GAAG,CAAuB,MAA0B,EAAiB,EAAE;IACpF,MAAM,KAAK,GAAG,MAAM,EAAE,KAAK,CAAC;IAC5B,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC;QAC5D,MAAM,IAAI,mBAAmB,CAAC,wBAAwB,CAAC,CAAC;IACzD,OAAO,YAAY,CAAI,KAAK,CAAC,CAAC;AAC/B,CAAC,CAAC;AAEF,MAAM,IAAI,GAAG,CACZ,MAAoB,EACpB,KAAa,EACb,KAAK,GAAc,WAAW,EACZ,EAAE;IACpB,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;IACrC,IAAI,MAAM,CAAC,MAAM,IAAI,KAAK;QAA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C;QACF,CAAC;IACF,CAAC;IAEO,UAAU;QACjB,IAAI,IAAI,CAAC,MAAM;YAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7D,CAAC;CACD","sourcesContent":["import type { Context } from \"@earendil-works/chord/context\";\nimport { apply, type Op } from \"@earendil-works/chord/delta\";\nimport type { JsonValue } from \"@earendil-works/chord/json\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteValue } from \"@earendil-works/chord/sqlite\";\nimport { StorageRequestError } from \"../../errors.ts\";\nimport { idFromNumber, seqFromNumber } from \"../../ids.ts\";\nimport type {\n\tCommitResult,\n\tConversationId,\n\tConversationQuery,\n\tConversationRecord,\n\tCursor,\n\tDocumentAddress,\n\tDocumentContent,\n\tDocumentId,\n\tDocumentPoint,\n\tDocumentQuery,\n\tDocumentRecord,\n\tEntryId,\n\tEntryQuery,\n\tEntryRecord,\n\tId,\n\tJsonObject,\n\tPage,\n\tScanOrder,\n\tSeq,\n\tStorage,\n\tStorageWrite,\n\tStoredDocument,\n\tSubmissionId,\n\tSubmissionQuery,\n\tSubmissionRecord,\n\tTaskId,\n\tTaskQuery,\n\tTaskRecord,\n} from \"../../types.ts\";\nimport { nextCursor, type ScanStart, scanStart } from \"../scan.ts\";\nimport { CommitState, claimOf, type DocumentAction, PendingWrites, prepareDocumentActions } from \"./commit.ts\";\nimport { applySqliteMigrationsForSchema } from \"./migrations.ts\";\nimport { addressParts, encodeIndexedString, isCurrentOnly, parseJson, scopeColumns } from \"./rows.ts\";\nimport { createSqliteSchema, type SqliteSchema } from \"./schema.ts\";\n\ntype StoredTask = TaskRecord<JsonValue, JsonValue, JsonValue>;\ntype JsonRow = { readonly record: string };\ntype EntryJsonRow = { readonly record: string; readonly commit_seq: number };\ntype RevisionRow = {\n\treadonly seq: number;\n\treadonly kind: DocumentContent[\"kind\"];\n\treadonly version: number;\n\treadonly content: string;\n};\ntype MetadataRow = { readonly next_id: string; readonly next_seq: number };\n\nexport type SqliteStorageOptions = {\n\t/**\n\t * Prefix for every table and index in the durable schema. It must be a SQLite identifier and must not use\n\t * SQLite's reserved `sqlite_` prefix. Existing data is not migrated when this changes.\n\t */\n\treadonly prefix?: string;\n};\n\nconst cursorId = <I extends Id<string>>(cursor: Cursor | undefined): I | undefined => {\n\tconst after = cursor?.after;\n\tif (after === undefined) return undefined;\n\tif (typeof after !== \"number\" || !Number.isSafeInteger(after))\n\t\tthrow new StorageRequestError(\"Invalid storage cursor\");\n\treturn idFromNumber<I>(after);\n};\n\nconst page = <T extends { readonly id: Id<string> }>(\n\tvalues: readonly T[],\n\tlimit: number,\n\torder: ScanOrder = \"ascending\",\n): Page<T, Cursor> => {\n\tconst items = values.slice(0, limit);\n\tif (values.length <= limit) return { items };\n\treturn { items, next: nextCursor(items.at(-1)!.id, order) };\n};\n\n/** The ID condition, its parameter, and the `ORDER BY` direction of a table scan. */\nconst scanSql = (start: ScanStart): { readonly clause: string; readonly param: number; readonly direction: string } =>\n\tstart.order === \"ascending\"\n\t\t? { clause: \"id > ?\", param: start.after ?? -1, direction: \"ASC\" }\n\t\t: { clause: \"id < ?\", param: start.after ?? Number.MAX_SAFE_INTEGER, direction: \"DESC\" };\n\nconst isAliveAt = (record: DocumentRecord, at: DocumentPoint): boolean => {\n\tif (at === \"current\") return record.retiredAt === undefined;\n\treturn record.createdAt <= at && (record.retiredAt === undefined || at < record.retiredAt);\n};\n\n/** Whether a database call of the checks failed, whatever it threw or rejected with. */\ntype CheckCalls = { failed: boolean };\n\n/**\n * `executor`, setting `calls.failed` when one of its calls throws, synchronously (a synchronous driver) or by\n * rejecting, with any value: then a failing check is the database's, not one of Durable's own.\n */\nfunction watchCalls(executor: SqliteExecutor, calls: CheckCalls): SqliteExecutor {\n\tconst watched = async <T>(call: () => Promise<T>): Promise<T> => {\n\t\ttry {\n\t\t\treturn await call();\n\t\t} catch (error) {\n\t\t\tcalls.failed = true;\n\t\t\tthrow error;\n\t\t}\n\t};\n\treturn {\n\t\texec: (sql) => watched(() => executor.exec(sql)),\n\t\trun: (sql, ...params) => watched(() => executor.run(sql, ...params)),\n\t\trunCounted: (sql, ...params) => watched(() => executor.runCounted(sql, ...params)),\n\t\tget: (sql, ...params) => watched(() => executor.get(sql, ...params)),\n\t\tall: (sql, ...params) => watched(() => executor.all(sql, ...params)),\n\t};\n}\n\n/** Portable SQLite implementation of the Pico storage contract. */\nexport class SqliteStorage implements Storage {\n\tprivate readonly db: SqliteDatabase;\n\tprivate readonly schema: SqliteSchema;\n\tprivate nextId: number;\n\tprivate closed = false;\n\tprivate closing: Promise<void> | undefined;\n\tprivate admittedReads = 0;\n\tprivate readsDrained: (() => void) | undefined;\n\n\tprivate constructor(db: SqliteDatabase, schema: SqliteSchema, nextId: number) {\n\t\tthis.db = db;\n\t\tthis.schema = schema;\n\t\tthis.nextId = nextId;\n\t}\n\n\t/** Initialize storage over an owned SQLite database facade. */\n\tstatic async open(db: SqliteDatabase, options: SqliteStorageOptions = {}): Promise<SqliteStorage> {\n\t\ttry {\n\t\t\tconst schema = createSqliteSchema(options.prefix);\n\t\t\tawait applySqliteMigrationsForSchema(db, schema);\n\t\t\tconst metadata = await db.get<MetadataRow>(\n\t\t\t\t`SELECT next_id, next_seq FROM ${schema.tables.durableMetadata} WHERE singleton = 1`,\n\t\t\t);\n\t\t\tif (metadata === undefined) throw new Error(\"Durable SQLite metadata is missing\");\n\t\t\treturn new SqliteStorage(db, schema, Number(metadata.next_id));\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait db.close();\n\t\t\t} catch {\n\t\t\t\t// Preserve the initialization failure.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Commit `batches` in one SQL transaction, each with its own seq. Each batch is checked before it writes anything,\n\t * against the state the earlier ones left, and the first one refused ends the batch: the transaction commits the ones\n\t * before it. No savepoints, which Durable Objects do not allow: the checks run before the writes instead. The checks\n\t * read the stored state of all batches up front and run in memory, and the accepted batches are written per table in\n\t * multi-row statements (`commit.ts`), so a call costs a few statements whatever its number of batches. A batch with a\n\t * copy reads the copy's source from the database: the batches before it are written first, so a call of many fork\n\t * batches costs a few statements per fork.\n\t */\n\tasync commit(\n\t\tbatches: readonly (readonly StorageWrite[])[],\n\t\treceive: (index: number, seq: Seq) => void,\n\t\t_context: Context,\n\t): Promise<CommitResult> {\n\t\tthis.assertOpen();\n\t\tconst seqs: Seq[] = [];\n\t\tlet refused: { readonly error: unknown } | undefined;\n\t\tlet candidateNextId = this.nextId;\n\t\tawait this.db.transaction(async (transaction) => {\n\t\t\tconst metadata = await this.readMetadata(transaction);\n\t\t\tlet next = metadata.next_seq;\n\t\t\t// A failure of the database rejects the call and rolls back the batches before it with the transaction.\n\t\t\tconst state = await CommitState.read(transaction, this.schema.tables, batches);\n\t\t\tconst pending = new PendingWrites();\n\t\t\tfor (const writes of batches) {\n\t\t\t\tconst checked = await this.checkBatch(transaction, state, pending, writes);\n\t\t\t\tif (\"refused\" in checked) {\n\t\t\t\t\trefused = { error: checked.refused };\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tconst seq = seqFromNumber(next++);\n\t\t\t\tstate.apply(writes, checked.actions, seq);\n\t\t\t\tpending.add(writes, checked.actions, seq, state);\n\t\t\t\tseqs.push(seq);\n\t\t\t\tcandidateNextId = Math.max(candidateNextId, this.candidateNextId(writes));\n\t\t\t}\n\t\t\tawait pending.flush(transaction, this.schema.tables);\n\t\t\tif (seqs.length > 0) {\n\t\t\t\tawait this.writeMetadata(transaction, Math.max(Number(metadata.next_id), candidateNextId), next);\n\t\t\t}\n\t\t});\n\t\tthis.nextId = Math.max(this.nextId, candidateNextId);\n\t\t// `COMMIT` returned: the stored batches are durable.\n\t\tfor (const [index, seq] of seqs.entries()) receive(index, seq);\n\t\treturn refused === undefined ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error };\n\t}\n\n\tprivate async readMetadata(executor: SqliteExecutor): Promise<MetadataRow> {\n\t\tconst metadata = await executor.get<MetadataRow>(\n\t\t\t`SELECT next_id, next_seq FROM ${this.schema.tables.durableMetadata} WHERE singleton = 1`,\n\t\t);\n\t\tif (metadata === undefined) throw new Error(\"Durable SQLite metadata is missing\");\n\t\treturn metadata;\n\t}\n\n\tprivate async writeMetadata(executor: SqliteExecutor, nextId: number, nextSeq: number): Promise<void> {\n\t\tawait executor.run(\n\t\t\t`UPDATE ${this.schema.tables.durableMetadata} SET next_id = ?, next_seq = ? WHERE singleton = 1`,\n\t\t\tString(nextId),\n\t\t\tnextSeq,\n\t\t);\n\t}\n\n\t/**\n\t * Durable's own checks of one batch, against what the batches before it left: its document actions, or its refusal.\n\t * Only these checks refuse; a failure of a database call rejects. A copy reads its source from the database, so the\n\t * batches before it are written first.\n\t */\n\tprivate async checkBatch(\n\t\ttransaction: SqliteExecutor,\n\t\tstate: CommitState,\n\t\tpending: PendingWrites,\n\t\twrites: readonly StorageWrite[],\n\t): Promise<{ readonly actions: Map<DocumentId, DocumentAction> } | { readonly refused: unknown }> {\n\t\tlet actions: Map<DocumentId, DocumentAction>;\n\t\ttry {\n\t\t\tactions = prepareDocumentActions(writes);\n\t\t\tstate.check(writes, actions);\n\t\t} catch (error) {\n\t\t\treturn { refused: error };\n\t\t}\n\t\tif (![...actions.values()].some((action) => action.copy !== undefined)) return { actions };\n\t\tawait pending.flush(transaction, this.schema.tables);\n\t\tconst calls: CheckCalls = { failed: false };\n\t\ttry {\n\t\t\tawait this.resolveCopies(watchCalls(transaction, calls), actions);\n\t\t} catch (error) {\n\t\t\tif (calls.failed) throw error;\n\t\t\treturn { refused: error };\n\t\t}\n\t\treturn { actions };\n\t}\n\n\tasync mintId<I extends Id<string>>(): Promise<I> {\n\t\tthis.assertOpen();\n\t\tif (!Number.isSafeInteger(this.nextId)) throw new Error(\"ID space is exhausted\");\n\t\treturn idFromNumber<I>(this.nextId++);\n\t}\n\n\tasync conversation(id: ConversationId, _context: Context): Promise<ConversationRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.conversations} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<ConversationRecord>(row.record);\n\t}\n\n\tasync scanConversations(\n\t\tquery: ConversationQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<ConversationRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst scan = scanSql(start);\n\t\tconst clauses = [scan.clause];\n\t\tconst params: SqliteValue[] = [scan.param];\n\t\tif (query.ownerConversationId !== undefined) {\n\t\t\tclauses.push(\"owner_conversation_id = ?\");\n\t\t\tparams.push(query.ownerConversationId);\n\t\t}\n\t\tif (query.ownerTaskId !== undefined) {\n\t\t\tclauses.push(\"owner_task_id = ?\");\n\t\t\tparams.push(query.ownerTaskId);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.conversations} WHERE ${clauses.join(\" AND \")} ORDER BY id ${scan.direction} LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<ConversationRecord>(row.record)),\n\t\t\tlimit,\n\t\t\tstart.order,\n\t\t);\n\t}\n\n\tentry(id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tentry(\n\t\tconversationId: ConversationId,\n\t\tid: EntryId,\n\t\tcontext: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;\n\tentry(\n\t\tidOrConversationId: EntryId | ConversationId,\n\t\tidOrContext: EntryId | Context,\n\t\tcontext?: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined> {\n\t\treturn this.admitRead(() => this.readEntry(idOrConversationId, idOrContext, context));\n\t}\n\n\tfindLatestHeadMarker(\n\t\tconversationId: ConversationId,\n\t\tatOrBeforeEntryId: EntryId | undefined,\n\t\t_context: Context,\n\t): Promise<(EntryRecord & { readonly head: EntryId }) | undefined> {\n\t\treturn this.admitRead(() => this.readLatestHeadMarker(conversationId, atOrBeforeEntryId));\n\t}\n\n\tscanEntries(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\treturn this.admitRead(() => this.readEntries(query, limit, cursor));\n\t}\n\n\tprivate async readEntry(\n\t\tidOrConversationId: EntryId | ConversationId,\n\t\tidOrContext: EntryId | Context,\n\t\tcontext?: Context,\n\t): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined> {\n\t\tconst id =\n\t\t\tcontext === undefined\n\t\t\t\t? idFromNumber<EntryId>(idOrConversationId)\n\t\t\t\t: typeof idOrContext === \"number\"\n\t\t\t\t\t? idFromNumber<EntryId>(idOrContext)\n\t\t\t\t\t: undefined;\n\t\tif (id === undefined) throw new StorageRequestError(\"Storage.entry() requires an entry ID\");\n\t\tlet conversation: ConversationRecord | undefined;\n\t\tif (context !== undefined) {\n\t\t\tconst conversationId = idFromNumber<ConversationId>(idOrConversationId);\n\t\t\tconversation = await this.readConversation(conversationId);\n\t\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\t}\n\t\tconst row = await this.db.get<EntryJsonRow>(\n\t\t\t`SELECT record, commit_seq FROM ${this.schema.tables.entries} WHERE id = ?`,\n\t\t\tid,\n\t\t);\n\t\tif (row === undefined) return undefined;\n\t\tconst entry = parseJson<EntryRecord>(row.record);\n\t\tif (conversation !== undefined) {\n\t\t\tlet upperEntryId = Number.POSITIVE_INFINITY;\n\t\t\twhile (conversation.id !== entry.conversationId) {\n\t\t\t\tif (conversation.parent === undefined) return undefined;\n\t\t\t\tupperEntryId = Math.min(upperEntryId, conversation.parent.at);\n\t\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t\t}\n\t\t\tif (entry.id > upperEntryId) return undefined;\n\t\t}\n\t\treturn { entry, commitSeq: seqFromNumber(row.commit_seq) };\n\t}\n\n\tprivate async readLatestHeadMarker(\n\t\tconversationId: ConversationId,\n\t\tatOrBeforeEntryId: EntryId | undefined,\n\t): Promise<(EntryRecord & { readonly head: EntryId }) | undefined> {\n\t\tlet conversation = await this.readConversation(conversationId);\n\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${conversationId}`);\n\t\tlet upper: number | undefined = atOrBeforeEntryId;\n\t\twhile (true) {\n\t\t\tconst row =\n\t\t\t\tupper === undefined\n\t\t\t\t\t? await this.db.get<JsonRow>(\n\t\t\t\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL ORDER BY id DESC LIMIT 1`,\n\t\t\t\t\t\t\tconversation.id,\n\t\t\t\t\t\t)\n\t\t\t\t\t: await this.db.get<JsonRow>(\n\t\t\t\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE conversation_id = ? AND head IS NOT NULL AND id <= ? ORDER BY id DESC LIMIT 1`,\n\t\t\t\t\t\t\tconversation.id,\n\t\t\t\t\t\t\tupper,\n\t\t\t\t\t\t);\n\t\t\tif (row !== undefined) return parseJson<EntryRecord & { readonly head: EntryId }>(row.record);\n\t\t\tif (conversation.parent === undefined) return undefined;\n\t\t\tupper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);\n\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t}\n\t}\n\n\tprivate async readEntries(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tconst { order, after } = scanStart(query.order, cursor, \"descending\");\n\t\tif (order === \"ascending\") return this.readEntriesAscending(query, limit, after);\n\t\tlet conversation = await this.readConversation(query.conversationId);\n\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${query.conversationId}`);\n\t\tlet upper: number | undefined = query.maxEntryId;\n\t\tif (after !== undefined) upper = Math.min(upper ?? Number.MAX_SAFE_INTEGER, after - 1);\n\t\tconst values: EntryRecord[] = [];\n\t\twhile (true) {\n\t\t\tconst clauses = [\"conversation_id = ?\"];\n\t\t\tconst params: SqliteValue[] = [conversation.id];\n\t\t\tif (query.minEntryId !== undefined) {\n\t\t\t\tclauses.push(\"id >= ?\");\n\t\t\t\tparams.push(query.minEntryId);\n\t\t\t}\n\t\t\tif (upper !== undefined) {\n\t\t\t\tclauses.push(\"id <= ?\");\n\t\t\t\tparams.push(upper);\n\t\t\t}\n\t\t\tparams.push(limit + 1 - values.length);\n\t\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE ${clauses.join(\" AND \")} ORDER BY id DESC LIMIT ?`,\n\t\t\t\t...params,\n\t\t\t);\n\t\t\tvalues.push(...rows.map((row) => parseJson<EntryRecord>(row.record)));\n\t\t\tif (values.length > limit || conversation.parent === undefined) break;\n\t\t\tupper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);\n\t\t\tif (query.minEntryId !== undefined && upper < query.minEntryId) break;\n\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t}\n\t\treturn page(values, limit, \"descending\");\n\t}\n\n\t/** Oldest first: the fork chain's segments from the root conversation forward, each up to its fork point. */\n\tprivate async readEntriesAscending(\n\t\tquery: EntryQuery,\n\t\tlimit: number,\n\t\tafter: number | undefined,\n\t): Promise<Page<EntryRecord, Cursor>> {\n\t\tconst segments: { readonly conversationId: ConversationId; readonly upper: number | undefined }[] = [];\n\t\tlet conversation = await this.readConversation(query.conversationId);\n\t\tif (conversation === undefined) throw new StorageRequestError(`Unknown conversation: ${query.conversationId}`);\n\t\tlet upper: number | undefined = query.maxEntryId;\n\t\twhile (true) {\n\t\t\tsegments.push({ conversationId: conversation.id, upper });\n\t\t\tif (conversation.parent === undefined) break;\n\t\t\tupper = upper === undefined ? conversation.parent.at : Math.min(upper, conversation.parent.at);\n\t\t\tif (query.minEntryId !== undefined && upper < query.minEntryId) break;\n\t\t\tconversation = (await this.readConversation(conversation.parent.conversationId))!;\n\t\t}\n\t\tlet lower: number | undefined = query.minEntryId;\n\t\tif (after !== undefined) lower = Math.max(lower ?? after + 1, after + 1);\n\t\tconst values: EntryRecord[] = [];\n\t\tfor (const segment of segments.reverse()) {\n\t\t\tconst clauses = [\"conversation_id = ?\"];\n\t\t\tconst params: SqliteValue[] = [segment.conversationId];\n\t\t\tif (lower !== undefined) {\n\t\t\t\tclauses.push(\"id >= ?\");\n\t\t\t\tparams.push(lower);\n\t\t\t}\n\t\t\tif (segment.upper !== undefined) {\n\t\t\t\tclauses.push(\"id <= ?\");\n\t\t\t\tparams.push(segment.upper);\n\t\t\t}\n\t\t\tparams.push(limit + 1 - values.length);\n\t\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t\t`SELECT record FROM ${this.schema.tables.entries} WHERE ${clauses.join(\" AND \")} ORDER BY id ASC LIMIT ?`,\n\t\t\t\t...params,\n\t\t\t);\n\t\t\tvalues.push(...rows.map((row) => parseJson<EntryRecord>(row.record)));\n\t\t\tif (values.length > limit) break;\n\t\t}\n\t\treturn page(values, limit, \"ascending\");\n\t}\n\n\tasync task(id: TaskId, _context: Context): Promise<StoredTask | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.tasks} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<StoredTask>(row.record);\n\t}\n\n\tasync scanTasks(\n\t\tquery: TaskQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<StoredTask, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst scan = scanSql(start);\n\t\tconst clauses = [scan.clause];\n\t\tconst params: SqliteValue[] = [scan.param];\n\t\tif (query.conversationId !== undefined) {\n\t\t\tclauses.push(\"conversation_id = ?\");\n\t\t\tparams.push(query.conversationId);\n\t\t}\n\t\tif (query.kind !== undefined) {\n\t\t\tclauses.push(\"kind = ?\");\n\t\t\tparams.push(encodeIndexedString(query.kind));\n\t\t}\n\t\tif (query.status !== undefined) {\n\t\t\tclauses.push(\"status = ?\");\n\t\t\tparams.push(query.status);\n\t\t}\n\t\tif (query.abortRequested !== undefined) {\n\t\t\tclauses.push(\"abort_requested = ?\");\n\t\t\tparams.push(query.abortRequested ? 1 : 0);\n\t\t}\n\t\tif (query.background !== undefined) {\n\t\t\tclauses.push(\"background = ?\");\n\t\t\tparams.push(query.background ? 1 : 0);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.tasks} WHERE ${clauses.join(\" AND \")} ORDER BY id ${scan.direction} LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<StoredTask>(row.record)),\n\t\t\tlimit,\n\t\t\tstart.order,\n\t\t);\n\t}\n\n\tasync submission(id: SubmissionId, _context: Context): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.submissions} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<SubmissionRecord>(row.record);\n\t}\n\n\tasync scanSubmissions(\n\t\tquery: SubmissionQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<SubmissionRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst start = scanStart(query.order, cursor, \"ascending\");\n\t\tconst scan = scanSql(start);\n\t\tconst clauses = [scan.clause];\n\t\tconst params: SqliteValue[] = [scan.param];\n\t\tif (query.conversationId !== undefined) {\n\t\t\tclauses.push(\"conversation_id = ?\");\n\t\t\tparams.push(query.conversationId);\n\t\t}\n\t\tif (query.status !== undefined) {\n\t\t\tclauses.push(\"status = ?\");\n\t\t\tparams.push(query.status);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.submissions} WHERE ${clauses.join(\" AND \")} ORDER BY id ${scan.direction} LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<SubmissionRecord>(row.record)),\n\t\t\tlimit,\n\t\t\tstart.order,\n\t\t);\n\t}\n\n\tasync submissionByRequest(\n\t\tconversationId: ConversationId,\n\t\trequestId: string,\n\t\t_context: Context,\n\t): Promise<SubmissionRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst row = await this.db.get<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.submissions} WHERE conversation_id = ? AND request_id = ?`,\n\t\t\tconversationId,\n\t\t\tencodeIndexedString(requestId),\n\t\t);\n\t\treturn row === undefined ? undefined : parseJson<SubmissionRecord>(row.record);\n\t}\n\n\tasync findDocument(\n\t\taddress: DocumentAddress,\n\t\tat: DocumentPoint,\n\t\t_context: Context,\n\t): Promise<DocumentRecord | undefined> {\n\t\tthis.assertOpen();\n\t\tconst parts = addressParts(address);\n\t\tconst sql =\n\t\t\tat === \"current\"\n\t\t\t\t? `SELECT record FROM ${this.schema.tables.documents}\n\t\t\t\t\tWHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?\n\t\t\t\t\tAND retired_at IS NULL ORDER BY created_at DESC LIMIT 1`\n\t\t\t\t: `SELECT record FROM ${this.schema.tables.documents}\n\t\t\t\t\tWHERE kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?\n\t\t\t\t\tAND created_at <= ? AND (retired_at IS NULL OR retired_at > ?)\n\t\t\t\t\tORDER BY created_at DESC LIMIT 1`;\n\t\tconst params: SqliteValue[] = [parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue];\n\t\tif (at !== \"current\") params.push(at, at);\n\t\tconst row = await this.db.get<JsonRow>(sql, ...params);\n\t\treturn row === undefined ? undefined : parseJson<DocumentRecord>(row.record);\n\t}\n\n\tasync document(id: DocumentId, at: DocumentPoint, _context: Context): Promise<StoredDocument | undefined> {\n\t\tthis.assertOpen();\n\t\t// The record and revision queries must observe one committed state; a commit between them can replace the base.\n\t\treturn this.db.transaction((transaction) => this.materializeDocument(transaction, id, at));\n\t}\n\n\tasync scanDocuments(\n\t\tquery: DocumentQuery,\n\t\tlimit: number,\n\t\tcursor: Cursor | undefined,\n\t\t_context: Context,\n\t): Promise<Page<DocumentRecord, Cursor>> {\n\t\tthis.assertOpen();\n\t\tconst scope = scopeColumns(query.scope);\n\t\tconst clauses = [\"scope_kind = ?\", \"owner_id = ?\", \"id > ?\"];\n\t\tconst params: SqliteValue[] = [scope.scopeKind, scope.ownerId, cursorId(cursor) ?? -1];\n\t\tif (query.kind !== undefined) {\n\t\t\tclauses.push(\"kind = ?\");\n\t\t\tparams.push(encodeIndexedString(query.kind));\n\t\t}\n\t\tif (query.at === \"current\") {\n\t\t\tclauses.push(\"retired_at IS NULL\");\n\t\t} else {\n\t\t\tclauses.push(\"created_at <= ?\", \"(retired_at IS NULL OR retired_at > ?)\");\n\t\t\tparams.push(query.at, query.at);\n\t\t}\n\t\tparams.push(limit + 1);\n\t\tconst rows = await this.db.all<JsonRow>(\n\t\t\t`SELECT record FROM ${this.schema.tables.documents} WHERE ${clauses.join(\" AND \")} ORDER BY id LIMIT ?`,\n\t\t\t...params,\n\t\t);\n\t\treturn page(\n\t\t\trows.map((row) => parseJson<DocumentRecord>(row.record)),\n\t\t\tlimit,\n\t\t);\n\t}\n\n\tclose(_context: Context): Promise<void> {\n\t\tif (this.closing === undefined) {\n\t\t\tthis.closed = true;\n\t\t\tthis.closing = this.closeDatabase();\n\t\t}\n\t\treturn this.closing;\n\t}\n\n\tprivate async closeDatabase(): Promise<void> {\n\t\tif (this.admittedReads > 0) {\n\t\t\tawait new Promise<void>((resolve) => {\n\t\t\t\tthis.readsDrained = resolve;\n\t\t\t});\n\t\t}\n\t\tawait this.db.close();\n\t}\n\n\t/**\n\t * Run a read that issues several queries. Close waits for admitted reads, so their later queries never reach a\n\t * closed database. Single-query reads and transactions are already ordered before close by the database.\n\t */\n\tprivate async admitRead<T>(read: () => Promise<T>): Promise<T> {\n\t\tthis.assertOpen();\n\t\tthis.admittedReads++;\n\t\ttry {\n\t\t\treturn await read();\n\t\t} finally {\n\t\t\tif (--this.admittedReads === 0) this.readsDrained?.();\n\t\t}\n\t}\n\n\tprivate async readConversation(id: ConversationId): Promise<ConversationRecord | undefined> {\n\t\tconst row = await this.db.get<JsonRow>(`SELECT record FROM ${this.schema.tables.conversations} WHERE id = ?`, id);\n\t\treturn row === undefined ? undefined : parseJson<ConversationRecord>(row.record);\n\t}\n\n\tprivate async materializeDocument(\n\t\texecutor: SqliteExecutor,\n\t\tid: DocumentId,\n\t\tat: DocumentPoint,\n\t): Promise<StoredDocument | undefined> {\n\t\tconst row = await executor.get<JsonRow>(`SELECT record FROM ${this.schema.tables.documents} WHERE id = ?`, id);\n\t\tif (row === undefined) return undefined;\n\t\tconst record = parseJson<DocumentRecord>(row.record);\n\t\tif (at !== \"current\" && isCurrentOnly(record)) {\n\t\t\tthrow new StorageRequestError(`Document ${id} does not retain historical content`);\n\t\t}\n\t\tif (!isAliveAt(record, at)) return undefined;\n\t\tconst upper = at === \"current\" ? Number.MAX_SAFE_INTEGER : at;\n\t\tconst base = await executor.get<RevisionRow>(\n\t\t\t`SELECT seq, kind, version, content FROM ${this.schema.tables.documentRevisions}\n\t\t\t\tWHERE document_id = ? AND kind = 'base' AND seq <= ? ORDER BY seq DESC LIMIT 1`,\n\t\t\tid,\n\t\t\tupper,\n\t\t);\n\t\tif (base === undefined) throw new Error(`Document ${id} is missing a required base`);\n\t\tlet value = parseJson<JsonObject>(base.content);\n\t\tconst tail = await executor.all<RevisionRow>(\n\t\t\t`SELECT seq, kind, version, content FROM ${this.schema.tables.documentRevisions}\n\t\t\t\tWHERE document_id = ? AND seq > ? AND seq <= ? ORDER BY seq`,\n\t\t\tid,\n\t\t\tbase.seq,\n\t\t\tupper,\n\t\t);\n\t\tfor (const revision of tail) {\n\t\t\tif (revision.kind !== \"delta\" || revision.version !== base.version) {\n\t\t\t\tthrow new Error(`Document ${id} crosses a stored version boundary without a base`);\n\t\t\t}\n\t\t\tvalue = apply(value, parseJson<readonly Op[]>(revision.content)) as JsonObject;\n\t\t}\n\t\treturn { record, version: base.version, value, deltasSinceBase: tail.length };\n\t}\n\n\tprivate candidateNextId(writes: readonly StorageWrite[]): number {\n\t\tlet nextId = this.nextId;\n\t\tfor (const write of writes) {\n\t\t\tconst id = claimOf(write)?.id;\n\t\t\tif (id !== undefined) nextId = Math.max(nextId, id + 1);\n\t\t}\n\t\treturn nextId;\n\t}\n\n\t/** Resolve each copy to a base of its source's state before this batch, which may not change the source. */\n\tprivate async resolveCopies(executor: SqliteExecutor, actions: Map<DocumentId, DocumentAction>): Promise<void> {\n\t\tfor (const [id, action] of actions) {\n\t\t\tif (action.copy === undefined) continue;\n\t\t\ttry {\n\t\t\t\tconst stored = await this.materializeDocument(executor, action.copy.id, action.copy.at);\n\t\t\t\tif (stored === undefined) throw new Error(`Fork source document ${action.copy.id} cannot be read`);\n\t\t\t\tconst create = action.create!;\n\t\t\t\tif (\n\t\t\t\t\tstored.record.scope.kind !== \"conversation\" ||\n\t\t\t\t\tcreate.scope.kind !== \"conversation\" ||\n\t\t\t\t\tstored.record.kind !== create.kind ||\n\t\t\t\t\tstored.record.key !== create.key ||\n\t\t\t\t\tstored.record.history !== create.history ||\n\t\t\t\t\tstored.record.fork !== create.fork\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Fork source document ${action.copy.id} does not match the copied record`);\n\t\t\t\t}\n\t\t\t\taction.content = { kind: \"base\", version: stored.version, value: stored.value };\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`Document copy ${id} was rejected`, { cause: error });\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate assertOpen(): void {\n\t\tif (this.closed) throw new Error(\"SqliteStorage is closed\");\n\t}\n}\n"]}
@@ -1,5 +1,5 @@
1
- import type { Context } from "@earendil-works/chord";
2
- import { type OwnerTable, type SeriesCommit, type StagedWrite, type Step, type StoreWrite } from "@earendil-works/chord/next";
1
+ import { type OwnerTable, type SeriesCommit, type StagedWrite, type Step, type StoreWrite } from "@earendil-works/chord";
2
+ import type { Context } from "@earendil-works/chord/context";
3
3
  import type { StorageWrite } from "../../types.ts";
4
4
  /** Durable's record types, as `record_ids` names them. */
5
5
  export type RecordType = "conversation" | "entry" | "task" | "submission" | "document";
@@ -1 +1 @@
1
- {"version":3,"file":"commit.d.ts","sourceRoot":"","sources":["../../../src/storage/store/commit.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,OAAO,EAAa,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAMN,KAAK,UAAU,EAGf,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,IAAI,EACT,KAAK,UAAU,EAEf,MAAM,4BAA4B,CAAC;AAEpC,OAAO,KAAK,EAOX,YAAY,EACZ,MAAM,gBAAgB,CAAC;AAIxB,0DAA0D;AAC1D,MAAM,MAAM,UAAU,GAAG,cAAc,GAAG,OAAO,GAAG,MAAM,GAAG,YAAY,GAAG,UAAU,CAAC;AAEvF,qDAAqD;AACrD,MAAM,MAAM,YAAY,GAAG;IAC1B,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAC;IAC/B,QAAQ,CAAC,aAAa,EAAE,UAAU,CAAC;IACnC,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAC;IAC7B,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC;IAChC,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,WAAW,EAAE,UAAU,CAAC;CACjC,CAAC;AAuBF,gGAAgG;AAChG,qBAAa,aAAc,YAA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;CACjC,CAAC;AAuBF,gGAAgG;AAChG,qBAAa,aAAc,YAAW,YAAY,EAAE,WAAW;;IAC9D,QAAQ,CAAC,KAAK,WAAW;IACzB,QAAQ,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,CAAC;IAaxC;;;OAGG;IACH,YACC,MAAM,EAAE,SAAS,YAAY,EAAE,EAC/B,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,YAAY,EACpB,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,EAC3B,OAAO,EAAE,OAAO,EAOhB;IAED;;;OAGG;IACG,KAAK,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAKrC;IAoCD,+DAA+D;IACzD,KAAK,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,SAAS,UAAU,EAAE,CAAC,CAiBtD;CA0KD"}
@@ -4,7 +4,7 @@
4
4
  // resolved from their sources (its messages, a refusal), then its one composite write: the table puts, and the
5
5
  // documents in two passes, existing ones first (their content, then their retirement, which frees the addresses this
6
6
  // commit's creations take), then the creations and copies.
7
- import { findDocument, insertDocument, readDocument, retireRecord, writeContent, } from "@earendil-works/chord/next";
7
+ import { findDocument, insertDocument, readDocument, retireRecord, writeContent, } from "@earendil-works/chord";
8
8
  import { StorageRequestError } from "../../errors.js";
9
9
  import { addressOf, durableRecord, engineRecord, readAt } from "./documents.js";
10
10
  import { conversationRow, entryRow, submissionRow, taskRow } from "./tables.js";
@@ -1 +1 @@
1
- {"version":3,"file":"commit.js","sourceRoot":"","sources":["../../../src/storage/store/commit.ts"],"names":[],"mappings":"AAAA,iHAAiH;AACjH,6GAA6G;AAC7G,oHAAoH;AACpH,+GAA+G;AAC/G,qHAAqH;AACrH,2DAA2D;AAG3D,OAAO,EAIN,YAAY,EACZ,cAAc,EAEd,YAAY,EACZ,YAAY,EAKZ,YAAY,GACZ,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAE,MAAM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K,EAAE,EAAE,CAAC;IACrG,CAAC;CACD;AAED,2FAA2F;AAC3F,SAAS,aAAa,CAAC,OAAwB;IAC9C,OAAO,OAAO,CAAC,IAAI,KAAK,MAAM;QAC7B,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE;QACnF,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC;AAClE,CAAC","sourcesContent":["// One Durable commit as one commit of the store's series (slice 6b §2.3): staged before the queue (rows encoded,\n// contents serialized, explicit ids raising the store's allocator), then inside the series' transaction what\n// `SqliteStorage` does inside its own, with the step's reader: Durable's checks of ids and documents and the copies\n// resolved from their sources (its messages, a refusal), then its one composite write: the table puts, and the\n// documents in two passes, existing ones first (their content, then their retirement, which frees the addresses this\n// commit's creations take), then the creations and copies.\n\nimport type { Context, JsonValue } from \"@earendil-works/chord\";\nimport {\n\ttype EncodedRow,\n\ttype DocumentContent as EngineContent,\n\ttype DocumentRecord as EngineRecord,\n\tfindDocument,\n\tinsertDocument,\n\ttype OwnerTable,\n\treadDocument,\n\tretireRecord,\n\ttype SeriesCommit,\n\ttype StagedWrite,\n\ttype Step,\n\ttype StoreWrite,\n\twriteContent,\n} from \"@earendil-works/chord/next\";\nimport { StorageRequestError } from \"../../errors.ts\";\nimport type {\n\tDocumentContent,\n\tDocumentCopySource,\n\tDocumentCreate,\n\tDocumentId,\n\tId,\n\tJsonObject,\n\tStorageWrite,\n} from \"../../types.ts\";\nimport { addressOf, durableRecord, engineRecord, readAt } from \"./documents.ts\";\nimport { conversationRow, entryRow, submissionRow, taskRow } from \"./tables.ts\";\n\n/** Durable's record types, as `record_ids` names them. */\nexport type RecordType = \"conversation\" | \"entry\" | \"task\" | \"submission\" | \"document\";\n\n/** The storage's tables, as a commit writes them. */\nexport type CommitTables = {\n\treadonly recordIds: OwnerTable;\n\treadonly conversations: OwnerTable;\n\treadonly entries: OwnerTable;\n\treadonly entryHeads: OwnerTable;\n\treadonly tasks: OwnerTable;\n\treadonly submissions: OwnerTable;\n};\n\n/** A table write of the commit: its record's id and type, its table and its row encoded at staging. */\ntype RowWrite = {\n\treadonly id: number;\n\treadonly type: Exclude<RecordType, \"document\">;\n\treadonly table: OwnerTable;\n\treadonly row: EncodedRow;\n};\n\n/** A base as the commit stores it: its version and value, and the value serialized. */\ntype StagedBase = { readonly version: number; readonly value: JsonObject; readonly text: string };\n\n/** What one commit does with one document, as `SqliteStorage`'s action map has it. */\ntype DocumentAction = {\n\tcreate?: DocumentCreate;\n\tcopy?: DocumentCopySource;\n\t/** A creation's base: the write's own, or a copy's once resolved. */\n\tbase?: StagedBase;\n\tcontent?: { readonly content: DocumentContent; readonly text: string };\n\tretire: boolean;\n};\n\n/** A Durable commit staged for the store's series: its checks, then itself as its one write. */\nexport class DurableCommit implements SeriesCommit, StagedWrite {\n\treadonly order = \"write\";\n\treadonly writes: readonly StagedWrite[];\n\treadonly #owner: string;\n\treadonly #tables: CommitTables;\n\treadonly #context: Context;\n\t/** Every id a write claims, in write order (documents created or copied included), for the id checks. */\n\treadonly #claims: { readonly id: number; readonly type: RecordType }[] = [];\n\treadonly #rows: RowWrite[] = [];\n\treadonly #actions = new Map<DocumentId, DocumentAction>();\n\t/** What `check` found for `apply`, in the same step: the stored types of the claimed ids, the changed documents. */\n\t#checked:\n\t\t| { readonly claimed: Map<number, RecordType>; readonly existing: Map<DocumentId, EngineRecord> }\n\t\t| undefined;\n\n\t/**\n\t * Stages `writes` (rule 8: rows and contents encoded here, before the queue); `raise` makes room above each explicit\n\t * id. A malformed batch (two content commands for one document, a second retirement) throws Durable's message.\n\t */\n\tconstructor(\n\t\twrites: readonly StorageWrite[],\n\t\towner: string,\n\t\ttables: CommitTables,\n\t\traise: (id: number) => void,\n\t\tcontext: Context,\n\t) {\n\t\tthis.#owner = owner;\n\t\tthis.#tables = tables;\n\t\tthis.#context = context;\n\t\tfor (const write of writes) this.#stage(write, raise);\n\t\tthis.writes = [this];\n\t}\n\n\t/**\n\t * Durable's checks against the state the series' earlier commits left, writing nothing: the ids, the documents and\n\t * the copies; a throw refuses the commit.\n\t */\n\tasync check(step: Step): Promise<void> {\n\t\tconst claimed = await this.#checkIds(step);\n\t\tconst existing = await this.#checkDocuments(step);\n\t\tawait this.#resolveCopies(step);\n\t\tthis.#checked = { claimed, existing };\n\t}\n\n\t/**\n\t * Resolves the copies (S11): each source read at its point and checked against the copy's record, entered as a\n\t * creation carrying the source's value as its base.\n\t */\n\tasync #resolveCopies(step: Step): Promise<void> {\n\t\tfor (const [id, action] of this.#actions) {\n\t\t\tconst source = action.copy;\n\t\t\tif (source === undefined) continue;\n\t\t\tif (this.#actions.has(source.id)) throw new Error(`Document copy ${id} source is changed in the copy batch`);\n\t\t\ttry {\n\t\t\t\tconst read = await readAt(step, source.id, source.at, this.#owner);\n\t\t\t\tif (read.kind === \"current_only\") {\n\t\t\t\t\tthrow new StorageRequestError(`Document ${read.id} does not retain historical content`);\n\t\t\t\t}\n\t\t\t\tconst stored = read.document;\n\t\t\t\tif (stored === undefined) throw new Error(`Fork source document ${source.id} cannot be read`);\n\t\t\t\tconst create = action.create!;\n\t\t\t\tif (\n\t\t\t\t\tstored.record.scope.kind !== \"conversation\" ||\n\t\t\t\t\tcreate.scope.kind !== \"conversation\" ||\n\t\t\t\t\tstored.record.kind !== create.kind ||\n\t\t\t\t\tstored.record.key !== create.key ||\n\t\t\t\t\tstored.record.history !== create.history ||\n\t\t\t\t\tstored.record.fork !== create.fork\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Fork source document ${source.id} does not match the copied record`);\n\t\t\t\t}\n\t\t\t\taction.base = { version: stored.version, value: stored.value, text: JSON.stringify(stored.value) };\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`Document copy ${id} was rejected`, { cause: error });\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The commit's writes, after its `check` in the same step. */\n\tasync apply(step: Step): Promise<readonly StoreWrite[]> {\n\t\tconst recorded: StoreWrite[] = [];\n\t\tconst { claimed, existing } = this.#checked!;\n\t\tfor (const write of this.#rows) {\n\t\t\tif (claimed.get(write.id) === undefined) recorded.push(await this.#claim(step, write.id, write.type));\n\t\t\tclaimed.set(write.id, write.type);\n\t\t\tconst stamp = write.table === this.#tables.entries ? \"commit_seq\" : undefined;\n\t\t\trecorded.push(await write.table.put(step, write.row, stamp));\n\t\t}\n\t\t// Existing documents first: a retirement frees its address before a creation of this commit takes it.\n\t\tfor (const [id, record] of existing) recorded.push(...(await this.#change(step, record, this.#actions.get(id)!)));\n\t\tfor (const [id, action] of this.#actions) {\n\t\t\tif (action.create === undefined) continue;\n\t\t\trecorded.push(await this.#claim(step, id, \"document\"));\n\t\t\trecorded.push(await this.#create(step, action.create, action.base!, action.retire));\n\t\t}\n\t\treturn recorded;\n\t}\n\n\t/** Stages one write: a table row encoded, a document command into its action. */\n\t#stage(write: StorageWrite, raise: (id: number) => void): void {\n\t\tconst tables = this.#tables;\n\t\tswitch (write.type) {\n\t\t\tcase \"conversation\":\n\t\t\t\tthis.#row(write.value.id, write.type, tables.conversations, conversationRow(write.value), raise);\n\t\t\t\treturn;\n\t\t\tcase \"entry\": {\n\t\t\t\tconst { id, conversationId, head } = write.value;\n\t\t\t\tthis.#row(id, write.type, tables.entries, entryRow(write.value), raise);\n\t\t\t\t// Its claim is the entry's: `apply` claims an id once.\n\t\t\t\tif (head !== undefined) {\n\t\t\t\t\tconst row = tables.entryHeads.encode({ id, conversation_id: conversationId });\n\t\t\t\t\tthis.#rows.push({ id, type: write.type, table: tables.entryHeads, row });\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"task\":\n\t\t\t\tthis.#row(write.value.id, write.type, tables.tasks, taskRow(write.value), raise);\n\t\t\t\treturn;\n\t\t\tcase \"submission\":\n\t\t\t\tthis.#row(write.value.id, write.type, tables.submissions, submissionRow(write.value), raise);\n\t\t\t\treturn;\n\t\t\tcase \"document.create\":\n\t\t\tcase \"document.copy\": {\n\t\t\t\tconst { id } = write.record;\n\t\t\t\tconst action = this.#action(id);\n\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t}\n\t\t\t\taction.create = write.record;\n\t\t\t\tif (write.type === \"document.copy\") action.copy = write.source;\n\t\t\t\telse action.base = { ...write.content, text: JSON.stringify(write.content.value) };\n\t\t\t\tthis.#claims.push({ id, type: \"document\" });\n\t\t\t\traise(id);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"document.change\": {\n\t\t\t\tconst action = this.#action(write.id);\n\t\t\t\t// A creation's base is its content command (`SqliteStorage` counts it so too), in either order.\n\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\tthrow new Error(`Document ${write.id} has more than one content command`);\n\t\t\t\t}\n\t\t\t\tconst { content } = write;\n\t\t\t\taction.content = { content, text: JSON.stringify(content.kind === \"base\" ? content.value : content.ops) };\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"document.retire\": {\n\t\t\t\tconst action = this.#action(write.id);\n\t\t\t\tif (action.retire) throw new Error(`Document ${write.id} is retired more than once`);\n\t\t\t\taction.retire = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t#row(id: Id<string>, type: RowWrite[\"type\"], table: OwnerTable, row: object, raise: (id: number) => void): void {\n\t\tthis.#claims.push({ id, type });\n\t\tthis.#rows.push({ id, type, table, row: table.encode(row) });\n\t\traise(id);\n\t}\n\n\t#action(id: DocumentId): DocumentAction {\n\t\tlet action = this.#actions.get(id);\n\t\tif (action === undefined) {\n\t\t\taction = { retire: false };\n\t\t\tthis.#actions.set(id, action);\n\t\t}\n\t\treturn action;\n\t}\n\n\t/**\n\t * Durable's global id checks (`SqliteStorage.checkGlobalIds`): a conversation, entry or document id claimed by\n\t * anything, or written twice; a task or submission id claimed by another type. Returns the stored types.\n\t */\n\tasync #checkIds(step: Step): Promise<Map<number, RecordType>> {\n\t\tconst stored = new Map<number, RecordType | undefined>();\n\t\tconst claimed = new Map<number, RecordType>();\n\t\tfor (const { id, type } of this.#claims) {\n\t\t\tlet existing = stored.get(id);\n\t\t\tif (!stored.has(id)) {\n\t\t\t\tconst row = await this.#tables.recordIds.get(step, [id], this.#context);\n\t\t\t\texisting = row?.record_type as RecordType | undefined;\n\t\t\t\tstored.set(id, existing);\n\t\t\t}\n\t\t\tconst earlier = claimed.get(id);\n\t\t\tif (type === \"conversation\" || type === \"entry\" || type === \"document\") {\n\t\t\t\tif (existing !== undefined) throw new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined) throw new Error(`ID ${id} is written more than once`);\n\t\t\t} else {\n\t\t\t\tif (existing !== undefined && existing !== type) throw new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined && earlier !== type) throw new Error(`ID ${id} is written as two record types`);\n\t\t\t}\n\t\t\tclaimed.set(id, type);\n\t\t}\n\t\tconst types = new Map<number, RecordType>();\n\t\tfor (const [id, type] of stored) if (type !== undefined) types.set(id, type);\n\t\treturn types;\n\t}\n\n\t/**\n\t * Durable's document checks (`SqliteStorage.checkDocumentActions`): a change or retirement of an unknown or retired\n\t * document, a delta on another version, more than one live incarnation per address after the commit. Returns the\n\t * existing records the commit changes or retires, in action order.\n\t */\n\tasync #checkDocuments(step: Step): Promise<Map<DocumentId, EngineRecord>> {\n\t\tconst existing = new Map<DocumentId, EngineRecord>();\n\t\tfor (const [id, action] of this.#actions) {\n\t\t\tif (action.create !== undefined) continue;\n\t\t\tconst stored = await readDocument(step, id);\n\t\t\tconst record = stored === undefined ? undefined : durableRecord(stored, this.#owner);\n\t\t\tif (record === undefined) throw new Error(`Unknown document: ${id}`);\n\t\t\tif (record.retiredAt !== undefined) throw new Error(`Document ${id} is retired`);\n\t\t\tconst content = action.content?.content;\n\t\t\tif (content?.kind === \"delta\" && content.version !== stored!.version) {\n\t\t\t\tthrow new Error(`Document ${id} version transition requires a base`);\n\t\t\t}\n\t\t\texisting.set(id, stored!);\n\t\t}\n\t\t/** Per address a live creation takes: its live incarnations after the commit so far. */\n\t\tconst live = new Map<string, number>();\n\t\tfor (const action of this.#actions.values()) {\n\t\t\tif (action.create === undefined || action.retire) continue;\n\t\t\tconst address = addressOf(action.create, this.#owner);\n\t\t\tconst key = JSON.stringify([address.namespace, address.kind, address.key]);\n\t\t\tlet count = live.get(key);\n\t\t\tif (count === undefined) {\n\t\t\t\t// The incarnation live there now counts unless this commit retires it.\n\t\t\t\tconst current = await findDocument(step, address);\n\t\t\t\tcount = current === undefined || this.#actions.get(current.id as DocumentId)?.retire === true ? 0 : 1;\n\t\t\t}\n\t\t\tif (++count > 1) throw new Error(\"Document address already has a current incarnation\");\n\t\t\tlive.set(key, count);\n\t\t}\n\t\treturn existing;\n\t}\n\n\t/** Puts `id`'s `record_ids` row: its record type. */\n\t#claim(step: Step, id: number, type: RecordType): Promise<StoreWrite> {\n\t\tconst table = this.#tables.recordIds;\n\t\treturn table.put(step, table.encode({ id, record_type: type }));\n\t}\n\n\t/** An existing document's content, then its retirement, as their writes. */\n\tasync #change(step: Step, record: EngineRecord, action: DocumentAction): Promise<StoreWrite[]> {\n\t\tconst writes: StoreWrite[] = [];\n\t\tlet { revision } = record;\n\t\tif (action.content !== undefined) {\n\t\t\tconst { content, text } = action.content;\n\t\t\tconst stored = engineContent(content);\n\t\t\tawait writeContent(step, record.id, record.history, revision, stored, text);\n\t\t\twrites.push({ kind: \"document.change\", id: record.id, revision, content: stored });\n\t\t\trevision++;\n\t\t}\n\t\tif (action.retire) {\n\t\t\tawait retireRecord(step, record);\n\t\t\twrites.push({ kind: \"document.retire\", id: record.id, revision });\n\t\t}\n\t\treturn writes;\n\t}\n\n\t/** A creation or a resolved copy (retired at once for a create-plus-retire, an empty lifetime), as its write. */\n\tasync #create(step: Step, create: DocumentCreate, base: StagedBase, retired: boolean): Promise<StoreWrite> {\n\t\tconst record = engineRecord(create, this.#owner, base.version, step.seq, retired);\n\t\tawait insertDocument(step, record, base.text);\n\t\tconst value = base.value as JsonValue;\n\t\treturn { kind: \"document.create\", record, base: { version: base.version, fingerprint: \"\", value } };\n\t}\n}\n\n/** A Durable content as the engine stores it: its documents have no schema fingerprint. */\nfunction engineContent(content: DocumentContent): EngineContent {\n\treturn content.kind === \"base\"\n\t\t? { kind: \"base\", version: content.version, fingerprint: \"\", value: content.value }\n\t\t: { kind: \"delta\", version: content.version, ops: content.ops };\n}\n"]}
1
+ {"version":3,"file":"commit.js","sourceRoot":"","sources":["../../../src/storage/store/commit.ts"],"names":[],"mappings":"AAAA,iHAAiH;AACjH,6GAA6G;AAC7G,oHAAoH;AACpH,+GAA+G;AAC/G,qHAAqH;AACrH,2DAA2D;AAE3D,OAAO,EAIN,YAAY,EACZ,cAAc,EAEd,YAAY,EACZ,YAAY,EAKZ,YAAY,GACZ,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAUtD,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAoChF,gGAAgG;AAChG,MAAM,OAAO,aAAa;IAChB,KAAK,GAAG,OAAO,CAAC;IAChB,MAAM,CAAyB;IAC/B,MAAM,CAAS;IACf,OAAO,CAAe;IACtB,QAAQ,CAAU;IAC3B,yGAAyG;IAChG,OAAO,GAAyD,EAAE,CAAC;IACnE,KAAK,GAAe,EAAE,CAAC;IACvB,QAAQ,GAAG,IAAI,GAAG,EAA8B,CAAC;IAC1D,oHAAoH;I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contents serialized, explicit ids raising the store's allocator), then inside the series' transaction what\n// `SqliteStorage` does inside its own, with the step's reader: Durable's checks of ids and documents and the copies\n// resolved from their sources (its messages, a refusal), then its one composite write: the table puts, and the\n// documents in two passes, existing ones first (their content, then their retirement, which frees the addresses this\n// commit's creations take), then the creations and copies.\n\nimport {\n\ttype EncodedRow,\n\ttype DocumentContent as EngineContent,\n\ttype DocumentRecord as EngineRecord,\n\tfindDocument,\n\tinsertDocument,\n\ttype OwnerTable,\n\treadDocument,\n\tretireRecord,\n\ttype SeriesCommit,\n\ttype StagedWrite,\n\ttype Step,\n\ttype StoreWrite,\n\twriteContent,\n} from \"@earendil-works/chord\";\nimport type { Context } from \"@earendil-works/chord/context\";\nimport type { JsonValue } from \"@earendil-works/chord/json\";\nimport { StorageRequestError } from \"../../errors.ts\";\nimport type {\n\tDocumentContent,\n\tDocumentCopySource,\n\tDocumentCreate,\n\tDocumentId,\n\tId,\n\tJsonObject,\n\tStorageWrite,\n} from \"../../types.ts\";\nimport { addressOf, durableRecord, engineRecord, readAt } from \"./documents.ts\";\nimport { conversationRow, entryRow, submissionRow, taskRow } from \"./tables.ts\";\n\n/** Durable's record types, as `record_ids` names them. */\nexport type RecordType = \"conversation\" | \"entry\" | \"task\" | \"submission\" | \"document\";\n\n/** The storage's tables, as a commit writes them. */\nexport type CommitTables = {\n\treadonly recordIds: OwnerTable;\n\treadonly conversations: OwnerTable;\n\treadonly entries: OwnerTable;\n\treadonly entryHeads: OwnerTable;\n\treadonly tasks: OwnerTable;\n\treadonly submissions: OwnerTable;\n};\n\n/** A table write of the commit: its record's id and type, its table and its row encoded at staging. */\ntype RowWrite = {\n\treadonly id: number;\n\treadonly type: Exclude<RecordType, \"document\">;\n\treadonly table: OwnerTable;\n\treadonly row: EncodedRow;\n};\n\n/** A base as the commit stores it: its version and value, and the value serialized. */\ntype StagedBase = { readonly version: number; readonly value: JsonObject; readonly text: string };\n\n/** What one commit does with one document, as `SqliteStorage`'s action map has it. */\ntype DocumentAction = {\n\tcreate?: DocumentCreate;\n\tcopy?: DocumentCopySource;\n\t/** A creation's base: the write's own, or a copy's once resolved. */\n\tbase?: StagedBase;\n\tcontent?: { readonly content: DocumentContent; readonly text: string };\n\tretire: boolean;\n};\n\n/** A Durable commit staged for the store's series: its checks, then itself as its one write. */\nexport class DurableCommit implements SeriesCommit, StagedWrite {\n\treadonly order = \"write\";\n\treadonly writes: readonly StagedWrite[];\n\treadonly #owner: string;\n\treadonly #tables: CommitTables;\n\treadonly #context: Context;\n\t/** Every id a write claims, in write order (documents created or copied included), for the id checks. */\n\treadonly #claims: { readonly id: number; readonly type: RecordType }[] = [];\n\treadonly #rows: RowWrite[] = [];\n\treadonly #actions = new Map<DocumentId, DocumentAction>();\n\t/** What `check` found for `apply`, in the same step: the stored types of the claimed ids, the changed documents. */\n\t#checked:\n\t\t| { readonly claimed: Map<number, RecordType>; readonly existing: Map<DocumentId, EngineRecord> }\n\t\t| undefined;\n\n\t/**\n\t * Stages `writes` (rule 8: rows and contents encoded here, before the queue); `raise` makes room above each explicit\n\t * id. A malformed batch (two content commands for one document, a second retirement) throws Durable's message.\n\t */\n\tconstructor(\n\t\twrites: readonly StorageWrite[],\n\t\towner: string,\n\t\ttables: CommitTables,\n\t\traise: (id: number) => void,\n\t\tcontext: Context,\n\t) {\n\t\tthis.#owner = owner;\n\t\tthis.#tables = tables;\n\t\tthis.#context = context;\n\t\tfor (const write of writes) this.#stage(write, raise);\n\t\tthis.writes = [this];\n\t}\n\n\t/**\n\t * Durable's checks against the state the series' earlier commits left, writing nothing: the ids, the documents and\n\t * the copies; a throw refuses the commit.\n\t */\n\tasync check(step: Step): Promise<void> {\n\t\tconst claimed = await this.#checkIds(step);\n\t\tconst existing = await this.#checkDocuments(step);\n\t\tawait this.#resolveCopies(step);\n\t\tthis.#checked = { claimed, existing };\n\t}\n\n\t/**\n\t * Resolves the copies (S11): each source read at its point and checked against the copy's record, entered as a\n\t * creation carrying the source's value as its base.\n\t */\n\tasync #resolveCopies(step: Step): Promise<void> {\n\t\tfor (const [id, action] of this.#actions) {\n\t\t\tconst source = action.copy;\n\t\t\tif (source === undefined) continue;\n\t\t\tif (this.#actions.has(source.id)) throw new Error(`Document copy ${id} source is changed in the copy batch`);\n\t\t\ttry {\n\t\t\t\tconst read = await readAt(step, source.id, source.at, this.#owner);\n\t\t\t\tif (read.kind === \"current_only\") {\n\t\t\t\t\tthrow new StorageRequestError(`Document ${read.id} does not retain historical content`);\n\t\t\t\t}\n\t\t\t\tconst stored = read.document;\n\t\t\t\tif (stored === undefined) throw new Error(`Fork source document ${source.id} cannot be read`);\n\t\t\t\tconst create = action.create!;\n\t\t\t\tif (\n\t\t\t\t\tstored.record.scope.kind !== \"conversation\" ||\n\t\t\t\t\tcreate.scope.kind !== \"conversation\" ||\n\t\t\t\t\tstored.record.kind !== create.kind ||\n\t\t\t\t\tstored.record.key !== create.key ||\n\t\t\t\t\tstored.record.history !== create.history ||\n\t\t\t\t\tstored.record.fork !== create.fork\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Fork source document ${source.id} does not match the copied record`);\n\t\t\t\t}\n\t\t\t\taction.base = { version: stored.version, value: stored.value, text: JSON.stringify(stored.value) };\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`Document copy ${id} was rejected`, { cause: error });\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The commit's writes, after its `check` in the same step. */\n\tasync apply(step: Step): Promise<readonly StoreWrite[]> {\n\t\tconst recorded: StoreWrite[] = [];\n\t\tconst { claimed, existing } = this.#checked!;\n\t\tfor (const write of this.#rows) {\n\t\t\tif (claimed.get(write.id) === undefined) recorded.push(await this.#claim(step, write.id, write.type));\n\t\t\tclaimed.set(write.id, write.type);\n\t\t\tconst stamp = write.table === this.#tables.entries ? \"commit_seq\" : undefined;\n\t\t\trecorded.push(await write.table.put(step, write.row, stamp));\n\t\t}\n\t\t// Existing documents first: a retirement frees its address before a creation of this commit takes it.\n\t\tfor (const [id, record] of existing) recorded.push(...(await this.#change(step, record, this.#actions.get(id)!)));\n\t\tfor (const [id, action] of this.#actions) {\n\t\t\tif (action.create === undefined) continue;\n\t\t\trecorded.push(await this.#claim(step, id, \"document\"));\n\t\t\trecorded.push(await this.#create(step, action.create, action.base!, action.retire));\n\t\t}\n\t\treturn recorded;\n\t}\n\n\t/** Stages one write: a table row encoded, a document command into its action. */\n\t#stage(write: StorageWrite, raise: (id: number) => void): void {\n\t\tconst tables = this.#tables;\n\t\tswitch (write.type) {\n\t\t\tcase \"conversation\":\n\t\t\t\tthis.#row(write.value.id, write.type, tables.conversations, conversationRow(write.value), raise);\n\t\t\t\treturn;\n\t\t\tcase \"entry\": {\n\t\t\t\tconst { id, conversationId, head } = write.value;\n\t\t\t\tthis.#row(id, write.type, tables.entries, entryRow(write.value), raise);\n\t\t\t\t// Its claim is the entry's: `apply` claims an id once.\n\t\t\t\tif (head !== undefined) {\n\t\t\t\t\tconst row = tables.entryHeads.encode({ id, conversation_id: conversationId });\n\t\t\t\t\tthis.#rows.push({ id, type: write.type, table: tables.entryHeads, row });\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"task\":\n\t\t\t\tthis.#row(write.value.id, write.type, tables.tasks, taskRow(write.value), raise);\n\t\t\t\treturn;\n\t\t\tcase \"submission\":\n\t\t\t\tthis.#row(write.value.id, write.type, tables.submissions, submissionRow(write.value), raise);\n\t\t\t\treturn;\n\t\t\tcase \"document.create\":\n\t\t\tcase \"document.copy\": {\n\t\t\t\tconst { id } = write.record;\n\t\t\t\tconst action = this.#action(id);\n\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\tthrow new Error(`Document ${id} has more than one content command`);\n\t\t\t\t}\n\t\t\t\taction.create = write.record;\n\t\t\t\tif (write.type === \"document.copy\") action.copy = write.source;\n\t\t\t\telse action.base = { ...write.content, text: JSON.stringify(write.content.value) };\n\t\t\t\tthis.#claims.push({ id, type: \"document\" });\n\t\t\t\traise(id);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"document.change\": {\n\t\t\t\tconst action = this.#action(write.id);\n\t\t\t\t// A creation's base is its content command (`SqliteStorage` counts it so too), in either order.\n\t\t\t\tif (action.create !== undefined || action.content !== undefined || action.copy !== undefined) {\n\t\t\t\t\tthrow new Error(`Document ${write.id} has more than one content command`);\n\t\t\t\t}\n\t\t\t\tconst { content } = write;\n\t\t\t\taction.content = { content, text: JSON.stringify(content.kind === \"base\" ? content.value : content.ops) };\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase \"document.retire\": {\n\t\t\t\tconst action = this.#action(write.id);\n\t\t\t\tif (action.retire) throw new Error(`Document ${write.id} is retired more than once`);\n\t\t\t\taction.retire = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t#row(id: Id<string>, type: RowWrite[\"type\"], table: OwnerTable, row: object, raise: (id: number) => void): void {\n\t\tthis.#claims.push({ id, type });\n\t\tthis.#rows.push({ id, type, table, row: table.encode(row) });\n\t\traise(id);\n\t}\n\n\t#action(id: DocumentId): DocumentAction {\n\t\tlet action = this.#actions.get(id);\n\t\tif (action === undefined) {\n\t\t\taction = { retire: false };\n\t\t\tthis.#actions.set(id, action);\n\t\t}\n\t\treturn action;\n\t}\n\n\t/**\n\t * Durable's global id checks (`SqliteStorage.checkGlobalIds`): a conversation, entry or document id claimed by\n\t * anything, or written twice; a task or submission id claimed by another type. Returns the stored types.\n\t */\n\tasync #checkIds(step: Step): Promise<Map<number, RecordType>> {\n\t\tconst stored = new Map<number, RecordType | undefined>();\n\t\tconst claimed = new Map<number, RecordType>();\n\t\tfor (const { id, type } of this.#claims) {\n\t\t\tlet existing = stored.get(id);\n\t\t\tif (!stored.has(id)) {\n\t\t\t\tconst row = await this.#tables.recordIds.get(step, [id], this.#context);\n\t\t\t\texisting = row?.record_type as RecordType | undefined;\n\t\t\t\tstored.set(id, existing);\n\t\t\t}\n\t\t\tconst earlier = claimed.get(id);\n\t\t\tif (type === \"conversation\" || type === \"entry\" || type === \"document\") {\n\t\t\t\tif (existing !== undefined) throw new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined) throw new Error(`ID ${id} is written more than once`);\n\t\t\t} else {\n\t\t\t\tif (existing !== undefined && existing !== type) throw new Error(`ID ${id} already belongs to ${existing}`);\n\t\t\t\tif (earlier !== undefined && earlier !== type) throw new Error(`ID ${id} is written as two record types`);\n\t\t\t}\n\t\t\tclaimed.set(id, type);\n\t\t}\n\t\tconst types = new Map<number, RecordType>();\n\t\tfor (const [id, type] of stored) if (type !== undefined) types.set(id, type);\n\t\treturn types;\n\t}\n\n\t/**\n\t * Durable's document checks (`SqliteStorage.checkDocumentActions`): a change or retirement of an unknown or retired\n\t * document, a delta on another version, more than one live incarnation per address after the commit. Returns the\n\t * existing records the commit changes or retires, in action order.\n\t */\n\tasync #checkDocuments(step: Step): Promise<Map<DocumentId, EngineRecord>> {\n\t\tconst existing = new Map<DocumentId, EngineRecord>();\n\t\tfor (const [id, action] of this.#actions) {\n\t\t\tif (action.create !== undefined) continue;\n\t\t\tconst stored = await readDocument(step, id);\n\t\t\tconst record = stored === undefined ? undefined : durableRecord(stored, this.#owner);\n\t\t\tif (record === undefined) throw new Error(`Unknown document: ${id}`);\n\t\t\tif (record.retiredAt !== undefined) throw new Error(`Document ${id} is retired`);\n\t\t\tconst content = action.content?.content;\n\t\t\tif (content?.kind === \"delta\" && content.version !== stored!.version) {\n\t\t\t\tthrow new Error(`Document ${id} version transition requires a base`);\n\t\t\t}\n\t\t\texisting.set(id, stored!);\n\t\t}\n\t\t/** Per address a live creation takes: its live incarnations after the commit so far. */\n\t\tconst live = new Map<string, number>();\n\t\tfor (const action of this.#actions.values()) {\n\t\t\tif (action.create === undefined || action.retire) continue;\n\t\t\tconst address = addressOf(action.create, this.#owner);\n\t\t\tconst key = JSON.stringify([address.namespace, address.kind, address.key]);\n\t\t\tlet count = live.get(key);\n\t\t\tif (count === undefined) {\n\t\t\t\t// The incarnation live there now counts unless this commit retires it.\n\t\t\t\tconst current = await findDocument(step, address);\n\t\t\t\tcount = current === undefined || this.#actions.get(current.id as DocumentId)?.retire === true ? 0 : 1;\n\t\t\t}\n\t\t\tif (++count > 1) throw new Error(\"Document address already has a current incarnation\");\n\t\t\tlive.set(key, count);\n\t\t}\n\t\treturn existing;\n\t}\n\n\t/** Puts `id`'s `record_ids` row: its record type. */\n\t#claim(step: Step, id: number, type: RecordType): Promise<StoreWrite> {\n\t\tconst table = this.#tables.recordIds;\n\t\treturn table.put(step, table.encode({ id, record_type: type }));\n\t}\n\n\t/** An existing document's content, then its retirement, as their writes. */\n\tasync #change(step: Step, record: EngineRecord, action: DocumentAction): Promise<StoreWrite[]> {\n\t\tconst writes: StoreWrite[] = [];\n\t\tlet { revision } = record;\n\t\tif (action.content !== undefined) {\n\t\t\tconst { content, text } = action.content;\n\t\t\tconst stored = engineContent(content);\n\t\t\tawait writeContent(step, record.id, record.history, revision, stored, text);\n\t\t\twrites.push({ kind: \"document.change\", id: record.id, revision, content: stored });\n\t\t\trevision++;\n\t\t}\n\t\tif (action.retire) {\n\t\t\tawait retireRecord(step, record);\n\t\t\twrites.push({ kind: \"document.retire\", id: record.id, revision });\n\t\t}\n\t\treturn writes;\n\t}\n\n\t/** A creation or a resolved copy (retired at once for a create-plus-retire, an empty lifetime), as its write. */\n\tasync #create(step: Step, create: DocumentCreate, base: StagedBase, retired: boolean): Promise<StoreWrite> {\n\t\tconst record = engineRecord(create, this.#owner, base.version, step.seq, retired);\n\t\tawait insertDocument(step, record, base.text);\n\t\tconst value = base.value as JsonValue;\n\t\treturn { kind: \"document.create\", record, base: { version: base.version, fingerprint: \"\", value } };\n\t}\n}\n\n/** A Durable content as the engine stores it: its documents have no schema fingerprint. */\nfunction engineContent(content: DocumentContent): EngineContent {\n\treturn content.kind === \"base\"\n\t\t? { kind: \"base\", version: content.version, fingerprint: \"\", value: content.value }\n\t\t: { kind: \"delta\", version: content.version, ops: content.ops };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type DocumentEntry, type DocumentHistory, type DocumentAddress as EngineAddress, type DocumentRecord as EngineRecord } from "@earendil-works/chord/next";
1
+ import { type DocumentEntry, type DocumentHistory, type DocumentAddress as EngineAddress, type DocumentRecord as EngineRecord } from "@earendil-works/chord";
2
2
  import type { SqliteExecutor } from "@earendil-works/chord/sqlite";
3
3
  import type { DocumentAddress, DocumentCreate, DocumentId, DocumentPoint, DocumentRecord, StoredDocument } from "../../types.ts";
4
4
  /** The namespaces a storage claims under its owner: Durable's scopes (Chord's namespaces never contain a `:`). */
@@ -1 +1 @@
1
- {"version":3,"file":"documents.d.ts","sourceRoot":"","sources":["../../../src/storage/store/documents.ts"],"names":[],"mappings":"AAKA,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,eAAe,IAAI,aAAa,EAErC,KAAK,cAAc,IAAI,YAAY,EAGnC,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEnE,OAAO,KAAK,EACX,eAAe,EACf,cAAc,EACd,UAAU,EACV,aAAa,EACb,cAAc,EAEd,cAAc,EACd,MAAM,gBAAgB,CAAC;AAGxB,kHAAkH;AAClH,eAAO,MAAM,gBAAgB,YAAI,SAAS,EAAE,eAAe,EAAE,OAAO,CAAU,CAAC;AAE/E,4FAA4F;AAC5F,wBAAgB,WAAW,CAAC,KAAK,EAAE,cAAc,CAAC,OAAO,CAAC,GAAG,MAAM,CASlE;AAED,6DAA6D;AAC7D,wBAAgB,SAAS,CAAC,OAAO,EAAE,eAAe,GAAG,cAAc,EAAE,KAAK,EAAE,MAAM,GAAG,aAAa,CAGjG;AAED,kHAAkH;AAClH,wBAAgB,SAAS,CAAC,MAAM,EAAE,cAAc,GAAG,cAAc,GAAG,eAAe,CAElF;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAC3B,MAAM,EAAE,cAAc,EACtB,KAAK,EAA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,EAAE,EAAE,aAAa,EACjB,KAAK,EAAE,MAAM,GACX,OAAO,CAAC,YAAY,CAAC,CAgBvB"}
@@ -2,7 +2,7 @@
2
2
  // under the storage's owner name (its scope as the namespace, its kind and key JSON-encoded as Durable's indexed
3
3
  // strings), a Durable record as an engine record and back (the Durable record in `meta`), and a document read at a
4
4
  // point.
5
- import { loadContent, readDocumentEntry, } from "@earendil-works/chord/next";
5
+ import { loadContent, readDocumentEntry, } from "@earendil-works/chord";
6
6
  import { seqFromNumber } from "../../ids.js";
7
7
  import { encodeIndexed } from "./tables.js";
8
8
  /** The namespaces a storage claims under its owner: Durable's scopes (Chord's namespaces never contain a `:`). */
@@ -1 +1 @@
1
- {"version":3,"file":"documents.js","sourceRoot":"","sources":["../../../src/storage/store/documents.ts"],"names":[],"mappings":"AAAA,kHAAkH;AAClH,iHAAiH;AACjH,mHAAmH;AACnH,SAAS;AAET,OAAO,EAMN,WAAW,EACX,iBAAiB,GACjB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAU7C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,kHAAkH;AAClH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,SAAS,EAAE,eAAe,EAAE,OAAO,CAAU,CAAC;AAE/E,4FAA4F;AAC5F,MAAM,UAAU,WAAW,CAAC,KAA8B;IACzD,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,SAAS;YACb,OAAO,SAAS,CAAC;QAClB,KAAK,cAAc;YAClB,OAAO,gBAAgB,KAAK,CAAC,cAAc,EAAE,CAAC;QAC/C,KAAK,MAAM;YACV,OAAO,QAAQ,KAAK,CAAC,MAAM,EAAE,CAAC;IAChC,CAAC;AACF,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,SAAS,CAAC,OAAyC,EAAE,KAAa;IACjF,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,SAAS,EAA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;IACpD,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,CAAC;QAC5E,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC;IAC/C,CAAC;IACD,MAAM,MAAM,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,EAAE,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,KAAK,YAAY;QAAE,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC;IAC5F,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC;IACxE,MAAM,KAAK,GAAgB,EAAE,CAAC;IAC9B,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IACtD,kEAAkE;IAClE,MAAM,KAAK,GAAG,MAAM,CAAC,KAAmB,CAAC;IACzC,OAAO;QACN,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,CAAC,eAAe,EAAE;KAC7F,CAAC;AACH,CAAC","sourcesContent":["// Durable's documents in the store's documents engine (slice 6b §1.5, R1): a Durable address as an engine address\n// under the storage's owner name (its scope as the namespace, its kind and key JSON-encoded as Durable's indexed\n// strings), a Durable record as an engine record and back (the Durable record in `meta`), and a document read at a\n// point.\n\nimport {\n\ttype DocumentEntry,\n\ttype DocumentHistory,\n\ttype DocumentAddress as EngineAddress,\n\ttype DocumentPoint as EnginePoint,\n\ttype DocumentRecord as EngineRecord,\n\tloadContent,\n\treadDocumentEntry,\n} from \"@earendil-works/chord/next\";\nimport type { SqliteExecutor } from \"@earendil-works/chord/sqlite\";\nimport { seqFromNumber } from \"../../ids.ts\";\nimport type {\n\tDocumentAddress,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentPoint,\n\tDocumentRecord,\n\tJsonObject,\n\tStoredDocument,\n} from \"../../types.ts\";\nimport { encodeIndexed } from \"./tables.ts\";\n\n/** The namespaces a storage claims under its owner: Durable's scopes (Chord's namespaces never contain a `:`). */\nexport const SCOPE_NAMESPACES = [\"session\", \"conversation:\", \"task:\"] as const;\n\n/** The engine namespace of a Durable scope: `session`, `conversation:<id>`, `task:<id>`. */\nexport function namespaceOf(scope: DocumentRecord[\"scope\"]): string {\n\tswitch (scope.kind) {\n\t\tcase \"session\":\n\t\t\treturn \"session\";\n\t\tcase \"conversation\":\n\t\t\treturn `conversation:${scope.conversationId}`;\n\t\tcase \"task\":\n\t\t\treturn `task:${scope.taskId}`;\n\t}\n}\n\n/** The engine address of a Durable address under `owner`. */\nexport function addressOf(address: DocumentAddress | DocumentCreate, owner: string): EngineAddress {\n\tconst at = { owner, namespace: namespaceOf(address.scope), kind: encodeIndexed(address.kind) };\n\treturn address.key === undefined ? at : { ...at, key: encodeIndexed(address.key) };\n}\n\n/** What a record of `scope` keeps: session and task documents and latest conversation ones their latest state. */\nexport function historyOf(record: DocumentCreate | DocumentRecord): DocumentHistory {\n\treturn record.scope.kind === \"conversation\" && record.history === \"rewindable\" ? \"rewindable\" : \"latest\";\n}\n\n/**\n * The engine record of a Durable creation at `seq` (retired at once for an empty lifetime): the Durable record itself,\n * its creation seq included, in `meta`, so a read of a live record parses one JSON text from one column, as\n * `SqliteStorage`'s does (a retirement later sets only the engine's `retired_at`).\n */\nexport function engineRecord(\n\tcreate: DocumentCreate,\n\towner: string,\n\tversion: number,\n\tseq: number,\n\tretired: boolean,\n): EngineRecord {\n\treturn {\n\t\tid: create.id,\n\t\t...addressOf(create, owner),\n\t\thistory: historyOf(create),\n\t\tcreatedAt: seq,\n\t\t...(retired ? { retiredAt: seq } : {}),\n\t\tmeta: JSON.stringify({ ...create, createdAt: seq }),\n\t\trevision: 1,\n\t\tversion,\n\t\tfingerprint: \"\",\n\t};\n}\n\n/**\n * The Durable record of an engine record of this storage's owner and scopes, `undefined` for anyone else's (a Chord\n * document, another owner's): its id is unknown to this storage.\n */\nexport function durableRecord(record: EngineRecord, owner: string): DocumentRecord | undefined {\n\tconst { meta } = record;\n\tif (meta === undefined || !ownedHere(record, owner)) return undefined;\n\treturn recordOfEntry({ meta, retired_at: record.retiredAt ?? null });\n}\n\n/** The Durable record of an engine entry read at one of this storage's addresses or scopes (the record in `meta`). */\nexport function recordOfEntry(entry: DocumentEntry): DocumentRecord {\n\t// Written by `engineRecord`, parsed fresh: a retirement since is set on it in place.\n\tconst record = JSON.parse(entry.meta!) as { -readonly [K in keyof DocumentRecord]: DocumentRecord[K] };\n\tif (entry.retired_at !== undefined && entry.retired_at !== null) record.retiredAt = seqFromNumber(entry.retired_at);\n\treturn record as DocumentRecord;\n}\n\n/** Whether a record is this storage's: `owner`'s, in one of Durable's scopes (not a Chord document of the owner). */\nfunction ownedHere(record: { readonly owner: string; readonly namespace: string }, owner: string): boolean {\n\tconst { namespace } = record;\n\tif (record.owner !== owner) return false;\n\treturn namespace === \"session\" || namespace.startsWith(\"conversation:\") || namespace.startsWith(\"task:\");\n}\n\n/** Whether a document is alive at `at` (the half-open lifetime). */\nexport function aliveAt(record: DocumentRecord, at: DocumentPoint): boolean {\n\tif (at === \"current\") return record.retiredAt === undefined;\n\treturn record.createdAt <= at && (record.retiredAt === undefined || at < record.retiredAt);\n}\n\n/**\n * A document read at a point, as a tagged result: request errors are told after the guarded read (slice 6b §1.4),\n * never thrown inside it.\n */\nexport type DocumentRead =\n\t| { readonly kind: \"found\"; readonly document: StoredDocument | undefined }\n\t| { readonly kind: \"current_only\"; readonly id: DocumentId };\n\n/**\n * Document `id` of `owner` at `at`: absent (unknown, someone else's, not alive at `at`), a record whose history does\n * not reach back to `at`, or its value from the base at or below `at` and the deltas up to it.\n */\nexport async function readAt(\n\texecutor: Pick<SqliteExecutor, \"get\" | \"all\">,\n\tid: DocumentId,\n\tat: DocumentPoint,\n\towner: string,\n): Promise<DocumentRead> {\n\tconst entry = await readDocumentEntry(executor, id);\n\tif (entry === undefined || entry.meta === null || !ownedHere(entry, owner)) {\n\t\treturn { kind: \"found\", document: undefined };\n\t}\n\tconst record = recordOfEntry(entry);\n\tif (at !== \"current\" && entry.history !== \"rewindable\") return { kind: \"current_only\", id };\n\tif (!aliveAt(record, at)) return { kind: \"found\", document: undefined };\n\tconst point: EnginePoint = at;\n\tconst loaded = await loadContent(executor, id, point);\n\t// The engine stores what Durable's commits gave it: JSON objects.\n\tconst value = loaded.value as JsonObject;\n\treturn {\n\t\tkind: \"found\",\n\t\tdocument: { record, version: loaded.version, value, deltasSinceBase: loaded.deltasSinceBase },\n\t};\n}\n"]}
1
+ {"version":3,"file":"documents.js","sourceRoot":"","sources":["../../../src/storage/store/documents.ts"],"names":[],"mappings":"AAAA,kHAAkH;AAClH,iHAAiH;AACjH,mHAAmH;AACnH,SAAS;AAET,OAAO,EAMN,WAAW,EACX,iBAAiB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAU7C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,kHAAkH;AAClH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,SAAS,EAAE,eAAe,EAAE,OAAO,CAAU,CAAC;AAE/E,4FAA4F;AAC5F,MAAM,UAAU,WAAW,CAAC,KAA8B;IACzD,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,SAAS;YACb,OAAO,SAAS,CAAC;QAClB,KAAK,cAAc;YAClB,OAAO,gBAAgB,KAAK,CAAC,cAAc,EAAE,CAAC;QAC/C,KAAK,MAAM;YACV,OAAO,QAAQ,KAAK,CAAC,MAAM,EAAE,CAAC;IAChC,CAAC;AACF,CAAC;AAED,6D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7C,EAAc,EACd,EAAiB,EACjB,KAAa;IAEb,MAAM,KAAK,GAAG,MAAM,iBAAiB,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IACpD,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE,CAAC;QAC5E,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC;IAC/C,CAAC;IACD,MAAM,MAAM,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,EAAE,KAAK,SAAS,IAAI,KAAK,CAAC,OAAO,KAAK,YAAY;QAAE,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC;IAC5F,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC;IACxE,MAAM,KAAK,GAAgB,EAAE,CAAC;IAC9B,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,QAAQ,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IACtD,kEAAkE;IAClE,MAAM,KAAK,GAAG,MAAM,CAAC,KAAmB,CAAC;IACzC,OAAO;QACN,IAAI,EAAE,OAAO;QACb,QAAQ,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,CAAC,eAAe,EAAE;KAC7F,CAAC;AACH,CAAC","sourcesContent":["// Durable's documents in the store's documents engine (slice 6b §1.5, R1): a Durable address as an engine address\n// under the storage's owner name (its scope as the namespace, its kind and key JSON-encoded as Durable's indexed\n// strings), a Durable record as an engine record and back (the Durable record in `meta`), and a document read at a\n// point.\n\nimport {\n\ttype DocumentEntry,\n\ttype DocumentHistory,\n\ttype DocumentAddress as EngineAddress,\n\ttype DocumentPoint as EnginePoint,\n\ttype DocumentRecord as EngineRecord,\n\tloadContent,\n\treadDocumentEntry,\n} from \"@earendil-works/chord\";\nimport type { SqliteExecutor } from \"@earendil-works/chord/sqlite\";\nimport { seqFromNumber } from \"../../ids.ts\";\nimport type {\n\tDocumentAddress,\n\tDocumentCreate,\n\tDocumentId,\n\tDocumentPoint,\n\tDocumentRecord,\n\tJsonObject,\n\tStoredDocument,\n} from \"../../types.ts\";\nimport { encodeIndexed } from \"./tables.ts\";\n\n/** The namespaces a storage claims under its owner: Durable's scopes (Chord's namespaces never contain a `:`). */\nexport const SCOPE_NAMESPACES = [\"session\", \"conversation:\", \"task:\"] as const;\n\n/** The engine namespace of a Durable scope: `session`, `conversation:<id>`, `task:<id>`. */\nexport function namespaceOf(scope: DocumentRecord[\"scope\"]): string {\n\tswitch (scope.kind) {\n\t\tcase \"session\":\n\t\t\treturn \"session\";\n\t\tcase \"conversation\":\n\t\t\treturn `conversation:${scope.conversationId}`;\n\t\tcase \"task\":\n\t\t\treturn `task:${scope.taskId}`;\n\t}\n}\n\n/** The engine address of a Durable address under `owner`. */\nexport function addressOf(address: DocumentAddress | DocumentCreate, owner: string): EngineAddress {\n\tconst at = { owner, namespace: namespaceOf(address.scope), kind: encodeIndexed(address.kind) };\n\treturn address.key === undefined ? at : { ...at, key: encodeIndexed(address.key) };\n}\n\n/** What a record of `scope` keeps: session and task documents and latest conversation ones their latest state. */\nexport function historyOf(record: DocumentCreate | DocumentRecord): DocumentHistory {\n\treturn record.scope.kind === \"conversation\" && record.history === \"rewindable\" ? \"rewindable\" : \"latest\";\n}\n\n/**\n * The engine record of a Durable creation at `seq` (retired at once for an empty lifetime): the Durable record itself,\n * its creation seq included, in `meta`, so a read of a live record parses one JSON text from one column, as\n * `SqliteStorage`'s does (a retirement later sets only the engine's `retired_at`).\n */\nexport function engineRecord(\n\tcreate: DocumentCreate,\n\towner: string,\n\tversion: number,\n\tseq: number,\n\tretired: boolean,\n): EngineRecord {\n\treturn {\n\t\tid: create.id,\n\t\t...addressOf(create, owner),\n\t\thistory: historyOf(create),\n\t\tcreatedAt: seq,\n\t\t...(retired ? { retiredAt: seq } : {}),\n\t\tmeta: JSON.stringify({ ...create, createdAt: seq }),\n\t\trevision: 1,\n\t\tversion,\n\t\tfingerprint: \"\",\n\t};\n}\n\n/**\n * The Durable record of an engine record of this storage's owner and scopes, `undefined` for anyone else's (a Chord\n * document, another owner's): its id is unknown to this storage.\n */\nexport function durableRecord(record: EngineRecord, owner: string): DocumentRecord | undefined {\n\tconst { meta } = record;\n\tif (meta === undefined || !ownedHere(record, owner)) return undefined;\n\treturn recordOfEntry({ meta, retired_at: record.retiredAt ?? null });\n}\n\n/** The Durable record of an engine entry read at one of this storage's addresses or scopes (the record in `meta`). */\nexport function recordOfEntry(entry: DocumentEntry): DocumentRecord {\n\t// Written by `engineRecord`, parsed fresh: a retirement since is set on it in place.\n\tconst record = JSON.parse(entry.meta!) as { -readonly [K in keyof DocumentRecord]: DocumentRecord[K] };\n\tif (entry.retired_at !== undefined && entry.retired_at !== null) record.retiredAt = seqFromNumber(entry.retired_at);\n\treturn record as DocumentRecord;\n}\n\n/** Whether a record is this storage's: `owner`'s, in one of Durable's scopes (not a Chord document of the owner). */\nfunction ownedHere(record: { readonly owner: string; readonly namespace: string }, owner: string): boolean {\n\tconst { namespace } = record;\n\tif (record.owner !== owner) return false;\n\treturn namespace === \"session\" || namespace.startsWith(\"conversation:\") || namespace.startsWith(\"task:\");\n}\n\n/** Whether a document is alive at `at` (the half-open lifetime). */\nexport function aliveAt(record: DocumentRecord, at: DocumentPoint): boolean {\n\tif (at === \"current\") return record.retiredAt === undefined;\n\treturn record.createdAt <= at && (record.retiredAt === undefined || at < record.retiredAt);\n}\n\n/**\n * A document read at a point, as a tagged result: request errors are told after the guarded read (slice 6b §1.4),\n * never thrown inside it.\n */\nexport type DocumentRead =\n\t| { readonly kind: \"found\"; readonly document: StoredDocument | undefined }\n\t| { readonly kind: \"current_only\"; readonly id: DocumentId };\n\n/**\n * Document `id` of `owner` at `at`: absent (unknown, someone else's, not alive at `at`), a record whose history does\n * not reach back to `at`, or its value from the base at or below `at` and the deltas up to it.\n */\nexport async function readAt(\n\texecutor: Pick<SqliteExecutor, \"get\" | \"all\">,\n\tid: DocumentId,\n\tat: DocumentPoint,\n\towner: string,\n): Promise<DocumentRead> {\n\tconst entry = await readDocumentEntry(executor, id);\n\tif (entry === undefined || entry.meta === null || !ownedHere(entry, owner)) {\n\t\treturn { kind: \"found\", document: undefined };\n\t}\n\tconst record = recordOfEntry(entry);\n\tif (at !== \"current\" && entry.history !== \"rewindable\") return { kind: \"current_only\", id };\n\tif (!aliveAt(record, at)) return { kind: \"found\", document: undefined };\n\tconst point: EnginePoint = at;\n\tconst loaded = await loadContent(executor, id, point);\n\t// The engine stores what Durable's commits gave it: JSON objects.\n\tconst value = loaded.value as JsonObject;\n\treturn {\n\t\tkind: \"found\",\n\t\tdocument: { record, version: loaded.version, value, deltasSinceBase: loaded.deltasSinceBase },\n\t};\n}\n"]}
@@ -1,5 +1,5 @@
1
- import type { Context } from "@earendil-works/chord";
2
- import type { OwnerTable } from "@earendil-works/chord/next";
1
+ import type { OwnerTable } from "@earendil-works/chord";
2
+ import type { Context } from "@earendil-works/chord/context";
3
3
  import type { SqliteExecutor, SqliteValue } from "@earendil-works/chord/sqlite";
4
4
  import type { CommitTables } from "./commit.ts";
5
5
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"queries.d.ts","sourceRoot":"","sources":["../../../src/storage/store/queries.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,KAAK,EAAS,UAAU,EAAa,MAAM,4BAA4B,CAAC;AAC/E,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAChF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD;;;GAGG;AACH,KAAK,SAAS,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