@bastani/atomic 0.9.41 → 0.9.42-alpha.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 (270) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +13 -0
  3. package/dist/builtin/intercom/README.md +7 -3
  4. package/dist/builtin/intercom/broker/broker-status.ts +48 -0
  5. package/dist/builtin/intercom/broker/broker.ts +90 -9
  6. package/dist/builtin/intercom/broker/client.ts +112 -12
  7. package/dist/builtin/intercom/broker/control.ts +225 -0
  8. package/dist/builtin/intercom/broker/multinode-router.ts +32 -39
  9. package/dist/builtin/intercom/broker/paths.ts +4 -0
  10. package/dist/builtin/intercom/broker/pending-send-registry.ts +27 -5
  11. package/dist/builtin/intercom/broker/shared-storage-setting.ts +60 -0
  12. package/dist/builtin/intercom/broker/spawn.ts +13 -4
  13. package/dist/builtin/intercom/broker/sql-lease-store.ts +23 -0
  14. package/dist/builtin/intercom/broker/watchdog.ts +105 -0
  15. package/dist/builtin/intercom/index.bundle.mjs +200 -22
  16. package/dist/builtin/intercom/package.json +1 -1
  17. package/dist/builtin/intercom/types.ts +34 -2
  18. package/dist/builtin/mcp/package.json +1 -1
  19. package/dist/builtin/subagents/package.json +1 -1
  20. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -0
  21. package/dist/builtin/web-access/package.json +1 -1
  22. package/dist/builtin/workflows/CHANGELOG.md +12 -0
  23. package/dist/builtin/workflows/README.md +10 -0
  24. package/dist/builtin/workflows/builtin/{chunk-txbc93t6.js → chunk-3s95f7ry.js} +1 -1
  25. package/dist/builtin/workflows/builtin/{chunk-n2gkzkty.js → chunk-edhf30ef.js} +1 -1
  26. package/dist/builtin/workflows/builtin/{chunk-8x61e0s7.js → chunk-frqxd4d1.js} +18 -9
  27. package/dist/builtin/workflows/builtin/goal.js +2 -2
  28. package/dist/builtin/workflows/builtin/index.js +3 -3
  29. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  30. package/dist/builtin/workflows/package.json +6 -1
  31. package/dist/builtin/workflows/src/authoring.d.ts +3 -1
  32. package/dist/builtin/workflows/src/durable/journal/internal.d.ts +13 -0
  33. package/dist/builtin/workflows/src/durable/journal/resolution.d.ts +2 -0
  34. package/dist/builtin/workflows/src/durable/journal/sql-run-journal.d.ts +1 -0
  35. package/dist/builtin/workflows/src/extension/index.bundle.mjs +88554 -82820
  36. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +72635 -0
  37. package/dist/builtin/workflows/src/index.js +53824 -5907
  38. package/dist/builtin/workflows/src/local-worker-entry.mjs +72635 -0
  39. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +7 -0
  40. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +2 -0
  41. package/dist/builtin/workflows/src/workers/public-options.d.ts +31 -0
  42. package/dist/bun/app-host-modules.d.ts +9 -0
  43. package/dist/bun/app-host-modules.d.ts.map +1 -0
  44. package/dist/bun/app-host-modules.js +10 -0
  45. package/dist/bun/app-host-modules.js.map +1 -0
  46. package/dist/bun/cli.d.ts +3 -1
  47. package/dist/bun/cli.d.ts.map +1 -1
  48. package/dist/bun/cli.js +15 -1
  49. package/dist/bun/cli.js.map +1 -1
  50. package/dist/bun/internal-intercom-broker.d.ts +17 -0
  51. package/dist/bun/internal-intercom-broker.d.ts.map +1 -1
  52. package/dist/bun/internal-intercom-broker.js +29 -0
  53. package/dist/bun/internal-intercom-broker.js.map +1 -1
  54. package/dist/bun/internal-workflow-worker.d.ts +4 -0
  55. package/dist/bun/internal-workflow-worker.d.ts.map +1 -0
  56. package/dist/bun/internal-workflow-worker.js +37 -0
  57. package/dist/bun/internal-workflow-worker.js.map +1 -0
  58. package/dist/bun/split-loader.js +10 -2
  59. package/dist/bun/split-loader.js.map +1 -1
  60. package/dist/cli/args.d.ts.map +1 -1
  61. package/dist/cli/args.js +3 -1
  62. package/dist/cli/args.js.map +1 -1
  63. package/dist/cli/intercom-command.d.ts +15 -0
  64. package/dist/cli/intercom-command.d.ts.map +1 -0
  65. package/dist/cli/intercom-command.js +87 -0
  66. package/dist/cli/intercom-command.js.map +1 -0
  67. package/dist/cli/storage-command.d.ts +39 -0
  68. package/dist/cli/storage-command.d.ts.map +1 -0
  69. package/dist/cli/storage-command.js +367 -0
  70. package/dist/cli/storage-command.js.map +1 -0
  71. package/dist/core/agent-session-events.d.ts.map +1 -1
  72. package/dist/core/agent-session-events.js +5 -1
  73. package/dist/core/agent-session-events.js.map +1 -1
  74. package/dist/core/agent-session-methods.d.ts +1 -0
  75. package/dist/core/agent-session-methods.d.ts.map +1 -1
  76. package/dist/core/agent-session-methods.js.map +1 -1
  77. package/dist/core/agent-session-tasks.d.ts.map +1 -1
  78. package/dist/core/agent-session-tasks.js +1 -0
  79. package/dist/core/agent-session-tasks.js.map +1 -1
  80. package/dist/core/agent-session-types.d.ts +1 -0
  81. package/dist/core/agent-session-types.d.ts.map +1 -1
  82. package/dist/core/agent-session-types.js.map +1 -1
  83. package/dist/core/agent-session.d.ts +1 -0
  84. package/dist/core/agent-session.d.ts.map +1 -1
  85. package/dist/core/agent-session.js +2 -0
  86. package/dist/core/agent-session.js.map +1 -1
  87. package/dist/core/builtin-install-layout.d.ts +6 -0
  88. package/dist/core/builtin-install-layout.d.ts.map +1 -1
  89. package/dist/core/builtin-install-layout.js +9 -0
  90. package/dist/core/builtin-install-layout.js.map +1 -1
  91. package/dist/core/child-session-options.d.ts.map +1 -1
  92. package/dist/core/child-session-options.js +3 -0
  93. package/dist/core/child-session-options.js.map +1 -1
  94. package/dist/core/exec.js +2 -2
  95. package/dist/core/exec.js.map +1 -1
  96. package/dist/core/export-html/template.css +9 -0
  97. package/dist/core/export-html/template.js +165 -45
  98. package/dist/core/extensions/loader-host-modules.d.ts +6 -0
  99. package/dist/core/extensions/loader-host-modules.d.ts.map +1 -1
  100. package/dist/core/extensions/loader-host-modules.js +12 -1
  101. package/dist/core/extensions/loader-host-modules.js.map +1 -1
  102. package/dist/core/extensions/loader-virtual-modules.d.ts +6 -0
  103. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  104. package/dist/core/extensions/loader-virtual-modules.js +18 -0
  105. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  106. package/dist/core/extensions/message-types.d.ts +4 -0
  107. package/dist/core/extensions/message-types.d.ts.map +1 -1
  108. package/dist/core/extensions/message-types.js.map +1 -1
  109. package/dist/core/fast-model-routing-transport.d.ts.map +1 -1
  110. package/dist/core/fast-model-routing-transport.js +5 -1
  111. package/dist/core/fast-model-routing-transport.js.map +1 -1
  112. package/dist/core/intercom-broker-control.d.ts +67 -0
  113. package/dist/core/intercom-broker-control.d.ts.map +1 -0
  114. package/dist/core/intercom-broker-control.js +17 -0
  115. package/dist/core/intercom-broker-control.js.map +1 -0
  116. package/dist/core/model-runtime-streaming.d.ts.map +1 -1
  117. package/dist/core/model-runtime-streaming.js +38 -1
  118. package/dist/core/model-runtime-streaming.js.map +1 -1
  119. package/dist/core/package-manager-git.d.ts +2 -2
  120. package/dist/core/package-manager-git.d.ts.map +1 -1
  121. package/dist/core/package-manager-git.js.map +1 -1
  122. package/dist/core/package-manager-manifest.d.ts.map +1 -1
  123. package/dist/core/package-manager-manifest.js +9 -1
  124. package/dist/core/package-manager-manifest.js.map +1 -1
  125. package/dist/core/package-manager-npm.d.ts +2 -2
  126. package/dist/core/package-manager-npm.d.ts.map +1 -1
  127. package/dist/core/package-manager-npm.js.map +1 -1
  128. package/dist/core/package-manager-paths.d.ts +7 -7
  129. package/dist/core/package-manager-paths.d.ts.map +1 -1
  130. package/dist/core/package-manager-paths.js.map +1 -1
  131. package/dist/core/package-manager-storage-adapters.d.ts +7 -0
  132. package/dist/core/package-manager-storage-adapters.d.ts.map +1 -0
  133. package/dist/core/package-manager-storage-adapters.js +76 -0
  134. package/dist/core/package-manager-storage-adapters.js.map +1 -0
  135. package/dist/core/package-manager-types.d.ts +4 -0
  136. package/dist/core/package-manager-types.d.ts.map +1 -1
  137. package/dist/core/package-manager-types.js.map +1 -1
  138. package/dist/core/provider-rate-limits.d.ts +23 -0
  139. package/dist/core/provider-rate-limits.d.ts.map +1 -0
  140. package/dist/core/provider-rate-limits.js +113 -0
  141. package/dist/core/provider-rate-limits.js.map +1 -0
  142. package/dist/core/provider-request-admission.d.ts +7 -0
  143. package/dist/core/provider-request-admission.d.ts.map +1 -0
  144. package/dist/core/provider-request-admission.js +91 -0
  145. package/dist/core/provider-request-admission.js.map +1 -0
  146. package/dist/core/resource-admission-scope.d.ts +4 -0
  147. package/dist/core/resource-admission-scope.d.ts.map +1 -0
  148. package/dist/core/resource-admission-scope.js +9 -0
  149. package/dist/core/resource-admission-scope.js.map +1 -0
  150. package/dist/core/sdk-types.d.ts +16 -0
  151. package/dist/core/sdk-types.d.ts.map +1 -1
  152. package/dist/core/sdk-types.js.map +1 -1
  153. package/dist/core/sdk.d.ts +2 -1
  154. package/dist/core/sdk.d.ts.map +1 -1
  155. package/dist/core/sdk.js +18 -2
  156. package/dist/core/sdk.js.map +1 -1
  157. package/dist/core/session-lifecycle-work.d.ts +1 -0
  158. package/dist/core/session-lifecycle-work.d.ts.map +1 -1
  159. package/dist/core/session-lifecycle-work.js +1 -0
  160. package/dist/core/session-lifecycle-work.js.map +1 -1
  161. package/dist/core/settings-manager-basic-accessors.d.ts +3 -0
  162. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  163. package/dist/core/settings-manager-basic-accessors.js +6 -0
  164. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  165. package/dist/core/settings-schema.d.ts +22 -0
  166. package/dist/core/settings-schema.d.ts.map +1 -1
  167. package/dist/core/settings-schema.js +18 -1
  168. package/dist/core/settings-schema.js.map +1 -1
  169. package/dist/core/storage/index.d.ts +1 -0
  170. package/dist/core/storage/index.d.ts.map +1 -1
  171. package/dist/core/storage/index.js +1 -0
  172. package/dist/core/storage/index.js.map +1 -1
  173. package/dist/core/storage/node-sqlite.d.ts +2 -1
  174. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  175. package/dist/core/storage/node-sqlite.js +5 -4
  176. package/dist/core/storage/node-sqlite.js.map +1 -1
  177. package/dist/core/storage/provider.d.ts +6 -0
  178. package/dist/core/storage/provider.d.ts.map +1 -1
  179. package/dist/core/storage/provider.js +27 -7
  180. package/dist/core/storage/provider.js.map +1 -1
  181. package/dist/core/storage/sqlite-facade.d.ts +49 -0
  182. package/dist/core/storage/sqlite-facade.d.ts.map +1 -0
  183. package/dist/core/storage/sqlite-facade.js +180 -0
  184. package/dist/core/storage/sqlite-facade.js.map +1 -0
  185. package/dist/core/storage/storage-status.d.ts +81 -0
  186. package/dist/core/storage/storage-status.d.ts.map +1 -0
  187. package/dist/core/storage/storage-status.js +409 -0
  188. package/dist/core/storage/storage-status.js.map +1 -0
  189. package/dist/core/tasks/supervisor.d.ts +2 -1
  190. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  191. package/dist/core/tasks/supervisor.js +105 -4
  192. package/dist/core/tasks/supervisor.js.map +1 -1
  193. package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
  194. package/dist/core/tools/bash-pty-native.js +1 -1
  195. package/dist/core/tools/bash-pty-native.js.map +1 -1
  196. package/dist/index.d.ts +2 -1
  197. package/dist/index.d.ts.map +1 -1
  198. package/dist/index.js +2 -1
  199. package/dist/index.js.map +1 -1
  200. package/dist/main.d.ts.map +1 -1
  201. package/dist/main.js +28 -2
  202. package/dist/main.js.map +1 -1
  203. package/dist/modes/interactive/components/assistant-message.d.ts +3 -1
  204. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  205. package/dist/modes/interactive/components/assistant-message.js +7 -3
  206. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  207. package/dist/modes/interactive/components/chat-message-renderer.d.ts +9 -1
  208. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  209. package/dist/modes/interactive/components/chat-message-renderer.js +16 -8
  210. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  211. package/dist/modes/interactive/components/login-dialog.d.ts +5 -0
  212. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  213. package/dist/modes/interactive/components/login-dialog.js +69 -2
  214. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  215. package/dist/modes/interactive/components/markdown-transform.d.ts +1 -1
  216. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -1
  217. package/dist/modes/interactive/components/markdown-transform.js +2 -2
  218. package/dist/modes/interactive/components/markdown-transform.js.map +1 -1
  219. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
  220. package/dist/modes/interactive/components/session-selector-search.js +80 -22
  221. package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
  222. package/dist/modes/interactive/components/user-message.d.ts +3 -1
  223. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  224. package/dist/modes/interactive/components/user-message.js +6 -2
  225. package/dist/modes/interactive/components/user-message.js.map +1 -1
  226. package/dist/modes/interactive/interactive-mode-deps.d.ts +1 -1
  227. package/dist/modes/interactive/interactive-mode-deps.d.ts.map +1 -1
  228. package/dist/modes/interactive/interactive-mode-deps.js.map +1 -1
  229. package/dist/modes/interactive/interactive-render-chat.js +6 -2
  230. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  231. package/dist/modes/interactive-engine/engine-health.d.ts +8 -4
  232. package/dist/modes/interactive-engine/engine-health.d.ts.map +1 -1
  233. package/dist/modes/interactive-engine/engine-health.js +41 -6
  234. package/dist/modes/interactive-engine/engine-health.js.map +1 -1
  235. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  236. package/dist/modes/interactive-engine/isolated-runtime.js +19 -17
  237. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  238. package/dist/modes/interactive-engine/remote-queue-pause.js +1 -1
  239. package/dist/modes/interactive-engine/remote-queue-pause.js.map +1 -1
  240. package/dist/modes/rpc/rpc-input-scheduler.d.ts +1 -0
  241. package/dist/modes/rpc/rpc-input-scheduler.d.ts.map +1 -1
  242. package/dist/modes/rpc/rpc-input-scheduler.js +4 -1
  243. package/dist/modes/rpc/rpc-input-scheduler.js.map +1 -1
  244. package/dist/modes/rpc/rpc-input.d.ts.map +1 -1
  245. package/dist/modes/rpc/rpc-input.js +29 -7
  246. package/dist/modes/rpc/rpc-input.js.map +1 -1
  247. package/dist/utils/shell.d.ts.map +1 -1
  248. package/dist/utils/shell.js +14 -0
  249. package/dist/utils/shell.js.map +1 -1
  250. package/docs/custom-provider/oauth.md +8 -1
  251. package/docs/extensions/api-reference.md +2 -0
  252. package/docs/intercom/operations.md +17 -8
  253. package/docs/intercom/reference.md +1 -1
  254. package/docs/keybindings.md +1 -1
  255. package/docs/packages/authoring.md +15 -0
  256. package/docs/packages.md +3 -2
  257. package/docs/providers.md +2 -0
  258. package/docs/reference/cli.md +17 -0
  259. package/docs/sdk.md +37 -0
  260. package/docs/settings.md +33 -2
  261. package/docs/storage.md +191 -219
  262. package/docs/usage.md +1 -1
  263. package/docs/workflows/api-reference.md +50 -0
  264. package/docs/workflows/operations.md +44 -1
  265. package/docs/workflows.md +25 -0
  266. package/examples/extensions/gondolin/package-lock.json +14 -24
  267. package/examples/extensions/gondolin/package.json +1 -1
  268. package/npm-shrinkwrap.json +35 -35
  269. package/package.json +4 -4
  270. package/schemas/settings.schema.json +87 -1
@@ -1 +1 @@
1
- {"version":3,"file":"node-sqlite.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,OAAO,EACN,uBAAuB,EAEvB,uBAAuB,EACvB,oBAAoB,EACpB,6BAA6B,EAC7B,uBAAuB,EACvB,gBAAgB,GAChB,MAAM,aAAa,CAAC;AAOrB,2GAA2G;AAC3G,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG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,CAAC,UAAwB;IAC9D,MAAM,UAAU,GAAG,EAAE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;IACpE,IAAI,CAAC;QACJ,UAAU,CAAC,QAAQ,GAAG,UAAU,CAAC,QAAQ,EAAE,IAAI,UAAU,CAAC;QAC1D,UAAU,CAAC,IAAI,CACd,oGAAoG,CACpG,CAAC;QACF,OAAO,IAAI,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;IAC9D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,uBAAuB,CAAC,UAAU,EAAE,KAA4B,CAAC,CAAC;IAC7E,CAAC;AACF,CAAC","sourcesContent":["import { mkdir, realpath } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteRow, SqliteValue, StorageDescriptor } from \"./database.js\";\nimport {\n\tStorageAdapterLoadError,\n\ttype StorageFailureCause,\n\tStorageInvalidTextError,\n\tStorageRollbackError,\n\tStorageTransactionClosedError,\n\tStorageUnavailableError,\n\tStoreClosedError,\n} from \"./errors.js\";\n\ninterface TransactionGates {\n\treadonly files: Map<string, Promise<void>>;\n\treadonly connections: WeakMap<DatabaseSync, Promise<void>>;\n}\n\n// Share gates across module reloads as well as adapter instances. Only live queues retain file identities.\nconst TRANSACTION_GATES = Symbol.for(\"atomic-storage/node-sqlite-transaction-gates@1\");\nconst gateBag = globalThis as typeof globalThis & Record<symbol, TransactionGates | undefined>;\nconst gates: TransactionGates = gateBag[TRANSACTION_GATES] ?? { files: new Map(), connections: new WeakMap() };\ngateBag[TRANSACTION_GATES] = gates;\n\nfunction gateTransaction<T>(identity: string | DatabaseSync, operation: () => Promise<T>): Promise<T> {\n\tconst prior = typeof identity === \"string\" ? gates.files.get(identity) : gates.connections.get(identity);\n\tconst result = (prior ?? Promise.resolve()).then(operation);\n\tconst settled = result.then(\n\t\t() => {},\n\t\t() => {},\n\t);\n\tif (typeof identity === \"string\") gates.files.set(identity, settled);\n\telse gates.connections.set(identity, settled);\n\tvoid settled.then(() => {\n\t\tif (typeof identity === \"string\") {\n\t\t\tif (gates.files.get(identity) === settled) gates.files.delete(identity);\n\t\t} else if (gates.connections.get(identity) === settled) gates.connections.delete(identity);\n\t});\n\treturn result;\n}\n\n/** Copies binary parameters so queued work binds the bytes the caller passed, not later buffer contents. */\nfunction snapshotParams(params: readonly SqliteValue[]): SqliteValue[] {\n\treturn params.map((value) => (value instanceof Uint8Array ? new Uint8Array(value) : value));\n}\n\n/**\n * Bun's `DatabaseSync.close()` defers closing the file until garbage collection finalizes every statement the\n * connection prepared, so the database, WAL and shared-memory files stay open (and locked on Windows). The adapter\n * keeps no statement references, so a synchronous collection finalizes them and releases the files. Node finalizes\n * statements inside `close()` and has no `Bun` global.\n */\nfunction finalizeReleasedStatements(): void {\n\t(globalThis as { Bun?: { gc(force: boolean): void } }).Bun?.gc(true);\n}\n\nfunction normalizeRow(row: Record<string, SqliteValue>): SqliteRow {\n\treturn Object.fromEntries(\n\t\tObject.entries(row).map(([key, value]) => [\n\t\t\tkey,\n\t\t\ttypeof value === \"bigint\" &&\n\t\t\tvalue >= -BigInt(Number.MAX_SAFE_INTEGER) &&\n\t\t\tvalue <= BigInt(Number.MAX_SAFE_INTEGER)\n\t\t\t\t? Number(value)\n\t\t\t\t: value instanceof Uint8Array\n\t\t\t\t\t? new Uint8Array(value)\n\t\t\t\t\t: value,\n\t\t]),\n\t);\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\treadonly descriptor: StorageDescriptor;\n\tprivate readonly connection: DatabaseSync;\n\tprivate tail: Promise<void> = Promise.resolve();\n\tprivate closing = false;\n\tprivate closePromise?: Promise<void>;\n\tprivate readonly executor: SqliteExecutor;\n\n\tprivate readonly ownsConnection: boolean;\n\tprivate readonly transactionIdentity: string | DatabaseSync;\n\n\tconstructor(\n\t\tconnection: DatabaseSync,\n\t\tdescriptor: StorageDescriptor,\n\t\townsConnection = true,\n\t\ttransactionIdentity: string | DatabaseSync = connection,\n\t) {\n\t\tthis.transactionIdentity = transactionIdentity;\n\t\tthis.ownsConnection = ownsConnection;\n\t\tthis.connection = connection;\n\t\tthis.descriptor = descriptor;\n\t\tthis.executor = this.createExecutor(() => true);\n\t}\n\n\tprivate driver<T>(operation: () => T): T {\n\t\ttry {\n\t\t\treturn operation();\n\t\t} catch (cause) {\n\t\t\tthrow new StorageUnavailableError(this.descriptor, cause as StorageFailureCause);\n\t\t}\n\t}\n\n\tprivate createExecutor(active: () => boolean): SqliteExecutor {\n\t\tconst execute = async <T>(operation: () => T, params: readonly SqliteValue[] = []): Promise<T> => {\n\t\t\tif (!active()) throw new StorageTransactionClosedError();\n\t\t\tconst invalidIndex = params.findIndex((value) => typeof value === \"string\" && value.includes(\"\\0\"));\n\t\t\tif (invalidIndex !== -1) throw new StorageInvalidTextError(invalidIndex);\n\t\t\treturn this.driver(operation);\n\t\t};\n\t\tconst statement = (sql: string) => {\n\t\t\tconst prepared = this.connection.prepare(sql);\n\t\t\tprepared.setReadBigInts(true);\n\t\t\treturn prepared;\n\t\t};\n\t\treturn {\n\t\t\texec: (sql) => execute(() => this.connection.exec(sql)),\n\t\t\trun: (sql, ...params) => execute(() => ({ changes: Number(statement(sql).run(...params).changes) }), params),\n\t\t\tget: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(() => {\n\t\t\t\t\tconst row = statement(sql).get(...params);\n\t\t\t\t\treturn row === undefined ? undefined : (normalizeRow(row) as T);\n\t\t\t\t}, params),\n\t\t\tall: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tstatement(sql)\n\t\t\t\t\t\t\t.all(...params)\n\t\t\t\t\t\t\t.map((row) => normalizeRow(row) as T),\n\t\t\t\t\tparams,\n\t\t\t\t),\n\t\t};\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => {},\n\t\t\t() => {},\n\t\t);\n\t\treturn result;\n\t}\n\n\texec(sql: string): Promise<void> {\n\t\treturn this.enqueue(() => this.executor.exec(sql));\n\t}\n\n\trun(sql: string, ...params: readonly SqliteValue[]) {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueue(() => this.executor.run(sql, ...bound));\n\t}\n\n\tget<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T | undefined> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueue(() => this.executor.get<T>(sql, ...bound));\n\t}\n\n\tall<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T[]> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueue(() => this.executor.all<T>(sql, ...bound));\n\t}\n\n\ttransaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {\n\t\treturn this.enqueue(() =>\n\t\t\tgateTransaction(this.transactionIdentity, async () => {\n\t\t\t\tawait this.executor.exec(\"BEGIN IMMEDIATE\");\n\t\t\t\tlet active = true;\n\t\t\t\tconst transaction = this.createExecutor(() => active);\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await callback(transaction);\n\t\t\t\t\tactive = false;\n\t\t\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t\t\t\treturn result;\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tactive = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t\t\t\t} catch (rollbackCause) {\n\t\t\t\t\t\tthrow new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause);\n\t\t\t\t\t}\n\t\t\t\t\tthrow cause;\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (!this.closePromise) {\n\t\t\tthis.closing = true;\n\t\t\tthis.closePromise = this.tail.then(() =>\n\t\t\t\tthis.driver(() => {\n\t\t\t\t\tif (this.ownsConnection) this.connection.close();\n\t\t\t\t\tfinalizeReleasedStatements();\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn this.closePromise;\n\t}\n}\n\nexport async function openNodeSqliteDatabase(\n\tpath: string,\n\t{ busyTimeoutMs = 5000 }: { busyTimeoutMs?: number } = {},\n): Promise<SqliteDatabase> {\n\tconst descriptor = { adapter: \"node-sqlite\", location: path };\n\t// Load node:sqlite on first open: importing it prints Node's experimental warning, which every importer of the\n\t// package entry point would otherwise see.\n\tlet Database: typeof DatabaseSync;\n\ttry {\n\t\t({ DatabaseSync: Database } = await import(\"node:sqlite\"));\n\t} catch (cause) {\n\t\tthrow new StorageAdapterLoadError(\"node:sqlite\", cause as StorageFailureCause);\n\t}\n\tlet connection: DatabaseSync | undefined;\n\ttry {\n\t\tif (path !== \":memory:\") await mkdir(dirname(path), { recursive: true });\n\t\tconnection = new Database(path);\n\t\tconnection.exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);\n\t\tconnection.exec(\"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\");\n\t\tconst location = connection.location();\n\t\tconst identity = location === null ? connection : await realpath(location);\n\t\treturn new NodeSqliteDatabase(connection, descriptor, true, identity);\n\t} catch (cause) {\n\t\ttry {\n\t\t\tconnection?.close();\n\t\t} catch {\n\t\t\t// Preserve the opening failure if cleanup also fails.\n\t\t}\n\t\tthrow new StorageUnavailableError(descriptor, cause as StorageFailureCause);\n\t}\n}\n\nexport function wrapNodeSqliteDatabase(connection: DatabaseSync): SqliteDatabase {\n\tconst descriptor = { adapter: \"node-sqlite\", location: \":memory:\" };\n\ttry {\n\t\tdescriptor.location = connection.location() || \":memory:\";\n\t\tconnection.exec(\n\t\t\t\"PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\",\n\t\t);\n\t\treturn new NodeSqliteDatabase(connection, descriptor, false);\n\t} catch (cause) {\n\t\tthrow new StorageUnavailableError(descriptor, cause as StorageFailureCause);\n\t}\n}\n"]}
1
+ {"version":3,"file":"node-sqlite.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,OAAO,EACN,uBAAuB,EAEvB,uBAAuB,EACvB,oBAAoB,EACpB,6BAA6B,EAC7B,uBAAuB,EACvB,gBAAgB,GAChB,MAAM,aAAa,CAAC;AAOrB,2GAA2G;AAC3G,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,gDAAgD,CAAC,CAAC;AACvF,MAAM,OAAO,GAAG,UAA8E,CAAC;AAC/F,MAAM,KAAK,GAAqB,OAAO,CAAC,iBAAiB,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,EAAE,WAAW,EAAE,IAAI,OAAO,EAAE,EAAE,CAAC;AAC/G,OAAO,CAAC,iBAAiB,CAAC,GAAG,KAAK,CAAC;AAEnC,SAAS,eAAe,CAAI,QAA+B,EAAE,SAA2B;IACvF,MAAM,KAAK,GAAG,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACzG,MAAM,MAAM,GAAG,CAAC,KAAK,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC5D,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAC1B,GAAG,EAAE,GA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AC,IAAI,CAAC,uBAAuB,aAAa,EAAE,CAAC,CAAC;QACxD,IAAI,CAAC,QAAQ;YAAE,UAAU,CAAC,IAAI,CAAC,0EAA0E,CAAC,CAAC;QAC3G,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,EAAE,CAAC;QACvC,MAAM,QAAQ,GAAG,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAC3E,OAAO,IAAI,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;IACvE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,IAAI,CAAC;YACJ,UAAU,EAAE,KAAK,EAAE,CAAC;QACrB,CAAC;QAAC,MAAM,CAAC;YACR,sDAAsD;QACvD,CAAC;QACD,MAAM,IAAI,uBAAuB,CAAC,UAAU,EAAE,KAA4B,CAAC,CAAC;IAC7E,CAAC;AACF,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,UAAwB;IAC9D,MAAM,UAAU,GAAG,EAAE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;IACpE,IAAI,CAAC;QACJ,UAAU,CAAC,QAAQ,GAAG,UAAU,CAAC,QAAQ,EAAE,IAAI,UAAU,CAAC;QAC1D,UAAU,CAAC,IAAI,CACd,oGAAoG,CACpG,CAAC;QACF,OAAO,IAAI,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC;IAC9D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,uBAAuB,CAAC,UAAU,EAAE,KAA4B,CAAC,CAAC;IAC7E,CAAC;AACF,CAAC","sourcesContent":["import { mkdir, realpath } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport type { DatabaseSync } from \"node:sqlite\";\nimport type { SqliteDatabase, SqliteExecutor, SqliteRow, SqliteValue, StorageDescriptor } from \"./database.js\";\nimport {\n\tStorageAdapterLoadError,\n\ttype StorageFailureCause,\n\tStorageInvalidTextError,\n\tStorageRollbackError,\n\tStorageTransactionClosedError,\n\tStorageUnavailableError,\n\tStoreClosedError,\n} from \"./errors.js\";\n\ninterface TransactionGates {\n\treadonly files: Map<string, Promise<void>>;\n\treadonly connections: WeakMap<DatabaseSync, Promise<void>>;\n}\n\n// Share gates across module reloads as well as adapter instances. Only live queues retain file identities.\nconst TRANSACTION_GATES = Symbol.for(\"atomic-storage/node-sqlite-transaction-gates@1\");\nconst gateBag = globalThis as typeof globalThis & Record<symbol, TransactionGates | undefined>;\nconst gates: TransactionGates = gateBag[TRANSACTION_GATES] ?? { files: new Map(), connections: new WeakMap() };\ngateBag[TRANSACTION_GATES] = gates;\n\nfunction gateTransaction<T>(identity: string | DatabaseSync, operation: () => Promise<T>): Promise<T> {\n\tconst prior = typeof identity === \"string\" ? gates.files.get(identity) : gates.connections.get(identity);\n\tconst result = (prior ?? Promise.resolve()).then(operation);\n\tconst settled = result.then(\n\t\t() => {},\n\t\t() => {},\n\t);\n\tif (typeof identity === \"string\") gates.files.set(identity, settled);\n\telse gates.connections.set(identity, settled);\n\tvoid settled.then(() => {\n\t\tif (typeof identity === \"string\") {\n\t\t\tif (gates.files.get(identity) === settled) gates.files.delete(identity);\n\t\t} else if (gates.connections.get(identity) === settled) gates.connections.delete(identity);\n\t});\n\treturn result;\n}\n\n/** Copies binary parameters so queued work binds the bytes the caller passed, not later buffer contents. */\nfunction snapshotParams(params: readonly SqliteValue[]): SqliteValue[] {\n\treturn params.map((value) => (value instanceof Uint8Array ? new Uint8Array(value) : value));\n}\n\n/**\n * Bun's `DatabaseSync.close()` defers closing the file until garbage collection finalizes every statement the\n * connection prepared, so the database, WAL and shared-memory files stay open (and locked on Windows). The adapter\n * keeps no statement references, so a synchronous collection finalizes them and releases the files. Node finalizes\n * statements inside `close()` and has no `Bun` global.\n */\nfunction finalizeReleasedStatements(): void {\n\t(globalThis as { Bun?: { gc(force: boolean): void } }).Bun?.gc(true);\n}\n\nfunction normalizeRow(row: Record<string, SqliteValue>): SqliteRow {\n\treturn Object.fromEntries(\n\t\tObject.entries(row).map(([key, value]) => [\n\t\t\tkey,\n\t\t\ttypeof value === \"bigint\" &&\n\t\t\tvalue >= -BigInt(Number.MAX_SAFE_INTEGER) &&\n\t\t\tvalue <= BigInt(Number.MAX_SAFE_INTEGER)\n\t\t\t\t? Number(value)\n\t\t\t\t: value instanceof Uint8Array\n\t\t\t\t\t? new Uint8Array(value)\n\t\t\t\t\t: value,\n\t\t]),\n\t);\n}\n\nclass NodeSqliteDatabase implements SqliteDatabase {\n\treadonly descriptor: StorageDescriptor;\n\tprivate readonly connection: DatabaseSync;\n\tprivate tail: Promise<void> = Promise.resolve();\n\tprivate closing = false;\n\tprivate closePromise?: Promise<void>;\n\tprivate readonly executor: SqliteExecutor;\n\n\tprivate readonly ownsConnection: boolean;\n\tprivate readonly transactionIdentity: string | DatabaseSync;\n\n\tconstructor(\n\t\tconnection: DatabaseSync,\n\t\tdescriptor: StorageDescriptor,\n\t\townsConnection = true,\n\t\ttransactionIdentity: string | DatabaseSync = connection,\n\t) {\n\t\tthis.transactionIdentity = transactionIdentity;\n\t\tthis.ownsConnection = ownsConnection;\n\t\tthis.connection = connection;\n\t\tthis.descriptor = descriptor;\n\t\tthis.executor = this.createExecutor(() => true);\n\t}\n\n\tprivate driver<T>(operation: () => T): T {\n\t\ttry {\n\t\t\treturn operation();\n\t\t} catch (cause) {\n\t\t\tthrow new StorageUnavailableError(this.descriptor, cause as StorageFailureCause);\n\t\t}\n\t}\n\n\tprivate createExecutor(active: () => boolean): SqliteExecutor {\n\t\tconst execute = async <T>(operation: () => T, params: readonly SqliteValue[] = []): Promise<T> => {\n\t\t\tif (!active()) throw new StorageTransactionClosedError();\n\t\t\tconst invalidIndex = params.findIndex((value) => typeof value === \"string\" && value.includes(\"\\0\"));\n\t\t\tif (invalidIndex !== -1) throw new StorageInvalidTextError(invalidIndex);\n\t\t\treturn this.driver(operation);\n\t\t};\n\t\tconst statement = (sql: string) => {\n\t\t\tconst prepared = this.connection.prepare(sql);\n\t\t\tprepared.setReadBigInts(true);\n\t\t\treturn prepared;\n\t\t};\n\t\treturn {\n\t\t\texec: (sql) => execute(() => this.connection.exec(sql)),\n\t\t\trun: (sql, ...params) => execute(() => ({ changes: Number(statement(sql).run(...params).changes) }), params),\n\t\t\tget: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(() => {\n\t\t\t\t\tconst row = statement(sql).get(...params);\n\t\t\t\t\treturn row === undefined ? undefined : (normalizeRow(row) as T);\n\t\t\t\t}, params),\n\t\t\tall: <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) =>\n\t\t\t\texecute(\n\t\t\t\t\t() =>\n\t\t\t\t\t\tstatement(sql)\n\t\t\t\t\t\t\t.all(...params)\n\t\t\t\t\t\t\t.map((row) => normalizeRow(row) as T),\n\t\t\t\t\tparams,\n\t\t\t\t),\n\t\t};\n\t}\n\n\tprivate enqueue<T>(operation: () => Promise<T>): Promise<T> {\n\t\tif (this.closing) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => {},\n\t\t\t() => {},\n\t\t);\n\t\treturn result;\n\t}\n\n\texec(sql: string): Promise<void> {\n\t\treturn this.enqueue(() => this.executor.exec(sql));\n\t}\n\n\trun(sql: string, ...params: readonly SqliteValue[]) {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueue(() => this.executor.run(sql, ...bound));\n\t}\n\n\tget<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T | undefined> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueue(() => this.executor.get<T>(sql, ...bound));\n\t}\n\n\tall<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T[]> {\n\t\tconst bound = snapshotParams(params);\n\t\treturn this.enqueue(() => this.executor.all<T>(sql, ...bound));\n\t}\n\n\ttransaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {\n\t\treturn this.enqueue(() =>\n\t\t\tgateTransaction(this.transactionIdentity, async () => {\n\t\t\t\tawait this.executor.exec(\"BEGIN IMMEDIATE\");\n\t\t\t\tlet active = true;\n\t\t\t\tconst transaction = this.createExecutor(() => active);\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await callback(transaction);\n\t\t\t\t\tactive = false;\n\t\t\t\t\tawait this.executor.exec(\"COMMIT\");\n\t\t\t\t\treturn result;\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tactive = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.executor.exec(\"ROLLBACK\");\n\t\t\t\t\t} catch (rollbackCause) {\n\t\t\t\t\t\tthrow new StorageRollbackError(cause as StorageFailureCause, rollbackCause as StorageFailureCause);\n\t\t\t\t\t}\n\t\t\t\t\tthrow cause;\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t}\n\n\tclose(): Promise<void> {\n\t\tif (!this.closePromise) {\n\t\t\tthis.closing = true;\n\t\t\tthis.closePromise = this.tail.then(() =>\n\t\t\t\tthis.driver(() => {\n\t\t\t\t\tif (this.ownsConnection) this.connection.close();\n\t\t\t\t\tfinalizeReleasedStatements();\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn this.closePromise;\n\t}\n}\n\nexport async function openNodeSqliteDatabase(\n\tpath: string,\n\t{ busyTimeoutMs = 5000, readOnly = false }: { busyTimeoutMs?: number; readOnly?: boolean } = {},\n): Promise<SqliteDatabase> {\n\tconst descriptor = { adapter: \"node-sqlite\", location: path };\n\t// Load node:sqlite on first open: importing it prints Node's experimental warning, which every importer of the\n\t// package entry point would otherwise see.\n\tlet Database: typeof DatabaseSync;\n\ttry {\n\t\t({ DatabaseSync: Database } = await import(\"node:sqlite\"));\n\t} catch (cause) {\n\t\tthrow new StorageAdapterLoadError(\"node:sqlite\", cause as StorageFailureCause);\n\t}\n\tlet connection: DatabaseSync | undefined;\n\ttry {\n\t\tif (!readOnly && path !== \":memory:\") await mkdir(dirname(path), { recursive: true });\n\t\tconnection = new Database(path, { readOnly });\n\t\tconnection.exec(`PRAGMA busy_timeout=${busyTimeoutMs}`);\n\t\tif (!readOnly) connection.exec(\"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\");\n\t\tconst location = connection.location();\n\t\tconst identity = location === null ? connection : await realpath(location);\n\t\treturn new NodeSqliteDatabase(connection, descriptor, true, identity);\n\t} catch (cause) {\n\t\ttry {\n\t\t\tconnection?.close();\n\t\t} catch {\n\t\t\t// Preserve the opening failure if cleanup also fails.\n\t\t}\n\t\tthrow new StorageUnavailableError(descriptor, cause as StorageFailureCause);\n\t}\n}\n\nexport function wrapNodeSqliteDatabase(connection: DatabaseSync): SqliteDatabase {\n\tconst descriptor = { adapter: \"node-sqlite\", location: \":memory:\" };\n\ttry {\n\t\tdescriptor.location = connection.location() || \":memory:\";\n\t\tconnection.exec(\n\t\t\t\"PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON\",\n\t\t);\n\t\treturn new NodeSqliteDatabase(connection, descriptor, false);\n\t} catch (cause) {\n\t\tthrow new StorageUnavailableError(descriptor, cause as StorageFailureCause);\n\t}\n}\n"]}
@@ -64,6 +64,12 @@ export interface JournalFactories {
64
64
  }): Promise<RunJournal>;
65
65
  }
66
66
  export declare function storageSelectionKey(selection: StorageSelection, agentDir?: string): string;
67
+ /**
68
+ * Loads an adapter module the way the extension loader loads extensions: `@bastani/atomic/storage` (and
69
+ * `@bastani/atomic`) resolve to this host's own modules, so adapters need no installed copy of Atomic and share its
70
+ * error classes. A package name selects an adapter listed by an installed Atomic package; other specifiers, and
71
+ * package names no installed package lists, resolve from the agent directory.
72
+ */
67
73
  export declare function loadStorageAdapter(module: string, context: StorageOpenContext): Promise<StorageAdapterModule>;
68
74
  /** The adapter's options with every `secrets` reference resolved, as the provider passes them to its hooks. */
69
75
  export declare function resolveAdapterOptions(selection: Extract<StorageSelection, {
@@ -1 +1 @@
1
- {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../src/core/storage/provider.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAUpF,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAEvD,MAAM,MAAM,SAAS,GAAG;IAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAC7E,MAAM,MAAM,cAAc,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC;AAC7E,MAAM,MAAM,gBAAgB,GACzB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GACjC;IAAE,QAAQ,EAAE,cAAc,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC7C;IAAE,MAAM,EAAE,IAAI,CAAA;CAAE,GAChB;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,cAAc,CAAC;IAAC,OAAO,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC7G,UAAU,CAAC;AACd,MAAM,MAAM,gBAAgB,GACzB;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAA;CAAE,GAC3B;IAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IAAC,QA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AG,UAAU,CAAC;IAClD,GAAG,CAAC,QAAQ,EAAE,cAAc,EAAE,OAAO,EAAE;QAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAC1F;AAeD,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,gBAAgB,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAqB1F;AAED;;;;;GAKG;AACH,wBAAsB,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAqCnH;AAED,+GAA+G;AAC/G,wBAAsB,qBAAqB,CAC1C,SAAS,EAAE,OAAO,CAAC,gBAAgB,EAAE;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC,EACzD,OAAO,EAAE,kBAAkB,GACzB,OAAO,CAAC,cAAc,CAAC,CAuBzB;AAyBD,MAAM,WAAW,eAAe;IAC/B,gBAAgB,CAAC,SAAS,EAAE,gBAAgB,EAAE,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;IAClG,cAAc,CAAC,SAAS,EAAE,gBAAgB,EAAE,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAC9F;AAED,eAAO,MAAM,eAAe,EAAE,KAAK,QAAQ,CAAC,EAAE,gBAAgB,KAAK,eA+JlE,CAAC"}
@@ -1,7 +1,6 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { dirname, isAbsolute, join, resolve } from "node:path";
3
- import { pathToFileURL } from "node:url";
4
- import { createJiti } from "jiti";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
4
  import { createSessionCwdMatcher } from "../../utils/canonical-path.js";
6
5
  import { StorageAdapterLoadError, StorageConfigError, StorageError, StorageUnavailableError, } from "./errors.js";
7
6
  import { openNodeSqliteDatabase } from "./node-sqlite.js";
@@ -42,12 +41,31 @@ export function storageSelectionKey(selection, agentDir) {
42
41
  }
43
42
  return JSON.stringify(selection);
44
43
  }
44
+ /**
45
+ * Loads an adapter module the way the extension loader loads extensions: `@bastani/atomic/storage` (and
46
+ * `@bastani/atomic`) resolve to this host's own modules, so adapters need no installed copy of Atomic and share its
47
+ * error classes. A package name selects an adapter listed by an installed Atomic package; other specifiers, and
48
+ * package names no installed package lists, resolve from the agent directory.
49
+ */
45
50
  export async function loadStorageAdapter(module, context) {
46
51
  try {
47
- const loader = createJiti(pathToFileURL(join(context.agentDir, "storage-adapter.js")).href, {
48
- interopDefault: true,
49
- });
50
- const adapter = await loader.import(module, { default: true });
52
+ const [{ createHostModuleJiti }, { getStorageAdapterHostModules }, { resolvePackageStorageAdapter }] = await Promise.all([
53
+ import("../extensions/loader-virtual-modules.js"),
54
+ import("../extensions/loader-host-modules.js"),
55
+ import("../package-manager-storage-adapters.js"),
56
+ ]);
57
+ const loader = await createHostModuleJiti(pathToFileURL(join(context.agentDir, "storage-adapter.js")).href, await getStorageAdapterHostModules(),
58
+ // JS adapters must also pass through virtual host modules, not native-import a second host copy.
59
+ { interopDefault: true, tryNative: false });
60
+ const specifier = (await resolvePackageStorageAdapter(module, context.agentDir)) ?? module;
61
+ const location = loader.esmResolve(specifier);
62
+ const filename = location.startsWith("file:") ? fileURLToPath(location) : location;
63
+ // jiti's async JS fast path uses native import even with tryNative:false. Force only JS entrypoints
64
+ // through its transform so their host imports use the live virtual modules, just like TS adapters.
65
+ const loaded = /\.[cm]?js$/.test(filename)
66
+ ? await loader.evalModule(await readFile(filename, "utf8"), { filename, async: true, forceTranspile: true })
67
+ : await loader.import(specifier, { default: true });
68
+ const adapter = (loaded?.default ?? loaded);
51
69
  if (adapter === null ||
52
70
  typeof adapter !== "object" ||
53
71
  adapter.atomicStorageAdapter !== 1 ||
@@ -72,12 +90,14 @@ export async function resolveAdapterOptions(selection, context) {
72
90
  value = environment;
73
91
  }
74
92
  else {
93
+ let text;
75
94
  try {
76
- value = await readFile(isAbsolute(ref.file) ? ref.file : join(dirname(context.agentDir), ref.file), "utf8");
95
+ text = await readFile(isAbsolute(ref.file) ? ref.file : join(dirname(context.agentDir), ref.file), "utf8");
77
96
  }
78
97
  catch (cause) {
79
98
  throw new StorageUnavailableError({ adapter: selection.module, location: ref.file }, cause);
80
99
  }
100
+ value = text.endsWith("\r\n") ? text.slice(0, -2) : text.endsWith("\n") ? text.slice(0, -1) : text;
81
101
  }
82
102
  Object.defineProperty(options, name, { value, enumerable: true, writable: true, configurable: true });
83
103
  }
@@ -1 +1 @@
1
- {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/core/storage/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAClC,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AAExE,OAAO,EACN,uBAAuB,EACvB,kBAAkB,EAClB,YAAY,EAEZ,uBAAuB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAgD/C,MAAM,WAAW,GAAG,IAAI,OAAO,EAA0B,CAAC;AAC1D,IAAI,cAAc,GAAG,CAAC,CAAC;AAEvB,SAAS,gBAAgB,CACxB,KAA4B;IAE5B,IAAI,KAAK,YAAY,UAAU;QAAE,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IACrE,IAAI,KAAK,KAAK,IAAI;QAAE,OA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BAAuB,CAAC,QAAQ,CAAC,UAAU,EAAE,KAA4B,CAAC,CAAC;gBACnF,MAAM,CAAC,cAAc,CAAC,YAAY,EAAE,cAAc,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;gBACjG,MAAM,YAAY,CAAC;YACpB,CAAC;YACD,MAAM,KAAK,CAAC;QACb,CAAC;IACF,CAAC;CACD,CAAC","sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { createJiti } from \"jiti\";\nimport { createSessionCwdMatcher } from \"../../utils/canonical-path.ts\";\nimport type { SqliteDatabase, SqliteValue, StorageDescriptor } from \"./database.js\";\nimport {\n\tStorageAdapterLoadError,\n\tStorageConfigError,\n\tStorageError,\n\ttype StorageFailureCause,\n\tStorageUnavailableError,\n} from \"./errors.js\";\nimport { openNodeSqliteDatabase } from \"./node-sqlite.js\";\nimport { validateStoragePrefix } from \"./prefix.js\";\nimport type { RunJournal } from \"./run-journal.js\";\nimport { selectStorage } from \"./selection.js\";\nimport type { SessionStore } from \"./session/types.js\";\n\nexport type SecretRef = { readonly env: string } | { readonly file: string };\nexport type AdapterOptions = Readonly<Record<string, SqliteValue | boolean>>;\nexport type RunJournalOption =\n\t| { path: string; prefix?: string }\n\t| { database: SqliteDatabase; prefix?: string }\n\t| { memory: true }\n\t| { adapter: string; options?: AdapterOptions; secrets?: Readonly<Record<string, SecretRef>>; prefix?: string }\n\t| RunJournal;\nexport type StorageSelection =\n\t| { readonly kind: \"memory\" }\n\t| { readonly kind: \"jsonl\"; readonly dir: string }\n\t| { readonly kind: \"sqlite\"; readonly path: string; readonly prefix?: string }\n\t| { readonly kind: \"database\"; readonly database: SqliteDatabase; readonly prefix?: string }\n\t| {\n\t\t\treadonly kind: \"adapter\";\n\t\t\treadonly module: string;\n\t\t\treadonly options?: AdapterOptions;\n\t\t\treadonly secrets?: Readonly<Record<string, SecretRef>>;\n\t\t\treadonly prefix?: string;\n\t };\nexport interface StorageOpenContext {\n\treadonly agentDir: string;\n\t/** `intercom`: the shared Intercom broker state that multi-node brokers open on the top-level selection. */\n\treadonly domain: \"sessions\" | \"journal\" | \"intercom\";\n\treadonly signal?: AbortSignal;\n}\nexport interface StorageAdapterModule {\n\treadonly atomicStorageAdapter: 1;\n\topenDatabase?(options: AdapterOptions, context: StorageOpenContext): Promise<SqliteDatabase>;\n\topenSessionStore?(\n\t\toptions: AdapterOptions,\n\t\tcontext: StorageOpenContext,\n\t\tstorage: { readonly prefix?: string },\n\t): Promise<SessionStore>;\n\topenRunJournal?(\n\t\toptions: AdapterOptions,\n\t\tcontext: StorageOpenContext,\n\t\tstorage: { readonly prefix?: string },\n\t): Promise<RunJournal>;\n}\nexport interface JournalFactories {\n\tmemory(descriptor: StorageDescriptor): RunJournal;\n\tsql(database: SqliteDatabase, options: { readonly prefix?: string }): Promise<RunJournal>;\n}\n\nconst databaseIds = new WeakMap<SqliteDatabase, number>();\nlet nextDatabaseId = 0;\n\nfunction storageOptionKey(\n\tvalue: SqliteValue | boolean,\n): readonly [string, string | boolean | readonly number[] | null] {\n\tif (value instanceof Uint8Array) return [\"bytes\", Array.from(value)];\n\tif (value === null) return [\"null\", null];\n\tif (typeof value === \"number\") return [\"number\", Object.is(value, -0) ? \"-0\" : String(value)];\n\tif (typeof value === \"bigint\") return [\"bigint\", String(value)];\n\treturn [typeof value, value];\n}\n\nexport function storageSelectionKey(selection: StorageSelection, agentDir?: string): string {\n\tif (selection.kind === \"database\") {\n\t\tlet id = databaseIds.get(selection.database);\n\t\tif (id === undefined) {\n\t\t\tid = ++nextDatabaseId;\n\t\t\tdatabaseIds.set(selection.database, id);\n\t\t}\n\t\treturn JSON.stringify([\"database\", id, selection.prefix ?? \"\"]);\n\t}\n\tif (selection.kind === \"sqlite\") {\n\t\tconst path = selection.path === \"\" || selection.path === \":memory:\" ? selection.path : resolve(selection.path);\n\t\treturn JSON.stringify([\"sqlite\", path, selection.prefix ?? \"\"]);\n\t}\n\tif (selection.kind === \"adapter\") {\n\t\tconst options = Object.entries(selection.options ?? {})\n\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t.map(([name, value]) => [name, storageOptionKey(value)]);\n\t\tconst secrets = Object.entries(selection.secrets ?? {}).sort(([a], [b]) => a.localeCompare(b));\n\t\treturn JSON.stringify([\"adapter\", agentDir, selection.module, options, secrets, selection.prefix ?? \"\"]);\n\t}\n\treturn JSON.stringify(selection);\n}\n\nexport async function loadStorageAdapter(module: string, context: StorageOpenContext): Promise<StorageAdapterModule> {\n\ttry {\n\t\tconst loader = createJiti(pathToFileURL(join(context.agentDir, \"storage-adapter.js\")).href, {\n\t\t\tinteropDefault: true,\n\t\t});\n\t\tconst adapter = await loader.import<StorageAdapterModule>(module, { default: true });\n\t\tif (\n\t\t\tadapter === null ||\n\t\t\ttypeof adapter !== \"object\" ||\n\t\t\tadapter.atomicStorageAdapter !== 1 ||\n\t\t\t[adapter.openDatabase, adapter.openSessionStore, adapter.openRunJournal].some(\n\t\t\t\t(hook) => hook !== undefined && typeof hook !== \"function\",\n\t\t\t)\n\t\t) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"adapter\", \"invalid-module-contract\");\n\t\t}\n\t\treturn adapter;\n\t} catch (cause) {\n\t\tthrow new StorageAdapterLoadError(module, cause as StorageFailureCause);\n\t}\n}\n\n/** The adapter's options with every `secrets` reference resolved, as the provider passes them to its hooks. */\nexport async function resolveAdapterOptions(\n\tselection: Extract<StorageSelection, { kind: \"adapter\" }>,\n\tcontext: StorageOpenContext,\n): Promise<AdapterOptions> {\n\tconst options = { ...selection.options };\n\tfor (const [name, ref] of Object.entries(selection.secrets ?? {})) {\n\t\tlet value: string;\n\t\tif (\"env\" in ref) {\n\t\t\tconst environment = process.env[ref.env];\n\t\t\tif (environment === undefined) throw new StorageConfigError(\"sdk\", `secrets.${name}`, \"secret-env-missing\");\n\t\t\tvalue = environment;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tvalue = await readFile(isAbsolute(ref.file) ? ref.file : join(dirname(context.agentDir), ref.file), \"utf8\");\n\t\t\t} catch (cause) {\n\t\t\t\tthrow new StorageUnavailableError(\n\t\t\t\t\t{ adapter: selection.module, location: ref.file },\n\t\t\t\t\tcause as StorageFailureCause,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tObject.defineProperty(options, name, { value, enumerable: true, writable: true, configurable: true });\n\t}\n\treturn options;\n}\n\nfunction withIdempotentClose<T extends { close(): Promise<void> }>(store: T, release?: () => Promise<void>): T {\n\tconst close = store.close.bind(store);\n\tlet closing: Promise<void> | undefined;\n\tstore.close = () => {\n\t\tclosing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tawait close();\n\t\t\t} finally {\n\t\t\t\tawait release?.();\n\t\t\t}\n\t\t})();\n\t\treturn closing;\n\t};\n\treturn store;\n}\n\ninterface SharedDatabase {\n\treadonly ready: Promise<SqliteDatabase>;\n\treferences: number;\n}\n\nconst sharedDatabases = new Map<string, SharedDatabase>();\n\nexport interface StorageProvider {\n\topenSessionStore(selection: StorageSelection, context: StorageOpenContext): Promise<SessionStore>;\n\topenRunJournal(selection: StorageSelection, context: StorageOpenContext): Promise<RunJournal>;\n}\n\nexport const StorageProvider: new (journals?: JournalFactories) => StorageProvider = class {\n\tprivate readonly journals?: JournalFactories;\n\tprivate readonly databases = sharedDatabases;\n\n\tconstructor(journals?: JournalFactories) {\n\t\tthis.journals = journals;\n\t}\n\n\tasync openSessionStore(selection: StorageSelection, context: StorageOpenContext): Promise<SessionStore> {\n\t\treturn this.open<SessionStore>(selection, context, {\n\t\t\tmemory: async () =>\n\t\t\t\tnew (await import(\"./session/memory-session-store.js\")).MemorySessionStore(createSessionCwdMatcher),\n\t\t\tjsonl: async (dir) =>\n\t\t\t\t(await import(\"./session/jsonl-session-store.js\")).JsonlSessionStore.open(dir, { exactDirectory: true }),\n\t\t\tdirect: (adapter, options, storage) => adapter.openSessionStore?.(options, context, storage),\n\t\t\tsql: async (database, options) =>\n\t\t\t\t(await import(\"./session/sql-session-store.js\")).SqlSessionStore.open(database, {\n\t\t\t\t\t...options,\n\t\t\t\t\tcwdMatcher: createSessionCwdMatcher,\n\t\t\t\t}),\n\t\t});\n\t}\n\n\tasync openRunJournal(selection: StorageSelection, context: StorageOpenContext): Promise<RunJournal> {\n\t\tconst journals = this.journals;\n\t\tif (!journals) throw new StorageConfigError(\"sdk\", \"journal\", \"adapter-domain-unsupported\");\n\t\treturn this.open<RunJournal>(selection, context, {\n\t\t\tmemory: () => journals.memory({ adapter: \"memory\", location: \":memory:\" }),\n\t\t\tdirect: (adapter, options, storage) => adapter.openRunJournal?.(options, context, storage),\n\t\t\tsql: async (database, options) => {\n\t\t\t\tconst journal = await journals.sql(database, options);\n\t\t\t\tconst createRun = journal.createRun.bind(journal);\n\t\t\t\tjournal.createRun = (header) => createRun({ ...header, storage: { ...database.descriptor } });\n\t\t\t\treturn journal;\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async open<T extends { close(): Promise<void> }>(\n\t\tselection: StorageSelection,\n\t\tcontext: StorageOpenContext,\n\t\tfactories: {\n\t\t\tmemory(): T | Promise<T>;\n\t\t\tjsonl?(dir: string): Promise<T>;\n\t\t\tdirect(\n\t\t\t\tadapter: StorageAdapterModule,\n\t\t\t\toptions: AdapterOptions,\n\t\t\t\tstorage: { readonly prefix?: string },\n\t\t\t): Promise<T> | undefined;\n\t\t\tsql(database: SqliteDatabase, options: { readonly prefix?: string }): Promise<T>;\n\t\t},\n\t): Promise<T> {\n\t\tif (selection === null || typeof selection !== \"object\" || Array.isArray(selection)) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"selection-object-required\");\n\t\t}\n\t\tif (![\"memory\", \"jsonl\", \"sqlite\", \"database\", \"adapter\"].includes(selection.kind)) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"invalid-kind\");\n\t\t}\n\t\tconst selector = { memory: undefined, jsonl: \"dir\", sqlite: \"path\", database: \"database\", adapter: \"module\" }[\n\t\t\tselection.kind\n\t\t];\n\t\tif (\n\t\t\t[\"path\", \"dir\", \"database\", \"module\", \"memory\", \"adapter\"].some((key) => key in selection && key !== selector)\n\t\t) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"multiple-selection-forms\");\n\t\t}\n\t\tif (selection.kind === \"sqlite\" && typeof selection.path !== \"string\") {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"invalid-path\");\n\t\t}\n\t\tif (selection.kind === \"adapter\" && (typeof selection.module !== \"string\" || selection.module.length === 0)) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"invalid-adapter\");\n\t\t}\n\t\tif (selection.kind === \"database\" && !(\"database\" in selection)) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"async-database-required\");\n\t\t}\n\t\tif (selection.kind === \"sqlite\" || selection.kind === \"database\" || selection.kind === \"adapter\") {\n\t\t\tselectStorage(\n\t\t\t\tselection.kind === \"adapter\" ? { ...selection, adapter: selection.module } : selection,\n\t\t\t\t\"sdk\",\n\t\t\t\t\"storage\",\n\t\t\t\t\"\",\n\t\t\t);\n\t\t}\n\t\tif (selection.kind === \"memory\") return withIdempotentClose(await factories.memory());\n\t\tif (selection.kind === \"jsonl\") {\n\t\t\tif (typeof selection.dir !== \"string\") throw new StorageConfigError(\"sdk\", \"dir\", \"invalid-dir\");\n\t\t\tif (factories.jsonl) return withIdempotentClose(await factories.jsonl(selection.dir));\n\t\t\tthrow new StorageConfigError(\"sdk\", \"dir\", \"adapter-domain-unsupported\");\n\t\t}\n\t\tvalidateStoragePrefix(selection.prefix);\n\t\tlet openDatabase: () => Promise<SqliteDatabase>;\n\t\tif (selection.kind === \"adapter\") {\n\t\t\tconst adapter = await loadStorageAdapter(selection.module, context);\n\t\t\tconst options = await resolveAdapterOptions(selection, context);\n\t\t\ttry {\n\t\t\t\tconst direct = factories.direct(adapter, options, { prefix: selection.prefix });\n\t\t\t\tif (direct !== undefined) return withIdempotentClose(await direct);\n\t\t\t} catch (cause) {\n\t\t\t\tif (cause instanceof StorageError) throw cause;\n\t\t\t\tthrow new StorageUnavailableError(\n\t\t\t\t\t{ adapter: selection.module, location: selection.module },\n\t\t\t\t\tcause as StorageFailureCause,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!adapter.openDatabase) throw new StorageConfigError(\"sdk\", \"adapter\", \"adapter-domain-unsupported\");\n\t\t\tconst hook = adapter.openDatabase.bind(adapter);\n\t\t\topenDatabase = async () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await hook(options, context);\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tif (cause instanceof StorageError) throw cause;\n\t\t\t\t\tthrow new StorageUnavailableError(\n\t\t\t\t\t\t{ adapter: selection.module, location: selection.module },\n\t\t\t\t\t\tcause as StorageFailureCause,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t};\n\t\t} else if (selection.kind === \"database\") {\n\t\t\treturn withIdempotentClose(await factories.sql(selection.database, { prefix: selection.prefix }));\n\t\t} else {\n\t\t\topenDatabase = () => openNodeSqliteDatabase(selection.path);\n\t\t}\n\t\tconst key = storageSelectionKey({ ...selection, prefix: undefined }, context.agentDir);\n\t\tlet shared = this.databases.get(key);\n\t\tif (!shared) {\n\t\t\tshared = { ready: openDatabase(), references: 0 };\n\t\t\tthis.databases.set(key, shared);\n\t\t}\n\t\tshared.references++;\n\t\tconst entry = shared;\n\t\tlet database: SqliteDatabase;\n\t\ttry {\n\t\t\tdatabase = await entry.ready;\n\t\t} catch (cause) {\n\t\t\tif (this.databases.get(key) === entry) this.databases.delete(key);\n\t\t\tthrow cause;\n\t\t}\n\t\tconst release = async () => {\n\t\t\tif (--entry.references === 0) {\n\t\t\t\tif (this.databases.get(key) === entry) this.databases.delete(key);\n\t\t\t\tawait database.close();\n\t\t\t}\n\t\t};\n\t\ttry {\n\t\t\treturn withIdempotentClose(await factories.sql(database, { prefix: selection.prefix }), release);\n\t\t} catch (cause) {\n\t\t\ttry {\n\t\t\t\tawait release();\n\t\t\t} catch (cleanupCause) {\n\t\t\t\tconst openingError =\n\t\t\t\t\tcause instanceof Error\n\t\t\t\t\t\t? cause\n\t\t\t\t\t\t: new StorageUnavailableError(database.descriptor, cause as StorageFailureCause);\n\t\t\t\tObject.defineProperty(openingError, \"cleanupCause\", { value: cleanupCause, configurable: true });\n\t\t\t\tthrow openingError;\n\t\t\t}\n\t\t\tthrow cause;\n\t\t}\n\t}\n};\n"]}
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/core/storage/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AAExE,OAAO,EACN,uBAAuB,EACvB,kBAAkB,EAClB,YAAY,EAEZ,uBAAuB,GACvB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAgD/C,MAAM,WAAW,GAAG,IAAI,OAAO,EAA0B,CAAC;AAC1D,IAAI,cAAc,GAAG,CAAC,CAAC;AAEvB,SAAS,gBAAgB,CACxB,KAA4B;IAE5B,IAAI,KAAK,YAAY,UAAU;QAAE,OAAO,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IACrE,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAC1C,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ACP,CAAC,CAAC,IAAI,uBAAuB,CAAC,QAAQ,CAAC,UAAU,EAAE,KAA4B,CAAC,CAAC;gBACnF,MAAM,CAAC,cAAc,CAAC,YAAY,EAAE,cAAc,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;gBACjG,MAAM,YAAY,CAAC;YACpB,CAAC;YACD,MAAM,KAAK,CAAC;QACb,CAAC;IACF,CAAC;CACD,CAAC","sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { createSessionCwdMatcher } from \"../../utils/canonical-path.ts\";\nimport type { SqliteDatabase, SqliteValue, StorageDescriptor } from \"./database.js\";\nimport {\n\tStorageAdapterLoadError,\n\tStorageConfigError,\n\tStorageError,\n\ttype StorageFailureCause,\n\tStorageUnavailableError,\n} from \"./errors.js\";\nimport { openNodeSqliteDatabase } from \"./node-sqlite.js\";\nimport { validateStoragePrefix } from \"./prefix.js\";\nimport type { RunJournal } from \"./run-journal.js\";\nimport { selectStorage } from \"./selection.js\";\nimport type { SessionStore } from \"./session/types.js\";\n\nexport type SecretRef = { readonly env: string } | { readonly file: string };\nexport type AdapterOptions = Readonly<Record<string, SqliteValue | boolean>>;\nexport type RunJournalOption =\n\t| { path: string; prefix?: string }\n\t| { database: SqliteDatabase; prefix?: string }\n\t| { memory: true }\n\t| { adapter: string; options?: AdapterOptions; secrets?: Readonly<Record<string, SecretRef>>; prefix?: string }\n\t| RunJournal;\nexport type StorageSelection =\n\t| { readonly kind: \"memory\" }\n\t| { readonly kind: \"jsonl\"; readonly dir: string }\n\t| { readonly kind: \"sqlite\"; readonly path: string; readonly prefix?: string }\n\t| { readonly kind: \"database\"; readonly database: SqliteDatabase; readonly prefix?: string }\n\t| {\n\t\t\treadonly kind: \"adapter\";\n\t\t\treadonly module: string;\n\t\t\treadonly options?: AdapterOptions;\n\t\t\treadonly secrets?: Readonly<Record<string, SecretRef>>;\n\t\t\treadonly prefix?: string;\n\t };\nexport interface StorageOpenContext {\n\treadonly agentDir: string;\n\t/** `intercom`: the shared Intercom broker state that multi-node brokers open on the top-level selection. */\n\treadonly domain: \"sessions\" | \"journal\" | \"intercom\";\n\treadonly signal?: AbortSignal;\n}\nexport interface StorageAdapterModule {\n\treadonly atomicStorageAdapter: 1;\n\topenDatabase?(options: AdapterOptions, context: StorageOpenContext): Promise<SqliteDatabase>;\n\topenSessionStore?(\n\t\toptions: AdapterOptions,\n\t\tcontext: StorageOpenContext,\n\t\tstorage: { readonly prefix?: string },\n\t): Promise<SessionStore>;\n\topenRunJournal?(\n\t\toptions: AdapterOptions,\n\t\tcontext: StorageOpenContext,\n\t\tstorage: { readonly prefix?: string },\n\t): Promise<RunJournal>;\n}\nexport interface JournalFactories {\n\tmemory(descriptor: StorageDescriptor): RunJournal;\n\tsql(database: SqliteDatabase, options: { readonly prefix?: string }): Promise<RunJournal>;\n}\n\nconst databaseIds = new WeakMap<SqliteDatabase, number>();\nlet nextDatabaseId = 0;\n\nfunction storageOptionKey(\n\tvalue: SqliteValue | boolean,\n): readonly [string, string | boolean | readonly number[] | null] {\n\tif (value instanceof Uint8Array) return [\"bytes\", Array.from(value)];\n\tif (value === null) return [\"null\", null];\n\tif (typeof value === \"number\") return [\"number\", Object.is(value, -0) ? \"-0\" : String(value)];\n\tif (typeof value === \"bigint\") return [\"bigint\", String(value)];\n\treturn [typeof value, value];\n}\n\nexport function storageSelectionKey(selection: StorageSelection, agentDir?: string): string {\n\tif (selection.kind === \"database\") {\n\t\tlet id = databaseIds.get(selection.database);\n\t\tif (id === undefined) {\n\t\t\tid = ++nextDatabaseId;\n\t\t\tdatabaseIds.set(selection.database, id);\n\t\t}\n\t\treturn JSON.stringify([\"database\", id, selection.prefix ?? \"\"]);\n\t}\n\tif (selection.kind === \"sqlite\") {\n\t\tconst path = selection.path === \"\" || selection.path === \":memory:\" ? selection.path : resolve(selection.path);\n\t\treturn JSON.stringify([\"sqlite\", path, selection.prefix ?? \"\"]);\n\t}\n\tif (selection.kind === \"adapter\") {\n\t\tconst options = Object.entries(selection.options ?? {})\n\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t.map(([name, value]) => [name, storageOptionKey(value)]);\n\t\tconst secrets = Object.entries(selection.secrets ?? {}).sort(([a], [b]) => a.localeCompare(b));\n\t\treturn JSON.stringify([\"adapter\", agentDir, selection.module, options, secrets, selection.prefix ?? \"\"]);\n\t}\n\treturn JSON.stringify(selection);\n}\n\n/**\n * Loads an adapter module the way the extension loader loads extensions: `@bastani/atomic/storage` (and\n * `@bastani/atomic`) resolve to this host's own modules, so adapters need no installed copy of Atomic and share its\n * error classes. A package name selects an adapter listed by an installed Atomic package; other specifiers, and\n * package names no installed package lists, resolve from the agent directory.\n */\nexport async function loadStorageAdapter(module: string, context: StorageOpenContext): Promise<StorageAdapterModule> {\n\ttry {\n\t\tconst [{ createHostModuleJiti }, { getStorageAdapterHostModules }, { resolvePackageStorageAdapter }] =\n\t\t\tawait Promise.all([\n\t\t\t\timport(\"../extensions/loader-virtual-modules.js\"),\n\t\t\t\timport(\"../extensions/loader-host-modules.js\"),\n\t\t\t\timport(\"../package-manager-storage-adapters.js\"),\n\t\t\t]);\n\t\tconst loader = await createHostModuleJiti(\n\t\t\tpathToFileURL(join(context.agentDir, \"storage-adapter.js\")).href,\n\t\t\tawait getStorageAdapterHostModules(),\n\t\t\t// JS adapters must also pass through virtual host modules, not native-import a second host copy.\n\t\t\t{ interopDefault: true, tryNative: false },\n\t\t);\n\t\tconst specifier = (await resolvePackageStorageAdapter(module, context.agentDir)) ?? module;\n\t\tconst location = loader.esmResolve(specifier);\n\t\tconst filename = location.startsWith(\"file:\") ? fileURLToPath(location) : location;\n\t\t// jiti's async JS fast path uses native import even with tryNative:false. Force only JS entrypoints\n\t\t// through its transform so their host imports use the live virtual modules, just like TS adapters.\n\t\tconst loaded = /\\.[cm]?js$/.test(filename)\n\t\t\t? await loader.evalModule(await readFile(filename, \"utf8\"), { filename, async: true, forceTranspile: true })\n\t\t\t: await loader.import<StorageAdapterModule>(specifier, { default: true });\n\t\tconst adapter = ((loaded as { default?: StorageAdapterModule })?.default ?? loaded) as StorageAdapterModule;\n\t\tif (\n\t\t\tadapter === null ||\n\t\t\ttypeof adapter !== \"object\" ||\n\t\t\tadapter.atomicStorageAdapter !== 1 ||\n\t\t\t[adapter.openDatabase, adapter.openSessionStore, adapter.openRunJournal].some(\n\t\t\t\t(hook) => hook !== undefined && typeof hook !== \"function\",\n\t\t\t)\n\t\t) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"adapter\", \"invalid-module-contract\");\n\t\t}\n\t\treturn adapter;\n\t} catch (cause) {\n\t\tthrow new StorageAdapterLoadError(module, cause as StorageFailureCause);\n\t}\n}\n\n/** The adapter's options with every `secrets` reference resolved, as the provider passes them to its hooks. */\nexport async function resolveAdapterOptions(\n\tselection: Extract<StorageSelection, { kind: \"adapter\" }>,\n\tcontext: StorageOpenContext,\n): Promise<AdapterOptions> {\n\tconst options = { ...selection.options };\n\tfor (const [name, ref] of Object.entries(selection.secrets ?? {})) {\n\t\tlet value: string;\n\t\tif (\"env\" in ref) {\n\t\t\tconst environment = process.env[ref.env];\n\t\t\tif (environment === undefined) throw new StorageConfigError(\"sdk\", `secrets.${name}`, \"secret-env-missing\");\n\t\t\tvalue = environment;\n\t\t} else {\n\t\t\tlet text: string;\n\t\t\ttry {\n\t\t\t\ttext = await readFile(isAbsolute(ref.file) ? ref.file : join(dirname(context.agentDir), ref.file), \"utf8\");\n\t\t\t} catch (cause) {\n\t\t\t\tthrow new StorageUnavailableError(\n\t\t\t\t\t{ adapter: selection.module, location: ref.file },\n\t\t\t\t\tcause as StorageFailureCause,\n\t\t\t\t);\n\t\t\t}\n\t\t\tvalue = text.endsWith(\"\\r\\n\") ? text.slice(0, -2) : text.endsWith(\"\\n\") ? text.slice(0, -1) : text;\n\t\t}\n\t\tObject.defineProperty(options, name, { value, enumerable: true, writable: true, configurable: true });\n\t}\n\treturn options;\n}\n\nfunction withIdempotentClose<T extends { close(): Promise<void> }>(store: T, release?: () => Promise<void>): T {\n\tconst close = store.close.bind(store);\n\tlet closing: Promise<void> | undefined;\n\tstore.close = () => {\n\t\tclosing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tawait close();\n\t\t\t} finally {\n\t\t\t\tawait release?.();\n\t\t\t}\n\t\t})();\n\t\treturn closing;\n\t};\n\treturn store;\n}\n\ninterface SharedDatabase {\n\treadonly ready: Promise<SqliteDatabase>;\n\treferences: number;\n}\n\nconst sharedDatabases = new Map<string, SharedDatabase>();\n\nexport interface StorageProvider {\n\topenSessionStore(selection: StorageSelection, context: StorageOpenContext): Promise<SessionStore>;\n\topenRunJournal(selection: StorageSelection, context: StorageOpenContext): Promise<RunJournal>;\n}\n\nexport const StorageProvider: new (journals?: JournalFactories) => StorageProvider = class {\n\tprivate readonly journals?: JournalFactories;\n\tprivate readonly databases = sharedDatabases;\n\n\tconstructor(journals?: JournalFactories) {\n\t\tthis.journals = journals;\n\t}\n\n\tasync openSessionStore(selection: StorageSelection, context: StorageOpenContext): Promise<SessionStore> {\n\t\treturn this.open<SessionStore>(selection, context, {\n\t\t\tmemory: async () =>\n\t\t\t\tnew (await import(\"./session/memory-session-store.js\")).MemorySessionStore(createSessionCwdMatcher),\n\t\t\tjsonl: async (dir) =>\n\t\t\t\t(await import(\"./session/jsonl-session-store.js\")).JsonlSessionStore.open(dir, { exactDirectory: true }),\n\t\t\tdirect: (adapter, options, storage) => adapter.openSessionStore?.(options, context, storage),\n\t\t\tsql: async (database, options) =>\n\t\t\t\t(await import(\"./session/sql-session-store.js\")).SqlSessionStore.open(database, {\n\t\t\t\t\t...options,\n\t\t\t\t\tcwdMatcher: createSessionCwdMatcher,\n\t\t\t\t}),\n\t\t});\n\t}\n\n\tasync openRunJournal(selection: StorageSelection, context: StorageOpenContext): Promise<RunJournal> {\n\t\tconst journals = this.journals;\n\t\tif (!journals) throw new StorageConfigError(\"sdk\", \"journal\", \"adapter-domain-unsupported\");\n\t\treturn this.open<RunJournal>(selection, context, {\n\t\t\tmemory: () => journals.memory({ adapter: \"memory\", location: \":memory:\" }),\n\t\t\tdirect: (adapter, options, storage) => adapter.openRunJournal?.(options, context, storage),\n\t\t\tsql: async (database, options) => {\n\t\t\t\tconst journal = await journals.sql(database, options);\n\t\t\t\tconst createRun = journal.createRun.bind(journal);\n\t\t\t\tjournal.createRun = (header) => createRun({ ...header, storage: { ...database.descriptor } });\n\t\t\t\treturn journal;\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async open<T extends { close(): Promise<void> }>(\n\t\tselection: StorageSelection,\n\t\tcontext: StorageOpenContext,\n\t\tfactories: {\n\t\t\tmemory(): T | Promise<T>;\n\t\t\tjsonl?(dir: string): Promise<T>;\n\t\t\tdirect(\n\t\t\t\tadapter: StorageAdapterModule,\n\t\t\t\toptions: AdapterOptions,\n\t\t\t\tstorage: { readonly prefix?: string },\n\t\t\t): Promise<T> | undefined;\n\t\t\tsql(database: SqliteDatabase, options: { readonly prefix?: string }): Promise<T>;\n\t\t},\n\t): Promise<T> {\n\t\tif (selection === null || typeof selection !== \"object\" || Array.isArray(selection)) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"selection-object-required\");\n\t\t}\n\t\tif (![\"memory\", \"jsonl\", \"sqlite\", \"database\", \"adapter\"].includes(selection.kind)) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"invalid-kind\");\n\t\t}\n\t\tconst selector = { memory: undefined, jsonl: \"dir\", sqlite: \"path\", database: \"database\", adapter: \"module\" }[\n\t\t\tselection.kind\n\t\t];\n\t\tif (\n\t\t\t[\"path\", \"dir\", \"database\", \"module\", \"memory\", \"adapter\"].some((key) => key in selection && key !== selector)\n\t\t) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"multiple-selection-forms\");\n\t\t}\n\t\tif (selection.kind === \"sqlite\" && typeof selection.path !== \"string\") {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"invalid-path\");\n\t\t}\n\t\tif (selection.kind === \"adapter\" && (typeof selection.module !== \"string\" || selection.module.length === 0)) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"invalid-adapter\");\n\t\t}\n\t\tif (selection.kind === \"database\" && !(\"database\" in selection)) {\n\t\t\tthrow new StorageConfigError(\"sdk\", \"storage\", \"async-database-required\");\n\t\t}\n\t\tif (selection.kind === \"sqlite\" || selection.kind === \"database\" || selection.kind === \"adapter\") {\n\t\t\tselectStorage(\n\t\t\t\tselection.kind === \"adapter\" ? { ...selection, adapter: selection.module } : selection,\n\t\t\t\t\"sdk\",\n\t\t\t\t\"storage\",\n\t\t\t\t\"\",\n\t\t\t);\n\t\t}\n\t\tif (selection.kind === \"memory\") return withIdempotentClose(await factories.memory());\n\t\tif (selection.kind === \"jsonl\") {\n\t\t\tif (typeof selection.dir !== \"string\") throw new StorageConfigError(\"sdk\", \"dir\", \"invalid-dir\");\n\t\t\tif (factories.jsonl) return withIdempotentClose(await factories.jsonl(selection.dir));\n\t\t\tthrow new StorageConfigError(\"sdk\", \"dir\", \"adapter-domain-unsupported\");\n\t\t}\n\t\tvalidateStoragePrefix(selection.prefix);\n\t\tlet openDatabase: () => Promise<SqliteDatabase>;\n\t\tif (selection.kind === \"adapter\") {\n\t\t\tconst adapter = await loadStorageAdapter(selection.module, context);\n\t\t\tconst options = await resolveAdapterOptions(selection, context);\n\t\t\ttry {\n\t\t\t\tconst direct = factories.direct(adapter, options, { prefix: selection.prefix });\n\t\t\t\tif (direct !== undefined) return withIdempotentClose(await direct);\n\t\t\t} catch (cause) {\n\t\t\t\tif (cause instanceof StorageError) throw cause;\n\t\t\t\tthrow new StorageUnavailableError(\n\t\t\t\t\t{ adapter: selection.module, location: selection.module },\n\t\t\t\t\tcause as StorageFailureCause,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!adapter.openDatabase) throw new StorageConfigError(\"sdk\", \"adapter\", \"adapter-domain-unsupported\");\n\t\t\tconst hook = adapter.openDatabase.bind(adapter);\n\t\t\topenDatabase = async () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn await hook(options, context);\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tif (cause instanceof StorageError) throw cause;\n\t\t\t\t\tthrow new StorageUnavailableError(\n\t\t\t\t\t\t{ adapter: selection.module, location: selection.module },\n\t\t\t\t\t\tcause as StorageFailureCause,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t};\n\t\t} else if (selection.kind === \"database\") {\n\t\t\treturn withIdempotentClose(await factories.sql(selection.database, { prefix: selection.prefix }));\n\t\t} else {\n\t\t\topenDatabase = () => openNodeSqliteDatabase(selection.path);\n\t\t}\n\t\tconst key = storageSelectionKey({ ...selection, prefix: undefined }, context.agentDir);\n\t\tlet shared = this.databases.get(key);\n\t\tif (!shared) {\n\t\t\tshared = { ready: openDatabase(), references: 0 };\n\t\t\tthis.databases.set(key, shared);\n\t\t}\n\t\tshared.references++;\n\t\tconst entry = shared;\n\t\tlet database: SqliteDatabase;\n\t\ttry {\n\t\t\tdatabase = await entry.ready;\n\t\t} catch (cause) {\n\t\t\tif (this.databases.get(key) === entry) this.databases.delete(key);\n\t\t\tthrow cause;\n\t\t}\n\t\tconst release = async () => {\n\t\t\tif (--entry.references === 0) {\n\t\t\t\tif (this.databases.get(key) === entry) this.databases.delete(key);\n\t\t\t\tawait database.close();\n\t\t\t}\n\t\t};\n\t\ttry {\n\t\t\treturn withIdempotentClose(await factories.sql(database, { prefix: selection.prefix }), release);\n\t\t} catch (cause) {\n\t\t\ttry {\n\t\t\t\tawait release();\n\t\t\t} catch (cleanupCause) {\n\t\t\t\tconst openingError =\n\t\t\t\t\tcause instanceof Error\n\t\t\t\t\t\t? cause\n\t\t\t\t\t\t: new StorageUnavailableError(database.descriptor, cause as StorageFailureCause);\n\t\t\t\tObject.defineProperty(openingError, \"cleanupCause\", { value: cleanupCause, configurable: true });\n\t\t\t\tthrow openingError;\n\t\t\t}\n\t\t\tthrow cause;\n\t\t}\n\t}\n};\n"]}
@@ -0,0 +1,49 @@
1
+ import type { SqliteDatabase, SqliteValue, StorageDescriptor } from "./database.js";
2
+ type Awaitable<T> = T | Promise<T>;
3
+ /** A value as a driver returns it. Blobs may be any binary view; the facade returns them as `Uint8Array` copies. */
4
+ export type SqliteDriverValue = SqliteValue | ArrayBuffer | ArrayBufferView;
5
+ /** One statement's result as a driver returns it: column names, positional rows, and the rows it changed. */
6
+ export interface SqliteDriverResult {
7
+ readonly columns: readonly string[];
8
+ readonly rows: readonly ArrayLike<SqliteDriverValue>[];
9
+ readonly changes: number;
10
+ }
11
+ /** Runs SQL on a driver connection or on an open driver transaction. */
12
+ export interface SqliteDriverExecutor {
13
+ /** Runs one statement with positional `?` parameters. */
14
+ execute(sql: string, params: readonly SqliteValue[]): Awaitable<SqliteDriverResult>;
15
+ /** Runs zero or more statements that take no parameters. */
16
+ executeMultiple(sql: string): Awaitable<void>;
17
+ }
18
+ export interface SqliteDriverTransaction extends SqliteDriverExecutor {
19
+ commit(): Awaitable<void>;
20
+ rollback(): Awaitable<void>;
21
+ /** Releases the transaction after it commits or rolls back. */
22
+ close?(): Awaitable<void>;
23
+ }
24
+ /** The driver calls `createSqliteDatabase` turns into a `SqliteDatabase`. */
25
+ export interface SqliteDriver extends SqliteDriverExecutor {
26
+ /** Diagnostic identity. Its `location` passes through `redact` before the facade exposes it. */
27
+ readonly descriptor: StorageDescriptor;
28
+ /** Begins a write transaction that holds the database's write lock, like `BEGIN IMMEDIATE`. */
29
+ beginTransaction(): Awaitable<SqliteDriverTransaction>;
30
+ /** Releases the connection. Called once, after accepted work drains. */
31
+ close(): Awaitable<void>;
32
+ /** Removes credentials from diagnostic text: the descriptor location and driver failure messages and stacks. */
33
+ redact?(text: string): string;
34
+ }
35
+ /**
36
+ * A redactor that replaces every non-empty secret, and its URI-encoded and URI-decoded forms, with `[redacted]`.
37
+ * Longer secrets are replaced first, so a secret that contains another is removed whole.
38
+ */
39
+ export declare function redactSecrets(secrets: Iterable<string>): (text: string) => string;
40
+ /**
41
+ * Wraps a SQLite-compatible driver as a `SqliteDatabase`. The facade queues operations in call order and keeps them
42
+ * outside active transactions, snapshots binary parameters at call time, rejects NUL text, returns safe-range integers
43
+ * as numbers and blobs as `Uint8Array` copies, expires transaction handles when their callback settles, maps driver
44
+ * failures to `StorageUnavailableError` with credentials redacted, and reports failed rollbacks with
45
+ * `StorageRollbackError`. Closing rejects new calls, drains accepted work, then closes the driver once.
46
+ */
47
+ export declare function createSqliteDatabase(driver: SqliteDriver): SqliteDatabase;
48
+ export {};
49
+ //# sourceMappingURL=sqlite-facade.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-facade.d.ts","sourceRoot":"","sources":["../../../src/core/storage/sqlite-facade.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAA6B,WAAW,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAW/G,KAAK,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAEnC,oHAAoH;AACpH,MAAM,MAAM,iBAAiB,GAAG,WAAW,GAAG,WAAW,GAAG,eAAe,CAAC;AAE5E,6GAA6G;AAC7G,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC,QAAQ,CAAC,IAAI,EAAE,SAAS,SAAS,CAAC,iBAAiB,CAAC,EAAE,CAAC;IACvD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CACzB;AAED,wEAAwE;AACxE,MAAM,WAAW,oBAAoB;IACpC,yDAAyD;IACzD,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,WAAW,EAAE,GAAG,SAAS,CAAC,kBAAkB,CAAC,CAAC;IACpF,4DAA4D;IAC5D,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;CAC9C;AAED,MAAM,WAAW,uBAAwB,SAAQ,oBAAoB;IACpE,MAAM,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC;IAC1B,QAAQ,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC;IAC5B,+DAA+D;IAC/D,KAAK,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED,6EAA6E;AAC7E,MAAM,WAAW,YAAa,SAAQ,oBAAoB;IACzD,gGAAgG;IAChG,QAAQ,CAAC,UAAU,EAAE,iBAAiB,CAAC;IACvC,+FAA+F;IAC/F,gBAAgB,IAAI,SAAS,CAAC,uBAAuB,CAAC,CAAC;IACvD,wEAAwE;IACxE,KAAK,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC;IACzB,gHAAgH;IAChH,MAAM,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;CAC9B;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,CAajF;AAmKD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,YAAY,GAAG,cAAc,CAEzE"}
@@ -0,0 +1,180 @@
1
+ import { StorageError, StorageInvalidTextError, StorageRollbackError, StorageTransactionClosedError, StorageUnavailableError, StoreClosedError, } from "./errors.js";
2
+ /**
3
+ * A redactor that replaces every non-empty secret, and its URI-encoded and URI-decoded forms, with `[redacted]`.
4
+ * Longer secrets are replaced first, so a secret that contains another is removed whole.
5
+ */
6
+ export function redactSecrets(secrets) {
7
+ const variants = new Set();
8
+ for (const secret of secrets) {
9
+ variants.add(secret);
10
+ try {
11
+ variants.add(encodeURIComponent(secret));
12
+ }
13
+ catch { }
14
+ try {
15
+ variants.add(decodeURIComponent(secret));
16
+ }
17
+ catch { }
18
+ }
19
+ const ordered = [...variants].filter(Boolean).sort((first, second) => second.length - first.length);
20
+ return (text) => ordered.reduce((value, secret) => value.replaceAll(secret, "[redacted]"), text);
21
+ }
22
+ function redactCause(cause, redact) {
23
+ if (typeof cause === "string")
24
+ return redact(cause);
25
+ if (!(cause instanceof Error))
26
+ return cause;
27
+ const nested = cause.cause;
28
+ const safeCause = redactCause(nested, redact);
29
+ const message = redact(cause.message);
30
+ const stack = cause.stack === undefined ? undefined : redact(cause.stack);
31
+ if (message === cause.message && stack === cause.stack && safeCause === nested)
32
+ return cause;
33
+ const safe = new StorageError(message, { cause: safeCause });
34
+ safe.stack = stack;
35
+ return safe;
36
+ }
37
+ function snapshotParams(params) {
38
+ return params.map((value) => (value instanceof Uint8Array ? new Uint8Array(value) : value));
39
+ }
40
+ function normalizeValue(value) {
41
+ if (typeof value === "bigint") {
42
+ return value >= -BigInt(Number.MAX_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER)
43
+ ? Number(value)
44
+ : value;
45
+ }
46
+ if (value instanceof ArrayBuffer)
47
+ return new Uint8Array(value.slice(0));
48
+ if (ArrayBuffer.isView(value))
49
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength).slice();
50
+ return value;
51
+ }
52
+ function normalizeRow(row, columns) {
53
+ return Object.fromEntries(columns.map((column, index) => [column, normalizeValue(row[index] ?? null)]));
54
+ }
55
+ /** Serializes operations in call order; a failed operation does not stop the ones queued after it. */
56
+ class CallQueue {
57
+ tail = Promise.resolve();
58
+ push(operation) {
59
+ const result = this.tail.then(operation);
60
+ this.tail = result.then(() => { }, () => { });
61
+ return result;
62
+ }
63
+ drained() {
64
+ return this.tail;
65
+ }
66
+ }
67
+ class DriverDatabase {
68
+ descriptor;
69
+ driver;
70
+ redact;
71
+ queue = new CallQueue();
72
+ closePromise;
73
+ executor;
74
+ constructor(driver, redact) {
75
+ this.driver = driver;
76
+ this.redact = redact;
77
+ this.descriptor = { adapter: driver.descriptor.adapter, location: redact(driver.descriptor.location) };
78
+ this.executor = this.createExecutor(driver, (operation) => {
79
+ if (this.closePromise)
80
+ return Promise.reject(new StoreClosedError(this.descriptor));
81
+ return this.queue.push(operation);
82
+ });
83
+ }
84
+ /** Maps a driver failure to `StorageUnavailableError` with a credential-free cause. */
85
+ async call(operation) {
86
+ try {
87
+ return await operation();
88
+ }
89
+ catch (cause) {
90
+ throw new StorageUnavailableError(this.descriptor, redactCause(cause, this.redact));
91
+ }
92
+ }
93
+ createExecutor(connection, admit) {
94
+ const statement = (sql, params) => {
95
+ const bound = snapshotParams(params);
96
+ return admit(async () => {
97
+ const invalidIndex = bound.findIndex((value) => typeof value === "string" && value.includes("\0"));
98
+ if (invalidIndex !== -1)
99
+ throw new StorageInvalidTextError(invalidIndex);
100
+ return this.call(() => connection.execute(sql, bound));
101
+ });
102
+ };
103
+ return {
104
+ exec: (sql) => admit(() => this.call(() => connection.executeMultiple(sql))),
105
+ run: async (sql, ...params) => ({ changes: (await statement(sql, params)).changes }),
106
+ get: async (sql, ...params) => {
107
+ const result = await statement(sql, params);
108
+ const row = result.rows[0];
109
+ return row === undefined ? undefined : normalizeRow(row, result.columns);
110
+ },
111
+ all: async (sql, ...params) => {
112
+ const result = await statement(sql, params);
113
+ return result.rows.map((row) => normalizeRow(row, result.columns));
114
+ },
115
+ };
116
+ }
117
+ exec(sql) {
118
+ return this.executor.exec(sql);
119
+ }
120
+ run(sql, ...params) {
121
+ return this.executor.run(sql, ...params);
122
+ }
123
+ get(sql, ...params) {
124
+ return this.executor.get(sql, ...params);
125
+ }
126
+ all(sql, ...params) {
127
+ return this.executor.all(sql, ...params);
128
+ }
129
+ transaction(callback) {
130
+ if (this.closePromise)
131
+ return Promise.reject(new StoreClosedError(this.descriptor));
132
+ return this.queue.push(async () => {
133
+ const connection = await this.call(() => this.driver.beginTransaction());
134
+ const handleQueue = new CallQueue();
135
+ let active = true;
136
+ let result;
137
+ const handle = this.createExecutor(connection, (operation) => active ? handleQueue.push(operation) : Promise.reject(new StorageTransactionClosedError()));
138
+ const close = () => this.call(() => connection.close?.());
139
+ try {
140
+ try {
141
+ result = await callback(handle);
142
+ }
143
+ finally {
144
+ active = false;
145
+ await handleQueue.drained();
146
+ }
147
+ await this.call(() => connection.commit());
148
+ }
149
+ catch (cause) {
150
+ let failure = cause;
151
+ try {
152
+ await this.call(() => connection.rollback());
153
+ }
154
+ catch (rollbackCause) {
155
+ failure = new StorageRollbackError(failure, rollbackCause);
156
+ }
157
+ // Cleanup must not replace a callback, commit, or rollback failure.
158
+ await close().catch(() => { });
159
+ throw failure;
160
+ }
161
+ await close();
162
+ return result;
163
+ });
164
+ }
165
+ close() {
166
+ this.closePromise ??= this.queue.drained().then(() => this.call(() => this.driver.close()));
167
+ return this.closePromise;
168
+ }
169
+ }
170
+ /**
171
+ * Wraps a SQLite-compatible driver as a `SqliteDatabase`. The facade queues operations in call order and keeps them
172
+ * outside active transactions, snapshots binary parameters at call time, rejects NUL text, returns safe-range integers
173
+ * as numbers and blobs as `Uint8Array` copies, expires transaction handles when their callback settles, maps driver
174
+ * failures to `StorageUnavailableError` with credentials redacted, and reports failed rollbacks with
175
+ * `StorageRollbackError`. Closing rejects new calls, drains accepted work, then closes the driver once.
176
+ */
177
+ export function createSqliteDatabase(driver) {
178
+ return new DriverDatabase(driver, driver.redact?.bind(driver) ?? ((text) => text));
179
+ }
180
+ //# sourceMappingURL=sqlite-facade.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-facade.js","sourceRoot":"","sources":["../../../src/core/storage/sqlite-facade.ts"],"names":[],"mappings":"AACA,OAAO,EACN,YAAY,EAEZ,uBAAuB,EACvB,oBAAoB,EACpB,6BAA6B,EAC7B,uBAAuB,EACvB,gBAAgB,GAChB,MAAM,aAAa,CAAC;AAyCrB;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,OAAyB;IACtD,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAC;IACnC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC9B,QAA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BACJ,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC,CAAC;gBAC9C,CAAC;gBAAC,OAAO,aAAa,EAAE,CAAC;oBACxB,OAAO,GAAG,IAAI,oBAAoB,CAAC,OAAO,EAAE,aAAoC,CAAC,CAAC;gBACnF,CAAC;gBACD,oEAAoE;gBACpE,MAAM,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;gBAC9B,MAAM,OAAO,CAAC;YACf,CAAC;YACD,MAAM,KAAK,EAAE,CAAC;YACd,OAAO,MAAM,CAAC;QACf,CAAC,CAAC,CAAC;IACJ,CAAC;IAED,KAAK;QACJ,IAAI,CAAC,YAAY,KAAK,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QAC5F,OAAO,IAAI,CAAC,YAAY,CAAC;IAC1B,CAAC;CACD;AAED;;;;;;GAMG;AACH,MAAM,UAAU,oBAAoB,CAAC,MAAoB;IACxD,OAAO,IAAI,cAAc,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;AACpF,CAAC","sourcesContent":["import type { SqliteDatabase, SqliteExecutor, SqliteRow, SqliteValue, StorageDescriptor } from \"./database.js\";\nimport {\n\tStorageError,\n\ttype StorageFailureCause,\n\tStorageInvalidTextError,\n\tStorageRollbackError,\n\tStorageTransactionClosedError,\n\tStorageUnavailableError,\n\tStoreClosedError,\n} from \"./errors.js\";\n\ntype Awaitable<T> = T | Promise<T>;\n\n/** A value as a driver returns it. Blobs may be any binary view; the facade returns them as `Uint8Array` copies. */\nexport type SqliteDriverValue = SqliteValue | ArrayBuffer | ArrayBufferView;\n\n/** One statement's result as a driver returns it: column names, positional rows, and the rows it changed. */\nexport interface SqliteDriverResult {\n\treadonly columns: readonly string[];\n\treadonly rows: readonly ArrayLike<SqliteDriverValue>[];\n\treadonly changes: number;\n}\n\n/** Runs SQL on a driver connection or on an open driver transaction. */\nexport interface SqliteDriverExecutor {\n\t/** Runs one statement with positional `?` parameters. */\n\texecute(sql: string, params: readonly SqliteValue[]): Awaitable<SqliteDriverResult>;\n\t/** Runs zero or more statements that take no parameters. */\n\texecuteMultiple(sql: string): Awaitable<void>;\n}\n\nexport interface SqliteDriverTransaction extends SqliteDriverExecutor {\n\tcommit(): Awaitable<void>;\n\trollback(): Awaitable<void>;\n\t/** Releases the transaction after it commits or rolls back. */\n\tclose?(): Awaitable<void>;\n}\n\n/** The driver calls `createSqliteDatabase` turns into a `SqliteDatabase`. */\nexport interface SqliteDriver extends SqliteDriverExecutor {\n\t/** Diagnostic identity. Its `location` passes through `redact` before the facade exposes it. */\n\treadonly descriptor: StorageDescriptor;\n\t/** Begins a write transaction that holds the database's write lock, like `BEGIN IMMEDIATE`. */\n\tbeginTransaction(): Awaitable<SqliteDriverTransaction>;\n\t/** Releases the connection. Called once, after accepted work drains. */\n\tclose(): Awaitable<void>;\n\t/** Removes credentials from diagnostic text: the descriptor location and driver failure messages and stacks. */\n\tredact?(text: string): string;\n}\n\n/**\n * A redactor that replaces every non-empty secret, and its URI-encoded and URI-decoded forms, with `[redacted]`.\n * Longer secrets are replaced first, so a secret that contains another is removed whole.\n */\nexport function redactSecrets(secrets: Iterable<string>): (text: string) => string {\n\tconst variants = new Set<string>();\n\tfor (const secret of secrets) {\n\t\tvariants.add(secret);\n\t\ttry {\n\t\t\tvariants.add(encodeURIComponent(secret));\n\t\t} catch {}\n\t\ttry {\n\t\t\tvariants.add(decodeURIComponent(secret));\n\t\t} catch {}\n\t}\n\tconst ordered = [...variants].filter(Boolean).sort((first, second) => second.length - first.length);\n\treturn (text) => ordered.reduce((value, secret) => value.replaceAll(secret, \"[redacted]\"), text);\n}\n\nfunction redactCause(cause: StorageFailureCause, redact: (text: string) => string): StorageFailureCause {\n\tif (typeof cause === \"string\") return redact(cause);\n\tif (!(cause instanceof Error)) return cause;\n\tconst nested = cause.cause as StorageFailureCause;\n\tconst safeCause = redactCause(nested, redact);\n\tconst message = redact(cause.message);\n\tconst stack = cause.stack === undefined ? undefined : redact(cause.stack);\n\tif (message === cause.message && stack === cause.stack && safeCause === nested) return cause;\n\tconst safe = new StorageError(message, { cause: safeCause });\n\tsafe.stack = stack;\n\treturn safe;\n}\n\nfunction snapshotParams(params: readonly SqliteValue[]): SqliteValue[] {\n\treturn params.map((value) => (value instanceof Uint8Array ? new Uint8Array(value) : value));\n}\n\nfunction normalizeValue(value: SqliteDriverValue): SqliteValue {\n\tif (typeof value === \"bigint\") {\n\t\treturn value >= -BigInt(Number.MAX_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER)\n\t\t\t? Number(value)\n\t\t\t: value;\n\t}\n\tif (value instanceof ArrayBuffer) return new Uint8Array(value.slice(0));\n\tif (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength).slice();\n\treturn value;\n}\n\nfunction normalizeRow(row: ArrayLike<SqliteDriverValue>, columns: readonly string[]): SqliteRow {\n\treturn Object.fromEntries(columns.map((column, index) => [column, normalizeValue(row[index] ?? null)]));\n}\n\n/** Serializes operations in call order; a failed operation does not stop the ones queued after it. */\nclass CallQueue {\n\tprivate tail: Promise<void> = Promise.resolve();\n\n\tpush<T>(operation: () => Promise<T>): Promise<T> {\n\t\tconst result = this.tail.then(operation);\n\t\tthis.tail = result.then(\n\t\t\t() => {},\n\t\t\t() => {},\n\t\t);\n\t\treturn result;\n\t}\n\n\tdrained(): Promise<void> {\n\t\treturn this.tail;\n\t}\n}\n\nclass DriverDatabase implements SqliteDatabase {\n\treadonly descriptor: StorageDescriptor;\n\tprivate readonly driver: SqliteDriver;\n\tprivate readonly redact: (text: string) => string;\n\tprivate readonly queue = new CallQueue();\n\tprivate closePromise?: Promise<void>;\n\tprivate readonly executor: SqliteExecutor;\n\n\tconstructor(driver: SqliteDriver, redact: (text: string) => string) {\n\t\tthis.driver = driver;\n\t\tthis.redact = redact;\n\t\tthis.descriptor = { adapter: driver.descriptor.adapter, location: redact(driver.descriptor.location) };\n\t\tthis.executor = this.createExecutor(driver, (operation) => {\n\t\t\tif (this.closePromise) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\t\treturn this.queue.push(operation);\n\t\t});\n\t}\n\n\t/** Maps a driver failure to `StorageUnavailableError` with a credential-free cause. */\n\tprivate async call<T>(operation: () => Awaitable<T>): Promise<T> {\n\t\ttry {\n\t\t\treturn await operation();\n\t\t} catch (cause) {\n\t\t\tthrow new StorageUnavailableError(this.descriptor, redactCause(cause as StorageFailureCause, this.redact));\n\t\t}\n\t}\n\n\tprivate createExecutor(\n\t\tconnection: SqliteDriverExecutor,\n\t\tadmit: <T>(operation: () => Promise<T>) => Promise<T>,\n\t): SqliteExecutor {\n\t\tconst statement = (sql: string, params: readonly SqliteValue[]) => {\n\t\t\tconst bound = snapshotParams(params);\n\t\t\treturn admit(async () => {\n\t\t\t\tconst invalidIndex = bound.findIndex((value) => typeof value === \"string\" && value.includes(\"\\0\"));\n\t\t\t\tif (invalidIndex !== -1) throw new StorageInvalidTextError(invalidIndex);\n\t\t\t\treturn this.call(() => connection.execute(sql, bound));\n\t\t\t});\n\t\t};\n\t\treturn {\n\t\t\texec: (sql) => admit(() => this.call(() => connection.executeMultiple(sql))),\n\t\t\trun: async (sql, ...params) => ({ changes: (await statement(sql, params)).changes }),\n\t\t\tget: async <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) => {\n\t\t\t\tconst result = await statement(sql, params);\n\t\t\t\tconst row = result.rows[0];\n\t\t\t\treturn row === undefined ? undefined : (normalizeRow(row, result.columns) as T);\n\t\t\t},\n\t\t\tall: async <T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]) => {\n\t\t\t\tconst result = await statement(sql, params);\n\t\t\t\treturn result.rows.map((row) => normalizeRow(row, result.columns) as T);\n\t\t\t},\n\t\t};\n\t}\n\n\texec(sql: string): Promise<void> {\n\t\treturn this.executor.exec(sql);\n\t}\n\n\trun(sql: string, ...params: readonly SqliteValue[]) {\n\t\treturn this.executor.run(sql, ...params);\n\t}\n\n\tget<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T | undefined> {\n\t\treturn this.executor.get<T>(sql, ...params);\n\t}\n\n\tall<T extends SqliteRow>(sql: string, ...params: readonly SqliteValue[]): Promise<T[]> {\n\t\treturn this.executor.all<T>(sql, ...params);\n\t}\n\n\ttransaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {\n\t\tif (this.closePromise) return Promise.reject(new StoreClosedError(this.descriptor));\n\t\treturn this.queue.push(async () => {\n\t\t\tconst connection = await this.call(() => this.driver.beginTransaction());\n\t\t\tconst handleQueue = new CallQueue();\n\t\t\tlet active = true;\n\t\t\tlet result: T;\n\t\t\tconst handle = this.createExecutor(connection, (operation) =>\n\t\t\t\tactive ? handleQueue.push(operation) : Promise.reject(new StorageTransactionClosedError()),\n\t\t\t);\n\t\t\tconst close = () => this.call(() => connection.close?.());\n\t\t\ttry {\n\t\t\t\ttry {\n\t\t\t\t\tresult = await callback(handle);\n\t\t\t\t} finally {\n\t\t\t\t\tactive = false;\n\t\t\t\t\tawait handleQueue.drained();\n\t\t\t\t}\n\t\t\t\tawait this.call(() => connection.commit());\n\t\t\t} catch (cause) {\n\t\t\t\tlet failure = cause as StorageFailureCause;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.call(() => connection.rollback());\n\t\t\t\t} catch (rollbackCause) {\n\t\t\t\t\tfailure = new StorageRollbackError(failure, rollbackCause as StorageFailureCause);\n\t\t\t\t}\n\t\t\t\t// Cleanup must not replace a callback, commit, or rollback failure.\n\t\t\t\tawait close().catch(() => {});\n\t\t\t\tthrow failure;\n\t\t\t}\n\t\t\tawait close();\n\t\t\treturn result;\n\t\t});\n\t}\n\n\tclose(): Promise<void> {\n\t\tthis.closePromise ??= this.queue.drained().then(() => this.call(() => this.driver.close()));\n\t\treturn this.closePromise;\n\t}\n}\n\n/**\n * Wraps a SQLite-compatible driver as a `SqliteDatabase`. The facade queues operations in call order and keeps them\n * outside active transactions, snapshots binary parameters at call time, rejects NUL text, returns safe-range integers\n * as numbers and blobs as `Uint8Array` copies, expires transaction handles when their callback settles, maps driver\n * failures to `StorageUnavailableError` with credentials redacted, and reports failed rollbacks with\n * `StorageRollbackError`. Closing rejects new calls, drains accepted work, then closes the driver once.\n */\nexport function createSqliteDatabase(driver: SqliteDriver): SqliteDatabase {\n\treturn new DriverDatabase(driver, driver.redact?.bind(driver) ?? ((text) => text));\n}\n"]}