@bastani/atomic 0.10.11-alpha.2 → 0.10.11

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 (447) hide show
  1. package/CHANGELOG.md +307 -0
  2. package/README.md +5 -8
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +6 -6
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +5 -5
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +6 -6
  9. package/dist/_shared/p0-cli-BB45ZQY6.js +46 -67
  10. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +7 -8
  12. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  13. package/dist/_shared/{p1b-elig-ENCUPKKJ.js → p1b-elig-TVB5CBLL.js} +36 -8
  14. package/dist/_shared/p1b-elig-TVB5CBLL.js.map +1 -0
  15. package/dist/_shared/p2-shell-main-B2WIALFD.js +6 -3
  16. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  17. package/dist/_shared/runtime-O4KCSG4C.js +3 -3
  18. package/dist/_shared/{sdk-IQMULKFU.js → sdk-B5LEWGGI.js} +1218 -657
  19. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  20. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  21. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  22. package/dist/_shared/{startup-0-0-3IXNMFM2.js → startup-0-0-XJJDOIEC.js} +50 -48
  23. package/dist/_shared/startup-0-0-XJJDOIEC.js.map +1 -0
  24. package/dist/_shared/{startup-0-1-7T2IAE7J.js → startup-0-1-M6OWAYHH.js} +540 -136
  25. package/dist/_shared/startup-0-1-M6OWAYHH.js.map +1 -0
  26. package/dist/_shared/startup-0-2-5QHPCEON.js +47 -48
  27. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  28. package/dist/_shared/startup-0-3-4ZYBYQNM.js +5 -5
  29. package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
  30. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  31. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  32. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  33. package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
  34. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  35. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -5
  36. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  37. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  38. package/dist/_shared/startup-15-1-4S7FLMNG.js +19 -27
  39. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  40. package/dist/_shared/startup-8-0-34CBHPZH.js +2144 -249
  41. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  42. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +98 -1184
  43. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  44. package/dist/_shared/storage-command-7MGXLJGZ.js +188 -37
  45. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  46. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  47. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  48. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  49. package/dist/_shared/team-DOQKICG2.js +376 -0
  50. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  51. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  52. package/dist/builtin/intercom/CHANGELOG.md +88 -0
  53. package/dist/builtin/intercom/README.md +2 -2
  54. package/dist/builtin/intercom/broker/broker.bundle.mjs +1917 -381
  55. package/dist/builtin/intercom/broker/client.ts +8 -0
  56. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +324 -68
  57. package/dist/builtin/intercom/broker/multinode-router.ts +256 -39
  58. package/dist/builtin/intercom/broker/multinode-state-store.ts +71 -5
  59. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  60. package/dist/builtin/intercom/broker/send-order-gate.ts +5 -2
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +50 -5
  62. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  63. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  64. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  65. package/dist/builtin/intercom/broker/sql-lease-store.ts +473 -121
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +821 -79
  67. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  68. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  69. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +256 -8
  70. package/dist/builtin/intercom/broker/sql-retention.ts +150 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +175 -24
  72. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  73. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  74. package/dist/builtin/intercom/index.bundle.mjs +14 -4
  75. package/dist/builtin/intercom/package.json +1 -1
  76. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  77. package/dist/builtin/mcp/package.json +1 -1
  78. package/dist/builtin/subagents/CHANGELOG.md +20 -0
  79. package/dist/builtin/subagents/package.json +1 -1
  80. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +8 -1
  81. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  82. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  83. package/dist/builtin/web-access/package.json +1 -1
  84. package/dist/bun/bundled-sqlite.js +41 -0
  85. package/dist/bun/bundled-sqlite.js.map +1 -0
  86. package/dist/cli/args.js +2 -2
  87. package/dist/cli/auth-cli.code.js +4 -4
  88. package/dist/cli/auth-cli.impl.js +3 -3
  89. package/dist/cli/auth-cli.js +3 -3
  90. package/dist/cli/blueprint-command.code.js +3 -3
  91. package/dist/cli/blueprint-command.impl.js +3 -3
  92. package/dist/cli/blueprint-command.js +3 -3
  93. package/dist/cli/intercom-command.code.js +3 -3
  94. package/dist/cli/intercom-command.code.js.map +1 -1
  95. package/dist/cli/intercom-command.impl.js +3 -3
  96. package/dist/cli/intercom-command.js +3 -3
  97. package/dist/cli/list-models.code.js +2 -2
  98. package/dist/cli/list-models.impl.js +3 -3
  99. package/dist/cli/list-models.js +3 -3
  100. package/dist/cli/session-picker.code.js +1 -1
  101. package/dist/cli/session-picker.impl.js +3 -3
  102. package/dist/cli/session-picker.js +3 -3
  103. package/dist/cli/startup-ui.code.js +1 -1
  104. package/dist/cli/startup-ui.impl.js +3 -3
  105. package/dist/cli/startup-ui.js +3 -3
  106. package/dist/cli/storage-command.impl.js +3 -3
  107. package/dist/cli/storage-command.js +3 -3
  108. package/dist/cli/storage-search-session.code.js +3 -3
  109. package/dist/cli/storage-search-session.impl.js +3 -3
  110. package/dist/cli/storage-search-session.js +3 -3
  111. package/dist/cli/team-command.code.js +19 -113
  112. package/dist/cli/team-command.code.js.map +1 -1
  113. package/dist/cli/team-command.impl.js +3 -3
  114. package/dist/cli/team-command.js +3 -3
  115. package/dist/cli.js +5 -18
  116. package/dist/cli.js.map +1 -1
  117. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  118. package/dist/core/compaction/compactor.d.ts +3 -3
  119. package/dist/core/debug.code.js +1 -1
  120. package/dist/core/debug.impl.js +3 -3
  121. package/dist/core/debug.js +3 -3
  122. package/dist/core/export-html/card-projection.impl.js +3 -3
  123. package/dist/core/export-html/card-projection.js +3 -3
  124. package/dist/core/export-html/index.code.js +4 -4
  125. package/dist/core/export-html/index.code.js.map +1 -1
  126. package/dist/core/export-html/index.impl.js +3 -3
  127. package/dist/core/export-html/index.js +3 -3
  128. package/dist/core/export-html/json-spans.impl.js +3 -3
  129. package/dist/core/export-html/json-spans.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  131. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  132. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  133. package/dist/core/export-html/tool-renderer.js +3 -3
  134. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  135. package/dist/core/extensions/jiti-loader.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  137. package/dist/core/extensions/jiti-static-loader.js +3 -3
  138. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  139. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  140. package/dist/core/extensions/loader-host-modules.js +3 -3
  141. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  142. package/dist/core/extensions/runner-context.js +2 -2
  143. package/dist/core/intercom-broker-control-host.code.js +2 -2
  144. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  145. package/dist/core/intercom-broker-control-host.js +3 -3
  146. package/dist/core/intercom-broker-control.code.js +3 -3
  147. package/dist/core/intercom-broker-control.impl.js +3 -3
  148. package/dist/core/intercom-broker-control.js +3 -3
  149. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  150. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  151. package/dist/core/package-manager-storage-adapters.js +3 -3
  152. package/dist/core/process-start-token.d.ts +12 -3
  153. package/dist/core/process-tree-containment.d.ts +16 -0
  154. package/dist/core/sdk-types.d.ts +1 -2
  155. package/dist/core/sdk-types.js.map +1 -1
  156. package/dist/core/sdk.code.js +3 -3
  157. package/dist/core/sdk.impl.js +3 -3
  158. package/dist/core/sdk.js +3 -3
  159. package/dist/core/session-manager-core.js +5 -5
  160. package/dist/core/session-manager-list.impl.js +3 -3
  161. package/dist/core/session-manager-list.js +3 -3
  162. package/dist/core/session-manager.code.js +1 -1
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-storage.code.js +1 -1
  166. package/dist/core/session-storage.impl.js +3 -3
  167. package/dist/core/session-storage.js +3 -3
  168. package/dist/core/settings-schema.d.ts +0 -3
  169. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  170. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  171. package/dist/core/storage/creation-time.js +105 -0
  172. package/dist/core/storage/creation-time.js.map +1 -0
  173. package/dist/core/storage/database.d.ts +25 -5
  174. package/dist/core/storage/database.js.map +1 -1
  175. package/dist/core/storage/dialect.d.ts +1 -1
  176. package/dist/core/storage/dialect.js +1 -1
  177. package/dist/core/storage/dialect.js.map +1 -1
  178. package/dist/core/storage/errors.d.ts +13 -13
  179. package/dist/core/storage/errors.js +10 -16
  180. package/dist/core/storage/errors.js.map +1 -1
  181. package/dist/core/storage/fenced-paths.d.ts +18 -6
  182. package/dist/core/storage/fenced-paths.js +18 -6
  183. package/dist/core/storage/fenced-paths.js.map +1 -1
  184. package/dist/core/storage/file-identity.d.ts +2 -0
  185. package/dist/core/storage/file-identity.js +24 -8
  186. package/dist/core/storage/file-identity.js.map +1 -1
  187. package/dist/core/storage/index.d.ts +3 -2
  188. package/dist/core/storage/index.js +5 -3
  189. package/dist/core/storage/index.js.map +1 -1
  190. package/dist/core/storage/libsql-removed.d.ts +71 -0
  191. package/dist/core/storage/libsql-removed.js +123 -0
  192. package/dist/core/storage/libsql-removed.js.map +1 -0
  193. package/dist/core/storage/migrations.d.ts +78 -14
  194. package/dist/core/storage/migrations.js +375 -49
  195. package/dist/core/storage/migrations.js.map +1 -1
  196. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  197. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  198. package/dist/core/storage/node-sqlite-thread.js +215 -30
  199. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  200. package/dist/core/storage/node-sqlite.js +484 -72
  201. package/dist/core/storage/node-sqlite.js.map +1 -1
  202. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  203. package/dist/core/storage/offline-snapshot-file.js +3 -3
  204. package/dist/core/storage/prefix.d.ts +1 -1
  205. package/dist/core/storage/prefix.js +9 -2
  206. package/dist/core/storage/prefix.js.map +1 -1
  207. package/dist/core/storage/process-selection.d.ts +5 -5
  208. package/dist/core/storage/provider.js +2 -2
  209. package/dist/core/storage/schema-catalog.d.ts +76 -15
  210. package/dist/core/storage/schema-catalog.js +359 -68
  211. package/dist/core/storage/schema-catalog.js.map +1 -1
  212. package/dist/core/storage/selection.d.ts +7 -82
  213. package/dist/core/storage/selection.js +20 -235
  214. package/dist/core/storage/selection.js.map +1 -1
  215. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  216. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  217. package/dist/core/storage/session/branch-fork-source.js +3 -3
  218. package/dist/core/storage/session/card-view.impl.js +3 -3
  219. package/dist/core/storage/session/card-view.js +3 -3
  220. package/dist/core/storage/session/child-reader.code.js +3 -3
  221. package/dist/core/storage/session/child-reader.impl.js +3 -3
  222. package/dist/core/storage/session/child-reader.js +3 -3
  223. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  224. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  225. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  226. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  227. package/dist/core/storage/session/expanded-child-details.js +3 -3
  228. package/dist/core/storage/session/fork-detach.d.ts +11 -1
  229. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  230. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  231. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  232. package/dist/core/storage/session/fork-row-index.js +3 -3
  233. package/dist/core/storage/session/fork-staging.code.js +4 -7
  234. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  235. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  236. package/dist/core/storage/session/fork-staging.js +3 -3
  237. package/dist/core/storage/session/fork-sweep.js +31 -7
  238. package/dist/core/storage/session/fork-sweep.js.map +1 -1
  239. package/dist/core/storage/session/fork-window.code.js +3 -3
  240. package/dist/core/storage/session/fork-window.impl.js +3 -3
  241. package/dist/core/storage/session/fork-window.js +3 -3
  242. package/dist/core/storage/session/history-pages.impl.js +3 -3
  243. package/dist/core/storage/session/history-pages.js +3 -3
  244. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  245. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  246. package/dist/core/storage/session/jsonl-session-lock.d.ts +100 -0
  247. package/dist/core/storage/session/jsonl-session-store.d.ts +46 -24
  248. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  249. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  250. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  251. package/dist/core/storage/session/memory-session-store.js +3 -3
  252. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  253. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  254. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  255. package/dist/core/storage/session/released-history-files.code.js +9 -9
  256. package/dist/core/storage/session/released-history-files.code.js.map +1 -1
  257. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  258. package/dist/core/storage/session/released-history-files.js +3 -3
  259. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  260. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  261. package/dist/core/storage/session/session-resume.impl.js +3 -3
  262. package/dist/core/storage/session/session-resume.js +3 -3
  263. package/dist/core/storage/session/session-search-index.d.ts +52 -5
  264. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  265. package/dist/core/storage/session/snapshot-cut.js +3 -3
  266. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  267. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  268. package/dist/core/storage/session/snapshot-history.js +3 -3
  269. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  270. package/dist/core/storage/session/sql-session-store.d.ts +99 -18
  271. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  272. package/dist/core/storage/session/sql-session-store.js +3 -3
  273. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  274. package/dist/core/storage/session/tree-outline.js +3 -3
  275. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  276. package/dist/core/storage/session/tree-presentation.js +3 -3
  277. package/dist/core/storage/sqlite-facade.d.ts +12 -1
  278. package/dist/core/storage/sqlite-facade.js +310 -33
  279. package/dist/core/storage/sqlite-facade.js.map +1 -1
  280. package/dist/core/storage/sqlite-open-batch.js +10 -0
  281. package/dist/core/storage/sqlite-open-batch.js.map +1 -0
  282. package/dist/core/storage/storage-status.code.js +1 -1
  283. package/dist/core/storage/storage-status.impl.js +3 -3
  284. package/dist/core/storage/storage-status.js +3 -3
  285. package/dist/core/storage/team.code.js +1 -1
  286. package/dist/core/storage/team.d.ts +26 -115
  287. package/dist/core/storage/team.impl.js +3 -3
  288. package/dist/core/storage/team.js +3 -3
  289. package/dist/core/structured-output/index.code.js +1 -1
  290. package/dist/core/structured-output/index.impl.js +3 -3
  291. package/dist/core/structured-output/index.js +3 -3
  292. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  293. package/dist/core/tasks/task-completion-entry.js +3 -3
  294. package/dist/core/tasks/task-file-history.code.js +3 -3
  295. package/dist/core/tasks/task-file-history.impl.js +3 -3
  296. package/dist/core/tasks/task-file-history.js +3 -3
  297. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  298. package/dist/core/tasks/task-reference-archive.js +3 -3
  299. package/dist/core/tasks/task-reference-identity.js +3 -3
  300. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  301. package/dist/core/tasks/task-reference-stream.js +3 -3
  302. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  303. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  304. package/dist/core/tasks/task-view-source.code.js +1 -1
  305. package/dist/core/tasks/task-view-source.impl.js +3 -3
  306. package/dist/core/tasks/task-view-source.js +3 -3
  307. package/dist/core/tools/history-tasks.d.ts +3 -2
  308. package/dist/core/tools/read-url.code.js +4 -4
  309. package/dist/core/tools/read-url.impl.js +3 -3
  310. package/dist/core/tools/read-url.js +3 -3
  311. package/dist/core/worktree-snapshot/blob-store.d.ts +44 -5
  312. package/dist/core/worktree-snapshot/blob-store.js +553 -30
  313. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  314. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  315. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  316. package/dist/core/worktree-snapshot/errors.js +3 -3
  317. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  318. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  319. package/dist/core/worktree-snapshot/fork-snapshot-index.js +208 -50
  320. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  321. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  322. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  323. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  325. package/dist/extensions/codemode/execute.code.js +1 -1
  326. package/dist/extensions/codemode/execute.impl.js +3 -3
  327. package/dist/extensions/codemode/execute.js +3 -3
  328. package/dist/extensions/codemode/renderer.code.js +2 -2
  329. package/dist/extensions/codemode/renderer.impl.js +3 -3
  330. package/dist/extensions/codemode/renderer.js +3 -3
  331. package/dist/extensions/mcp/cli.code.js +3 -3
  332. package/dist/extensions/mcp/cli.impl.js +3 -3
  333. package/dist/extensions/mcp/cli.js +3 -3
  334. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  335. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  336. package/dist/extensions/mcp/cli.lazy.js +3 -3
  337. package/dist/extensions/mcp/runtime.code.js +1 -1
  338. package/dist/extensions/mcp/runtime.impl.js +3 -3
  339. package/dist/extensions/mcp/runtime.js +3 -3
  340. package/dist/index.d.ts +3 -1
  341. package/dist/index.js +5 -5
  342. package/dist/main-first-time-setup.code.js +1 -1
  343. package/dist/main-first-time-setup.impl.js +3 -3
  344. package/dist/main-first-time-setup.js +3 -3
  345. package/dist/main.js +1 -1
  346. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  347. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  348. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  349. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  350. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  351. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  352. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  353. package/dist/modes/print-mode.js +1 -1
  354. package/dist/package-manager-cli.code.js +6 -6
  355. package/dist/package-manager-cli.impl.js +3 -3
  356. package/dist/package-manager-cli.js +3 -3
  357. package/dist/rpc-entry.js +1 -1
  358. package/dist/startup-files.json +1 -1
  359. package/dist/startup-stages/10.js +1 -1
  360. package/dist/startup-stages/11.js +1 -1
  361. package/dist/startup-stages/12.js +1 -1
  362. package/dist/startup-stages/2.js +2 -4
  363. package/dist/startup-stages/3.js +1 -3
  364. package/dist/startup-stages/4.js +1 -2
  365. package/dist/startup-stages/5.js +1 -1
  366. package/dist/startup-stages/6.js +5 -7
  367. package/dist/startup-stages/7.js +3 -10
  368. package/dist/startup-stages/8.js +7 -2
  369. package/dist/startup-stages/9.js +1 -7
  370. package/dist/startup-stages/stages.json +1 -1
  371. package/dist/utils/compile-cache-deferral.js +8 -13
  372. package/dist/utils/compile-cache-deferral.js.map +1 -1
  373. package/dist/utils/compile-cache-warmup-host.js +3 -4
  374. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  375. package/dist/utils/compile-cache.js +12 -100
  376. package/dist/utils/compile-cache.js.map +1 -1
  377. package/dist/utils/startup-database-spare.code.js +2 -2
  378. package/dist/utils/startup-database-spare.impl.js +3 -3
  379. package/dist/utils/startup-database-spare.js +3 -3
  380. package/dist/utils/tools-manager.code.js +1 -1
  381. package/dist/utils/tools-manager.impl.js +3 -3
  382. package/dist/utils/tools-manager.js +3 -3
  383. package/dist/utils/worker-threads.js +2 -15
  384. package/dist/utils/worker-threads.js.map +1 -1
  385. package/docs/build.md +3 -3
  386. package/docs/changelog.mdx +1498 -69
  387. package/docs/compaction/reference.md +5 -5
  388. package/docs/compaction.md +7 -9
  389. package/docs/containerization.md +2 -2
  390. package/docs/custom-provider/api-reference.md +1 -1
  391. package/docs/docs.json +37 -10
  392. package/docs/environment-variables.md +0 -2
  393. package/docs/extensions/api-reference.md +4 -4
  394. package/docs/getting-started/installation.md +3 -0
  395. package/docs/guides/configuration.md +1 -1
  396. package/docs/guides/non-interactive.md +1 -1
  397. package/docs/guides/resume-on-any-machine.md +14 -22
  398. package/docs/guides/team-setup.md +56 -83
  399. package/docs/guides.md +2 -4
  400. package/docs/herdr.md +1 -1
  401. package/docs/index.md +1 -1
  402. package/docs/intercom/operations.md +26 -21
  403. package/docs/intercom/reference.md +2 -2
  404. package/docs/intercom.md +1 -1
  405. package/docs/libraries/storage-postgres.md +9 -9
  406. package/docs/libraries.md +2 -3
  407. package/docs/models-configuration.md +2 -2
  408. package/docs/models.md +2 -3
  409. package/docs/packages/authoring.md +7 -7
  410. package/docs/packages.md +1 -1
  411. package/docs/programmatic.md +2 -2
  412. package/docs/quickstart.md +1 -1
  413. package/docs/reference/cli.md +6 -11
  414. package/docs/reference.md +2 -2
  415. package/docs/rpc/extension-ui.md +2 -2
  416. package/docs/sdk/reference.md +5 -4
  417. package/docs/sdk/storage.md +8 -92
  418. package/docs/sdk/structured-decisions.md +1 -1
  419. package/docs/sdk/web-server.md +3 -3
  420. package/docs/sdk.md +14 -4
  421. package/docs/security.md +1 -1
  422. package/docs/session-format.md +5 -5
  423. package/docs/sessions.md +29 -49
  424. package/docs/settings.md +7 -8
  425. package/docs/storage/custom-adapters.md +255 -0
  426. package/docs/storage/jsonl.md +117 -0
  427. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +66 -68
  428. package/docs/storage/postgres/tuning.md +337 -0
  429. package/docs/storage/postgres.md +556 -0
  430. package/docs/storage/sqlite.md +99 -0
  431. package/docs/storage.md +326 -990
  432. package/docs/subagents/authoring.md +1 -1
  433. package/docs/subagents.md +2 -2
  434. package/docs/tools.md +1 -1
  435. package/docs/worktree-snapshots.md +2 -2
  436. package/package.json +9 -9
  437. package/schemas/models.schema.json +2 -2
  438. package/schemas/settings.schema.json +0 -14
  439. package/dist/_shared/p1b-elig-ENCUPKKJ.js.map +0 -1
  440. package/dist/_shared/sdk-IQMULKFU.js.map +0 -1
  441. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +0 -1
  442. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +0 -1
  443. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  444. package/dist/core/intercom-broker-control.d.ts +0 -129
  445. package/dist/startup-stages/13.js +0 -1
  446. package/docs/guides/postgres-tuning.md +0 -311
  447. package/docs/libraries/storage-libsql.md +0 -97
@@ -12,9 +12,46 @@ import { sqliteDialect } from "./dialect.js";
12
12
  const CONNECTION_SOURCE = `
13
13
  ${EVAL_WORKER_BUILTIN}
14
14
  const { parentPort, workerData } = builtin("node:worker_threads");
15
+ const fs = builtin("node:fs");
15
16
  process.emitWarning = () => {};
16
17
  const { DatabaseSync } = builtin("node:sqlite");
18
+ const { statSync } = fs;
17
19
  let database;
20
+ let walPath;
21
+ let lastWalSize = -1n;
22
+ let lastWalMtimeNs = -1n;
23
+ const WAL_SIZE_LIMIT_BYTES = BigInt(workerData.walSizeLimit);
24
+ const CHECKPOINT_AFTER = new Set(["exec", "run", "get", "all", "begin", "sequence"]);
25
+ let holderFd;
26
+ let holderActive = false;
27
+ let writersDir;
28
+ let lastFreed = false;
29
+ let lastHasWaiters;
30
+ let pendingHolderError;
31
+ const HOLDER_FREE = "free " + "0".repeat(15) + "\\n";
32
+
33
+ function hasWriters(dir) {
34
+ if (!fs.existsSync(dir)) return false;
35
+ try {
36
+ return fs.readdirSync(dir).length > 0;
37
+ } catch (error) {
38
+ return error?.code !== "ENOENT";
39
+ }
40
+ }
41
+
42
+ function writeHolder(record) {
43
+ if (holderFd === undefined) return;
44
+ try {
45
+ fs.writeSync(holderFd, record, 0, "utf8");
46
+ } catch (error) {
47
+ holderFd = undefined;
48
+ pendingHolderError ??= failure(error);
49
+ }
50
+ }
51
+
52
+ function holderLine(prefix) {
53
+ return prefix + " " + String(Date.now()).padStart(15, "0") + "\\n";
54
+ }
18
55
 
19
56
  const STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];
20
57
  // Bun stamps every error with where it was thrown; the caller's copy gets its own.
@@ -75,11 +112,6 @@ function statement(sql) {
75
112
  return made;
76
113
  }
77
114
 
78
- // Node 22 binds an empty Uint8Array that arrived in a message as NULL; a new empty one binds as a zero-length blob.
79
- function bind(params) {
80
- return params.map((value) => (value instanceof Uint8Array && value.byteLength === 0 ? new Uint8Array(0) : value));
81
- }
82
-
83
115
  function value(each) {
84
116
  if (typeof each === "bigint") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;
85
117
  // A copy of its own: a view of a larger buffer would send the whole buffer.
@@ -96,17 +128,29 @@ function table(rows) {
96
128
  const handlers = {
97
129
  open: (request) => {
98
130
  database = new DatabaseSync(request.path, { readOnly: request.readOnly });
99
- return database.location();
131
+ const location = database.location();
132
+ if (!request.readOnly && typeof location === "string" && location.length > 0) {
133
+ walPath = location + "-wal";
134
+ lastWalSize = -1n;
135
+ lastWalMtimeNs = -1n;
136
+ database.exec(
137
+ "PRAGMA wal_autocheckpoint=" +
138
+ workerData.walAutoCheckpoint +
139
+ "; PRAGMA journal_size_limit=" +
140
+ workerData.walSizeLimit,
141
+ );
142
+ }
143
+ return location;
100
144
  },
101
145
  exec: (request) => {
102
146
  database.exec(request.sql);
103
147
  },
104
- run: (request) => ({ changes: Number(statement(request.sql).run(...bind(request.params)).changes) }),
148
+ run: (request) => ({ changes: Number(statement(request.sql).run(...request.params).changes) }),
105
149
  get: (request) => {
106
- const row = statement(request.sql).get(...bind(request.params));
150
+ const row = statement(request.sql).get(...request.params);
107
151
  return row === undefined ? undefined : table([row]);
108
152
  },
109
- all: (request) => table(statement(request.sql).all(...bind(request.params))),
153
+ all: (request) => table(statement(request.sql).all(...request.params)),
110
154
  // A read transaction's start: BEGIN, then its leading reads, in one request. A BEGIN that fails fails the request and
111
155
  // leaves no transaction. The reads answer up to the first that fails, which, with the ones after it, the caller then
112
156
  // sends on its own in the same transaction, so it fails or answers there as it always would.
@@ -115,7 +159,7 @@ const handlers = {
115
159
  const answers = [];
116
160
  for (const { sql, params } of request.statements) {
117
161
  try {
118
- answers.push(table(statement(sql).all(...bind(params))));
162
+ answers.push(table(statement(sql).all(...params)));
119
163
  } catch {
120
164
  break;
121
165
  }
@@ -134,8 +178,18 @@ const handlers = {
134
178
  throw error;
135
179
  }
136
180
  },
137
- // One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.
181
+ // One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering, then the transaction's
182
+ // leading statements, if any, in the same request. When writersDir and checkQueue are given, checks the
183
+ // writers' queue directory first and returns { contended: true } without taking the lock if entries are present
184
+ // (or the directory cannot be listed). When holderFd is given, writes the connection's holder record in place
185
+ // around taking and releasing the lock.
138
186
  begin: (request) => {
187
+ if (request.writersDir !== undefined) writersDir = request.writersDir;
188
+ if ("holderFd" in request) holderFd = request.holderFd;
189
+ if (request.checkQueue === true && writersDir !== undefined && hasWriters(writersDir)) {
190
+ return { contended: true };
191
+ }
192
+ writeHolder(holderLine("want"));
139
193
  // The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a
140
194
  // statement the calling thread runs meanwhile; settleLock gives it back once the transaction ended.
141
195
  if (request.lockState !== undefined) {
@@ -157,6 +211,7 @@ const handlers = {
157
211
  try {
158
212
  database.exec("BEGIN IMMEDIATE");
159
213
  began = true;
214
+ holderActive = true;
160
215
  } finally {
161
216
  try {
162
217
  database.exec("PRAGMA busy_timeout=" + configured);
@@ -165,7 +220,11 @@ const handlers = {
165
220
  throw restoreFailure;
166
221
  }
167
222
  }
223
+ const result = request.statements === undefined ? undefined : lead(request.statements);
224
+ if (inTransaction()) writeHolder(holderLine("held"));
225
+ return result;
168
226
  },
227
+ lead: (request) => lead(request.statements),
169
228
  // \`repeat\`, then each statement, in one request: the statements the caller would send one at a time, in the same
170
229
  // order, each prepared when it is reached. The caller's abort flag is read where the caller would check its signal.
171
230
  sequence: (request) => {
@@ -177,7 +236,7 @@ const handlers = {
177
236
  while (repeated < times) {
178
237
  if (aborted()) return { aborted: true };
179
238
  const before = Number(statement("SELECT total_changes() AS changes").get().changes);
180
- statement(repeat.sql).run(...bind(repeat.params));
239
+ statement(repeat.sql).run(...repeat.params);
181
240
  const after = Number(statement("SELECT total_changes() AS changes").get().changes);
182
241
  if (after - before < minChanges) break;
183
242
  repeated++;
@@ -186,7 +245,7 @@ const handlers = {
186
245
  for (const { sql, params, script } of request.statements) {
187
246
  if (aborted()) return { aborted: true };
188
247
  if (script === true) database.exec(sql);
189
- else statement(sql).run(...bind(params));
248
+ else statement(sql).run(...params);
190
249
  }
191
250
  return { repeated };
192
251
  },
@@ -203,29 +262,65 @@ const handlers = {
203
262
  },
204
263
  close: () => {
205
264
  prepared.clear();
265
+ walPath = undefined;
206
266
  database?.close();
267
+ database = undefined;
207
268
  globalThis.Bun?.gc?.(true);
208
269
  },
209
270
  };
210
271
 
272
+ // A write transaction's leading statements, run in order once BEGIN IMMEDIATE took the lock: each answers with its rows
273
+ // and the rows it changed, as all and run would, up to the first that fails; nothing after it runs. The answer says
274
+ // whether the transaction is still open after that failure: SQLite rolls back only the statement for most failures, and
275
+ // the whole transaction for a few (a full disk, an I/O error). A script answers nothing.
276
+ function lead(statements) {
277
+ const answers = [];
278
+ for (const { sql, params, script } of statements) {
279
+ try {
280
+ if (script === true) {
281
+ database.exec(sql);
282
+ answers.push({ columns: [], values: [], changes: 0 });
283
+ continue;
284
+ }
285
+ const rows = table(statement(sql).all(...params));
286
+ answers.push({ ...rows, changes: Number(statement("SELECT changes() AS changes").get().changes) });
287
+ } catch (error) {
288
+ return { answers, failure: failure(error), open: database.isTransaction === true };
289
+ }
290
+ }
291
+ return { answers };
292
+ }
293
+
211
294
  // The file's lock word while this connection takes or holds the lock: held while a transaction is open on it, given
212
295
  // back (and the waiting threads woken) once none is, before the request that ended it is answered.
213
296
  let lockState;
214
297
 
215
- function settleLock() {
216
- if (lockState === undefined) return;
217
- const { state, held } = lockState;
218
- let open = false;
298
+ function inTransaction() {
219
299
  try {
220
- open = database?.isTransaction === true;
221
- } catch {}
222
- if (open) {
223
- if (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);
224
- return;
300
+ return database?.isTransaction === true;
301
+ } catch {
302
+ return false;
303
+ }
304
+ }
305
+
306
+ function settleLock() {
307
+ const open = inTransaction();
308
+ if (lockState !== undefined) {
309
+ const { state, held } = lockState;
310
+ if (open) {
311
+ if (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);
312
+ } else {
313
+ lockState = undefined;
314
+ if (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)
315
+ Atomics.notify(state, 0);
316
+ }
317
+ }
318
+ if (holderActive && !open) {
319
+ holderActive = false;
320
+ writeHolder(HOLDER_FREE);
321
+ lastFreed = true;
322
+ lastHasWaiters = writersDir !== undefined && fs.existsSync(writersDir);
225
323
  }
226
- lockState = undefined;
227
- if (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)
228
- Atomics.notify(state, 0);
229
324
  }
230
325
 
231
326
  function handle(request) {
@@ -236,12 +331,49 @@ function handle(request) {
236
331
  }
237
332
  }
238
333
 
334
+ function maybeCheckpoint(kind) {
335
+ if (walPath === undefined || database === undefined || !CHECKPOINT_AFTER.has(kind)) return;
336
+ try {
337
+ if (database.isTransaction !== false) return;
338
+ const stat = statSync(walPath, { bigint: true, throwIfNoEntry: false });
339
+ if (stat === undefined) {
340
+ lastWalSize = -1n;
341
+ lastWalMtimeNs = -1n;
342
+ return;
343
+ }
344
+ if (stat.size <= WAL_SIZE_LIMIT_BYTES) {
345
+ lastWalSize = stat.size;
346
+ lastWalMtimeNs = stat.mtimeNs;
347
+ return;
348
+ }
349
+ if (stat.size === lastWalSize && stat.mtimeNs === lastWalMtimeNs) return;
350
+ lastWalSize = stat.size;
351
+ lastWalMtimeNs = stat.mtimeNs;
352
+ database.exec("PRAGMA wal_checkpoint(PASSIVE)");
353
+ } catch {}
354
+ }
355
+
239
356
  parentPort.on("message", (request) => {
357
+ let answered = false;
358
+ lastFreed = false;
359
+ lastHasWaiters = undefined;
360
+ pendingHolderError = undefined;
240
361
  try {
241
- parentPort.postMessage({ id: request.id, value: handle(request) });
362
+ const value = handle(request);
363
+ const reply = { id: request.id, value, tx: inTransaction() };
364
+ if (lastFreed) reply.freed = true;
365
+ if (lastHasWaiters !== undefined) reply.hasWaiters = lastHasWaiters;
366
+ if (pendingHolderError !== undefined) reply.holderError = pendingHolderError;
367
+ parentPort.postMessage(reply);
368
+ answered = true;
242
369
  } catch (error) {
243
- parentPort.postMessage({ id: request.id, failure: failure(error) });
370
+ const reply = { id: request.id, failure: failure(error), tx: inTransaction() };
371
+ if (lastFreed) reply.freed = true;
372
+ if (lastHasWaiters !== undefined) reply.hasWaiters = lastHasWaiters;
373
+ if (pendingHolderError !== undefined) reply.holderError = pendingHolderError;
374
+ parentPort.postMessage(reply);
244
375
  }
376
+ if (answered) maybeCheckpoint(request.kind);
245
377
  });
246
378
  `;
247
379
  const STANDARD_ERRORS = {
@@ -315,13 +447,41 @@ const WORKER_CODE_OPTIONS = new Set(["--require", "-r", "--import", "--loader",
315
447
  let spare;
316
448
  /** How many prepared statements a connection keeps for reuse, least recently used first out. */
317
449
  export const STATEMENT_CACHE_SIZE = 256;
450
+ /** Safety-net automatic WAL checkpoint threshold in pages on writable file connections. */
451
+ const WAL_AUTO_CHECKPOINT = 10_000;
452
+ /** Target write-ahead log size limit in bytes (4 MiB) for journal truncation and post-response checkpoints. */
453
+ const WAL_SIZE_LIMIT = 4 * 1024 * 1024;
318
454
  /** A node:sqlite connection running on its own worker thread. */
319
455
  export class ThreadConnection {
320
456
  worker;
321
457
  waiting = new Map();
322
458
  nextId = 1;
459
+ _inTransaction;
460
+ _lastFreed = false;
461
+ _lastHasWaiters;
462
+ _holderError;
323
463
  ended;
324
464
  closing;
465
+ /** Whether SQLite had an open transaction after the thread's last answer; undefined for older connection threads. */
466
+ get inTransaction() {
467
+ return this._inTransaction;
468
+ }
469
+ /** Consumes any connection-thread holder-record write failure reported since the last check. */
470
+ takeHolderError() {
471
+ const error = this._holderError;
472
+ this._holderError = undefined;
473
+ return error;
474
+ }
475
+ /**
476
+ * Consumes the release metadata reported by the connection thread when the transaction ended: whether the thread
477
+ * already wrote the `"free"` holder record, and whether the writers'-queue directory existed.
478
+ */
479
+ takeReleaseState() {
480
+ const state = { freed: this._lastFreed, hasWaiters: this._lastHasWaiters };
481
+ this._lastFreed = false;
482
+ this._lastHasWaiters = undefined;
483
+ return state;
484
+ }
325
485
  constructor() {
326
486
  // None of the process's own flags: the caller's preloads would run again for every connection, and its
327
487
  // `--input-type=module` would make this source a module. Whether node:sqlite is available was settled by the
@@ -329,7 +489,12 @@ export class ThreadConnection {
329
489
  this.worker = new Worker(CONNECTION_SOURCE, {
330
490
  eval: true,
331
491
  execArgv: [],
332
- workerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now`, statementCacheSize: STATEMENT_CACHE_SIZE },
492
+ workerData: {
493
+ nowSql: `SELECT ${sqliteDialect.nowMs} AS now`,
494
+ statementCacheSize: STATEMENT_CACHE_SIZE,
495
+ walAutoCheckpoint: WAL_AUTO_CHECKPOINT,
496
+ walSizeLimit: WAL_SIZE_LIMIT,
497
+ },
333
498
  });
334
499
  this.worker.on("message", (reply) => this.receive(reply));
335
500
  this.worker.on("error", (error) => this.end(error));
@@ -410,6 +575,18 @@ export class ThreadConnection {
410
575
  return answer.then((value) => rowsOf(value));
411
576
  if (request.kind === "read")
412
577
  return answer.then((value) => value.map(rowsOf));
578
+ if (request.kind === "lead" || (request.kind === "begin" && request.statements !== undefined))
579
+ return answer.then((value) => {
580
+ if (value === undefined)
581
+ return undefined;
582
+ if (typeof value === "object" && value !== null && "contended" in value)
583
+ return value;
584
+ const { answers, failure, open } = value;
585
+ return {
586
+ answers: answers.map((each) => ({ rows: rowsOf(each), changes: each.changes })),
587
+ ...(failure === undefined ? {} : { failure: connectionError(failure), open: open === true }),
588
+ };
589
+ });
413
590
  return answer;
414
591
  }
415
592
  send(request) {
@@ -450,6 +627,14 @@ export class ThreadConnection {
450
627
  return this.closing;
451
628
  }
452
629
  receive(reply) {
630
+ if (typeof reply.tx === "boolean")
631
+ this._inTransaction = reply.tx;
632
+ if (reply.freed === true) {
633
+ this._lastFreed = true;
634
+ this._lastHasWaiters = reply.hasWaiters;
635
+ }
636
+ if (reply.holderError !== undefined)
637
+ this._holderError ??= connectionError(reply.holderError);
453
638
  const waiter = this.waiting.get(reply.id);
454
639
  if (waiter === undefined)
455
640
  return;
@@ -501,7 +686,7 @@ function __atomicOnDemandFailed(error, feature) {
501
686
  return (async () => {
502
687
  const root = new URL("../../", import.meta.url);
503
688
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
504
- const key = `${root.href}#0.10.11-alpha.2`;
689
+ const key = `${root.href}#0.10.11`;
505
690
  let release = releases.get(key);
506
691
  if (release === undefined) {
507
692
  const current = (async () => {
@@ -529,7 +714,7 @@ function __atomicOnDemandFailed(error, feature) {
529
714
  } catch {
530
715
  // No installation to read, as in a bundle of the package: the release the process runs decides.
531
716
  }
532
- const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.2" ? installed : running !== undefined && running.version !== "0.10.11-alpha.2" ? "0.10.11-alpha.2" : undefined;
717
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11" ? installed : running !== undefined && running.version !== "0.10.11" ? "0.10.11" : undefined;
533
718
  if (updatedTo === undefined) throw error;
534
719
  const application = typeof running?.name === "string" ? running.name : "atomic";
535
720
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {
@@ -1 +1 @@
1
- {"version":3,"file":"node-sqlite-thread.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-thread.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG7C;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG;EACxB,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyOpB,CAAC;AA4FF,MAAM,eAAe,GAA+C;IACnE,KAAK;IACL,SAAS;IACT,UAAU;IACV,WAAW;IACX,cAAc;IACd,SAAS;IACT,QAAQ;CACR,CAAC;AAEF,2FAA2F;AAC3F,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAkB,CAAC;AAEpD,kHA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,QAAyE,EACzE,eAA8B;QAE9B,MAAM,EAAE,8BAA8B,EAAE,GAAG,MAAM,MAAM,CAAC,uCAAuC,CAAC,CAAC;QACjG,IAAI,eAAe,EAAE,IAAI,8BAA8B,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;YAChF,gBAAgB,CAAC,UAAU,EAAE,CAAC;QAC/B,CAAC;IACF,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { startupNodeOptions } from \"@bastani/atomic-codemode/node-options\";\nimport { EVAL_WORKER_BUILTIN } from \"../../utils/worker-threads.js\";\nimport type { SqliteRow, SqliteStatement, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport type { SequencedStatement, SqliteSequence } from \"./statement-sequence.js\";\n\n/**\n * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the\n * calling thread sends it one request at a time and receives each answer as a message, so no statement, lock wait or\n * synced commit runs on the caller's event loop. SQLite's busy handler waits on the connection's own thread, so a\n * statement waiting for a lock that another connection of the same process holds never stops that connection from\n * finishing.\n */\nconst CONNECTION_SOURCE = `\n${EVAL_WORKER_BUILTIN}\nconst { parentPort, workerData } = builtin(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = builtin(\"node:sqlite\");\nlet database;\n\nconst STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];\n// Bun stamps every error with where it was thrown; the caller's copy gets its own.\nconst LOCATION_FIELDS = new Set([\"stack\", \"message\", \"line\", \"column\", \"originalLine\", \"originalColumn\", \"sourceURL\"]);\n\n// An object's own fields that hold plain values, with their enumerability.\nfunction fieldsOf(object, skip) {\n\tconst fields = [];\n\tfor (const key of Object.getOwnPropertyNames(object)) {\n\t\tif (skip.has(key)) continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\t\tconst value = descriptor?.value;\n\t\tif (value === null || (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\" && typeof value !== \"bigint\")) continue;\n\t\tfields.push([key, value, descriptor.enumerable === true]);\n\t}\n\treturn fields;\n}\n\n// A thrown error as it crosses to the caller: the standard constructor it descends from, its message, and its own\n// fields with their enumerability. A runtime's error class of its own between the error and that constructor (Bun's\n// node:sqlite errors have one holding name, code and toString) is described by its fields and whether it has a\n// toString of its own, and how it shows.\nfunction failure(error) {\n\tif (!(error instanceof Error)) return { constructor: \"Error\", message: String(error), fields: [] };\n\tlet standard = Object.getPrototypeOf(error);\n\tlet between;\n\twhile (standard !== null && !STANDARD_ERRORS.some((each) => each.prototype === standard)) {\n\t\tif (between === undefined) {\n\t\t\tconst toString = Object.getOwnPropertyDescriptor(standard, \"toString\");\n\t\t\tbetween = {\n\t\t\t\tfields: fieldsOf(standard, new Set([\"constructor\", \"message\"])),\n\t\t\t\t...(typeof toString?.value === \"function\" ? { toString: { enumerable: toString.enumerable === true } } : {}),\n\t\t\t};\n\t\t}\n\t\tstandard = Object.getPrototypeOf(standard);\n\t}\n\treturn {\n\t\tconstructor: standard === null ? \"Error\" : standard.constructor.name,\n\t\tmessage: String(error.message),\n\t\tfields: fieldsOf(error, LOCATION_FIELDS),\n\t\t...(between === undefined ? {} : { between }),\n\t};\n}\n\nconst prepared = new Map();\n\nfunction statement(sql) {\n\tconst cached = prepared.get(sql);\n\tif (cached !== undefined) {\n\t\tprepared.delete(sql);\n\t\tprepared.set(sql, cached);\n\t\treturn cached;\n\t}\n\tconst made = database.prepare(sql);\n\tmade.setReadBigInts(true);\n\tprepared.set(sql, made);\n\tif (prepared.size > workerData.statementCacheSize) prepared.delete(prepared.keys().next().value);\n\treturn made;\n}\n\n// Node 22 binds an empty Uint8Array that arrived in a message as NULL; a new empty one binds as a zero-length blob.\nfunction bind(params) {\n\treturn params.map((value) => (value instanceof Uint8Array && value.byteLength === 0 ? new Uint8Array(0) : value));\n}\n\nfunction value(each) {\n\tif (typeof each === \"bigint\") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;\n\t// A copy of its own: a view of a larger buffer would send the whole buffer.\n\treturn each instanceof Uint8Array ? new Uint8Array(each) : each;\n}\n\n// Rows cross as their column names and one array of values each, in the order the driver gives a row's fields.\nfunction table(rows) {\n\tif (rows.length === 0) return { columns: [], values: [] };\n\tconst columns = Object.keys(rows[0]);\n\treturn { columns, values: rows.map((row) => columns.map((column) => value(row[column]))) };\n}\n\nconst handlers = {\n\topen: (request) => {\n\t\tdatabase = new DatabaseSync(request.path, { readOnly: request.readOnly });\n\t\treturn database.location();\n\t},\n\texec: (request) => {\n\t\tdatabase.exec(request.sql);\n\t},\n\trun: (request) => ({ changes: Number(statement(request.sql).run(...bind(request.params)).changes) }),\n\tget: (request) => {\n\t\tconst row = statement(request.sql).get(...bind(request.params));\n\t\treturn row === undefined ? undefined : table([row]);\n\t},\n\tall: (request) => table(statement(request.sql).all(...bind(request.params))),\n\t// A read transaction's start: BEGIN, then its leading reads, in one request. A BEGIN that fails fails the request and\n\t// leaves no transaction. The reads answer up to the first that fails, which, with the ones after it, the caller then\n\t// sends on its own in the same transaction, so it fails or answers there as it always would.\n\tread: (request) => {\n\t\tdatabase.exec(\"BEGIN\");\n\t\tconst answers = [];\n\t\tfor (const { sql, params } of request.statements) {\n\t\t\ttry {\n\t\t\t\tanswers.push(table(statement(sql).all(...bind(params))));\n\t\t\t} catch {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn answers;\n\t},\n\t// A read transaction's end, which its caller does not wait for: COMMIT, or ROLLBACK where COMMIT fails, so the\n\t// connection is never left inside it.\n\tendRead: () => {\n\t\ttry {\n\t\t\tdatabase.exec(\"COMMIT\");\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\t} catch {}\n\t\t\tthrow error;\n\t\t}\n\t},\n\t// One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.\n\tbegin: (request) => {\n\t\t// The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a\n\t\t// statement the calling thread runs meanwhile; settleLock gives it back once the transaction ended.\n\t\tif (request.lockState !== undefined) {\n\t\t\tconst state = new Int32Array(request.lockState);\n\t\t\tfor (;;) {\n\t\t\t\tconst found = Atomics.compareExchange(state, 0, 0, request.lockTag * 4 + 2);\n\t\t\t\tif (found === 0) break;\n\t\t\t\t// Anything but a statement of the calling thread (1) is another holder: a lock taken, as BEGIN would find.\n\t\t\t\tif (found !== 1)\n\t\t\t\t\tthrow Object.assign(new Error(\"database is locked\"), { code: \"ERR_SQLITE_ERROR\", errcode: 5, errstr: \"database is locked\" });\n\t\t\t\tAtomics.wait(state, 0, 1, 50);\n\t\t\t}\n\t\t\tAtomics.notify(state, 0);\n\t\t\tlockState = { state, held: request.lockTag * 4 + 3 };\n\t\t}\n\t\tconst configured = Number(database.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\tdatabase.exec(\"PRAGMA busy_timeout=0\");\n\t\tlet began = false;\n\t\ttry {\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\tbegan = true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"PRAGMA busy_timeout=\" + configured);\n\t\t\t} catch (restoreFailure) {\n\t\t\t\tif (began) database.exec(\"ROLLBACK\");\n\t\t\t\tthrow restoreFailure;\n\t\t\t}\n\t\t}\n\t},\n\t// \\`repeat\\`, then each statement, in one request: the statements the caller would send one at a time, in the same\n\t// order, each prepared when it is reached. The caller's abort flag is read where the caller would check its signal.\n\tsequence: (request) => {\n\t\tconst abort = request.abort === undefined ? undefined : new Int32Array(request.abort);\n\t\tconst aborted = () => abort !== undefined && Atomics.load(abort, 0) !== 0;\n\t\tlet repeated = 0;\n\t\tif (request.repeat !== undefined) {\n\t\t\tconst { statement: repeat, times, minChanges } = request.repeat;\n\t\t\twhile (repeated < times) {\n\t\t\t\tif (aborted()) return { aborted: true };\n\t\t\t\tconst before = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tstatement(repeat.sql).run(...bind(repeat.params));\n\t\t\t\tconst after = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tif (after - before < minChanges) break;\n\t\t\t\trepeated++;\n\t\t\t}\n\t\t}\n\t\tfor (const { sql, params, script } of request.statements) {\n\t\t\tif (aborted()) return { aborted: true };\n\t\t\tif (script === true) database.exec(sql);\n\t\t\telse statement(sql).run(...bind(params));\n\t\t}\n\t\treturn { repeated };\n\t},\n\tdataVersion: () => Number(database.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0),\n\tnow: () => Number(database.prepare(workerData.nowSql).get().now),\n\tjsonbExtract: () => {\n\t\ttry {\n\t\t\tstatement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\tthrow error;\n\t\t}\n\t},\n\tclose: () => {\n\t\tprepared.clear();\n\t\tdatabase?.close();\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\n// The file's lock word while this connection takes or holds the lock: held while a transaction is open on it, given\n// back (and the waiting threads woken) once none is, before the request that ended it is answered.\nlet lockState;\n\nfunction settleLock() {\n\tif (lockState === undefined) return;\n\tconst { state, held } = lockState;\n\tlet open = false;\n\ttry {\n\t\topen = database?.isTransaction === true;\n\t} catch {}\n\tif (open) {\n\t\tif (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);\n\t\treturn;\n\t}\n\tlockState = undefined;\n\tif (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)\n\t\tAtomics.notify(state, 0);\n}\n\nfunction handle(request) {\n\ttry {\n\t\treturn handlers[request.kind](request);\n\t} finally {\n\t\tsettleLock();\n\t}\n}\n\nparentPort.on(\"message\", (request) => {\n\ttry {\n\t\tparentPort.postMessage({ id: request.id, value: handle(request) });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: request.id, failure: failure(error) });\n\t}\n});\n`;\n\n/**\n * Statements sent as one request (see `SqliteSequence`). `abort` holds one `Int32` the caller sets to non-zero when its\n * signal aborts: the thread reads it before each run of `repeat` and before each statement.\n */\nexport interface SequenceRequest {\n\treadonly kind: \"sequence\";\n\treadonly repeat?: SqliteSequence[\"repeat\"];\n\treadonly statements: readonly SequencedStatement[];\n\treadonly abort?: SharedArrayBuffer;\n}\n\n/**\n * What a sequence request is answered with: how many runs of `repeat` changed `minChanges` rows or more, or that it\n * stopped because the caller's signal aborted.\n */\nexport type SequenceAnswer = { readonly repeated: number } | { readonly aborted: true };\n\n/** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */\nexport type ConnectionRequest =\n\t| { readonly kind: \"open\"; readonly path: string; readonly readOnly: boolean }\n\t| { readonly kind: \"exec\"; readonly sql: string }\n\t| { readonly kind: \"run\" | \"get\" | \"all\"; readonly sql: string; readonly params: readonly SqliteValue[] }\n\t| { readonly kind: \"begin\"; readonly lockState?: SharedArrayBuffer; readonly lockTag?: number }\n\t| { readonly kind: \"dataVersion\" | \"now\" | \"jsonbExtract\" | \"close\" }\n\t| ReadTransactionRequest\n\t| SequenceRequest;\n\n/**\n * A read-only transaction's start with its leading reads, and its end, which only a connection on a thread of its own\n * is sent: see the thread's `read` and `endRead`.\n */\nexport type ReadTransactionRequest =\n\t| { readonly kind: \"read\"; readonly statements: readonly SqliteStatement[] }\n\t| { readonly kind: \"endRead\" };\n\n/** Rows as they cross from a connection's thread: the column names, then each row's values in their order. */\ninterface RowTable {\n\treadonly columns: readonly string[];\n\treadonly values: readonly (readonly SqliteValue[])[];\n}\n\n/** What a request's answer carries as it crosses, before rows are rebuilt. */\ntype ConnectionValue =\n\t| RowTable\n\t| readonly RowTable[]\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/**\n * What a request is answered with: `get` a row or undefined, `all` rows, `read` the rows of each leading read up to\n * the first that failed, `run` the changes, `sequence` a `SequenceAnswer`, `open` the location, `dataVersion` and `now`\n * a number, `jsonbExtract` a boolean, the others undefined.\n */\nexport type ConnectionAnswer =\n\t| SqliteRow\n\t| SqliteRow[]\n\t| SqliteRow[][]\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/** An own field that holds a plain value: its key, value and enumerability. */\ntype ConnectionField = readonly [string, string | number | boolean | bigint, boolean];\n\n/** A failure as it crosses from a connection's thread; see `failure` in the thread's source. */\ninterface ConnectionFailure {\n\treadonly constructor: string;\n\treadonly message: string;\n\treadonly fields: readonly ConnectionField[];\n\treadonly between?: {\n\t\treadonly fields: readonly ConnectionField[];\n\t\treadonly toString?: { readonly enumerable: boolean };\n\t};\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: ConnectionValue;\n\treadonly failure?: ConnectionFailure;\n}\n\nconst STANDARD_ERRORS: Readonly<Record<string, ErrorConstructor>> = {\n\tError,\n\tTypeError,\n\tRangeError,\n\tSyntaxError,\n\tReferenceError,\n\tEvalError,\n\tURIError,\n};\n\n/** One prototype per runtime error class seen, by what it holds: see `connectionError`. */\nconst betweenPrototypes = new Map<string, object>();\n\n/** How a runtime's error class of its own shows an error, as Bun's do: `TypeError [ERR_INVALID_ARG_VALUE]: …`. */\nfunction showWithCode(this: Error & { readonly code?: unknown }): string {\n\treturn `${this.name} [${String(this.code)}]: ${this.message}`;\n}\n\nfunction betweenPrototype(base: ErrorConstructor, between: NonNullable<ConnectionFailure[\"between\"]>): object {\n\tconst key = JSON.stringify([\n\t\tbase.name,\n\t\tbetween.fields.map(([field, value, enumerable]) => [field, String(value), enumerable]),\n\t\tbetween.toString,\n\t]);\n\tlet prototype = betweenPrototypes.get(key);\n\tif (prototype === undefined) {\n\t\tconst created: object = Object.create(base.prototype);\n\t\tfor (const [field, value, enumerable] of between.fields)\n\t\t\tObject.defineProperty(created, field, { value, enumerable, writable: true, configurable: true });\n\t\tif (between.toString !== undefined)\n\t\t\tObject.defineProperty(created, \"toString\", {\n\t\t\t\tvalue: showWithCode,\n\t\t\t\tenumerable: between.toString.enumerable,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\tbetweenPrototypes.set(key, created);\n\t\tprototype = created;\n\t}\n\treturn prototype;\n}\n\n/**\n * The driver's error, rebuilt on the calling thread as the driver threw it: an instance of the same standard error\n * class with the same message, and the same own fields (`code`, `errcode`, `errstr` for SQLite's errors) with the same\n * enumerability. A runtime's own error class between them is stood in for by a prototype that holds the same fields and\n * shows the error the same way.\n */\nfunction connectionError(failure: ConnectionFailure): Error {\n\tconst base = STANDARD_ERRORS[failure.constructor] ?? Error;\n\tconst error = new base(failure.message);\n\tif (failure.between !== undefined) Object.setPrototypeOf(error, betweenPrototype(base, failure.between));\n\tfor (const [key, value, enumerable] of failure.fields)\n\t\tObject.defineProperty(error, key, { value, enumerable, writable: true, configurable: true });\n\treturn error;\n}\n\n/** The rows of `table`, each a plain object built the way the calling-thread connection builds them. */\nfunction rowsOf(table: RowTable): SqliteRow[] {\n\tconst { columns, values } = table;\n\treturn values.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index] as SqliteValue])));\n}\n\ninterface Waiter {\n\treadonly resolve: (value: ConnectionValue) => void;\n\treadonly reject: (error: unknown) => void;\n}\n\n/** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */\nexport class ConnectionThreadEndedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ConnectionThreadEndedError\";\n\t}\n}\n\n/** Options that make every worker thread run code of the user's: a preload or a module loader. */\nconst WORKER_CODE_OPTIONS = new Set([\"--require\", \"-r\", \"--import\", \"--loader\", \"--experimental-loader\"]);\n\n/** The thread `startSpare` started for the next open, until an open takes it or `releaseSpare` ends it. */\nlet spare: ThreadConnection | undefined;\n\n/** How many prepared statements a connection keeps for reuse, least recently used first out. */\nexport const STATEMENT_CACHE_SIZE = 256;\n\n/** A node:sqlite connection running on its own worker thread. */\nexport class ThreadConnection {\n\tprivate readonly worker: Worker;\n\tprivate readonly waiting = new Map<number, Waiter>();\n\tprivate nextId = 1;\n\tprivate ended?: Error;\n\tprivate closing?: Promise<undefined>;\n\n\tprivate constructor() {\n\t\t// None of the process's own flags: the caller's preloads would run again for every connection, and its\n\t\t// `--input-type=module` would make this source a module. Whether node:sqlite is available was settled by the\n\t\t// open before it started the thread.\n\t\tthis.worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\texecArgv: [],\n\t\t\tworkerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now`, statementCacheSize: STATEMENT_CACHE_SIZE },\n\t\t});\n\t\tthis.worker.on(\"message\", (reply: ConnectionReply) => this.receive(reply));\n\t\tthis.worker.on(\"error\", (error: Error) => this.end(error));\n\t\tthis.worker.on(\"exit\", (code: number) =>\n\t\t\tthis.end(new ConnectionThreadEndedError(`SQLite connection thread exited with code ${code}`)),\n\t\t);\n\t}\n\n\t/**\n\t * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure\n\t * to start the thread or to open the database rejects with its cause; the thread is gone then.\n\t */\n\tstatic async open(\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined && started.ended === undefined) {\n\t\t\ttry {\n\t\t\t\treturn await ThreadConnection.openOn(started, path, options);\n\t\t\t} catch (error) {\n\t\t\t\t// The spare thread was lost before it answered: open on a thread of its own, as without one.\n\t\t\t\tif (error !== started.ended) throw error;\n\t\t\t}\n\t\t}\n\t\treturn ThreadConnection.openOn(new ThreadConnection(), path, options);\n\t}\n\n\t/**\n\t * Starts one connection thread now, for the next open to take, so that the thread's startup overlaps whatever the\n\t * process does until then (an interactive session loads its modules meanwhile). Idle, the thread keeps nothing\n\t * alive. Nothing starts when the process runs a preload or a module loader, which every worker thread runs again,\n\t * or runs under the permission model; a thread that cannot start leaves every open as it is without one.\n\t */\n\tstatic startSpare(): void {\n\t\tif (spare !== undefined || process.permission !== undefined) return;\n\t\tif (startupNodeOptions().some((option) => WORKER_CODE_OPTIONS.has(option.name))) return;\n\t\ttry {\n\t\t\tconst started = new ThreadConnection();\n\t\t\tstarted.worker.unref();\n\t\t\tspare = started;\n\t\t} catch {\n\t\t\t// Opens start their own threads.\n\t\t}\n\t}\n\n\t/** Ends the spare thread if no open has taken it. */\n\tstatic releaseSpare(): void {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined) void started.stop();\n\t}\n\n\tprivate static async openOn(\n\t\tconnection: ThreadConnection,\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\ttry {\n\t\t\tconst location = await connection.request({\n\t\t\t\tkind: \"open\",\n\t\t\t\tpath: options.openAs ?? path,\n\t\t\t\treadOnly: options.readOnly,\n\t\t\t});\n\t\t\treturn { connection, location: typeof location === \"string\" ? location : null };\n\t\t} catch (error) {\n\t\t\tawait connection.stop();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request\n\t * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the\n\t * calling thread would not.\n\t */\n\trequest(request: ConnectionRequest): Promise<ConnectionAnswer> {\n\t\tif (request.kind === \"close\") return this.close();\n\t\tconst answer = this.send(request);\n\t\tif (request.kind === \"get\")\n\t\t\treturn answer.then((value) => (value === undefined ? undefined : rowsOf(value as RowTable)[0]));\n\t\tif (request.kind === \"all\") return answer.then((value) => rowsOf(value as RowTable));\n\t\tif (request.kind === \"read\") return answer.then((value) => (value as readonly RowTable[]).map(rowsOf));\n\t\treturn answer as Promise<ConnectionAnswer>;\n\t}\n\n\tprivate send(request: ConnectionRequest): Promise<ConnectionValue> {\n\t\treturn new Promise<ConnectionValue>((resolve, reject) => {\n\t\t\tif (this.ended !== undefined) {\n\t\t\t\treject(this.ended);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.nextId++;\n\t\t\ttry {\n\t\t\t\tthis.worker.postMessage({ id, ...request });\n\t\t\t} catch (error) {\n\t\t\t\t// A value the thread cannot receive.\n\t\t\t\treject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tif (this.waiting.size === 1) this.worker.ref();\n\t\t});\n\t}\n\n\t/**\n\t * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A\n\t * thread already lost has nothing to close.\n\t */\n\tprivate close(): Promise<undefined> {\n\t\tthis.closing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tif (this.ended === undefined) await this.send({ kind: \"close\" });\n\t\t\t} finally {\n\t\t\t\tawait this.stop();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\treturn this.closing;\n\t}\n\n\tprivate receive(reply: ConnectionReply): void {\n\t\tconst waiter = this.waiting.get(reply.id);\n\t\tif (waiter === undefined) return;\n\t\tthis.waiting.delete(reply.id);\n\t\tif (this.waiting.size === 0) this.worker.unref();\n\t\tif (reply.failure === undefined) waiter.resolve(reply.value);\n\t\telse waiter.reject(connectionError(reply.failure));\n\t}\n\n\t/** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */\n\tprivate end(cause: Error): void {\n\t\tif (this.ended !== undefined) return;\n\t\t// Kept for as long as the connection is: an error's stack, until formatted, keeps the functions of the frames it\n\t\t// names, and so whatever they hold, such as a session that closed its store.\n\t\tvoid cause.stack;\n\t\tthis.ended = cause;\n\t\tconst waiting = [...this.waiting.values()];\n\t\tthis.waiting.clear();\n\t\tthis.worker.unref();\n\t\tfor (const waiter of waiting) waiter.reject(cause);\n\t}\n\n\tprivate async stop(): Promise<void> {\n\t\tthis.end(new ConnectionThreadEndedError(\"SQLite connection closed\"));\n\t\tawait this.worker.terminate();\n\t}\n\n\t/** Calls `listener` once the connection's thread has exited, whether closed or lost. */\n\tonExit(listener: () => void): void {\n\t\tthis.worker.once(\"exit\", listener);\n\t}\n\n\t/**\n\t * Starts a spare worker for a non-interactive or storage-overridden CLI\n\t * invocation only when the real CLI/storage resolvers select a SQLite store.\n\t */\n\tstatic async startSpareIfSqlNeeded(\n\t\targs: readonly string[],\n\t\tterminal: { readonly stdinIsTTY: boolean; readonly stdoutIsTTY: boolean },\n\t\tstillBeforeMain: () => boolean,\n\t): Promise<void> {\n\t\tconst { shouldStartSpareDatabaseThread } = await import(\"../../utils/startup-database-spare.ts\");\n\t\tif (stillBeforeMain() && shouldStartSpareDatabaseThread(args, false, terminal)) {\n\t\t\tThreadConnection.startSpare();\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"node-sqlite-thread.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-thread.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEpE,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG7C;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG;EACxB,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,IAAI,eAAe,EAAE,IAAI,8BAA8B,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;YAChF,gBAAgB,CAAC,UAAU,EAAE,CAAC;QAC/B,CAAC;IACF,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { startupNodeOptions } from \"@bastani/atomic-codemode/node-options\";\nimport { EVAL_WORKER_BUILTIN } from \"../../utils/worker-threads.js\";\nimport type { SqliteRow, SqliteStatement, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport type { SequencedStatement, SqliteSequence } from \"./statement-sequence.js\";\n\n/**\n * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the\n * calling thread sends it one request at a time and receives each answer as a message, so no statement, lock wait or\n * synced commit runs on the caller's event loop. SQLite's busy handler waits on the connection's own thread, so a\n * statement waiting for a lock that another connection of the same process holds never stops that connection from\n * finishing.\n */\nconst CONNECTION_SOURCE = `\n${EVAL_WORKER_BUILTIN}\nconst { parentPort, workerData } = builtin(\"node:worker_threads\");\nconst fs = builtin(\"node:fs\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = builtin(\"node:sqlite\");\nconst { statSync } = fs;\nlet database;\nlet walPath;\nlet lastWalSize = -1n;\nlet lastWalMtimeNs = -1n;\nconst WAL_SIZE_LIMIT_BYTES = BigInt(workerData.walSizeLimit);\nconst CHECKPOINT_AFTER = new Set([\"exec\", \"run\", \"get\", \"all\", \"begin\", \"sequence\"]);\nlet holderFd;\nlet holderActive = false;\nlet writersDir;\nlet lastFreed = false;\nlet lastHasWaiters;\nlet pendingHolderError;\nconst HOLDER_FREE = \"free \" + \"0\".repeat(15) + \"\\\\n\";\n\nfunction hasWriters(dir) {\n\tif (!fs.existsSync(dir)) return false;\n\ttry {\n\t\treturn fs.readdirSync(dir).length > 0;\n\t} catch (error) {\n\t\treturn error?.code !== \"ENOENT\";\n\t}\n}\n\nfunction writeHolder(record) {\n\tif (holderFd === undefined) return;\n\ttry {\n\t\tfs.writeSync(holderFd, record, 0, \"utf8\");\n\t} catch (error) {\n\t\tholderFd = undefined;\n\t\tpendingHolderError ??= failure(error);\n\t}\n}\n\nfunction holderLine(prefix) {\n\treturn prefix + \" \" + String(Date.now()).padStart(15, \"0\") + \"\\\\n\";\n}\n\nconst STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];\n// Bun stamps every error with where it was thrown; the caller's copy gets its own.\nconst LOCATION_FIELDS = new Set([\"stack\", \"message\", \"line\", \"column\", \"originalLine\", \"originalColumn\", \"sourceURL\"]);\n\n// An object's own fields that hold plain values, with their enumerability.\nfunction fieldsOf(object, skip) {\n\tconst fields = [];\n\tfor (const key of Object.getOwnPropertyNames(object)) {\n\t\tif (skip.has(key)) continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\t\tconst value = descriptor?.value;\n\t\tif (value === null || (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\" && typeof value !== \"bigint\")) continue;\n\t\tfields.push([key, value, descriptor.enumerable === true]);\n\t}\n\treturn fields;\n}\n\n// A thrown error as it crosses to the caller: the standard constructor it descends from, its message, and its own\n// fields with their enumerability. A runtime's error class of its own between the error and that constructor (Bun's\n// node:sqlite errors have one holding name, code and toString) is described by its fields and whether it has a\n// toString of its own, and how it shows.\nfunction failure(error) {\n\tif (!(error instanceof Error)) return { constructor: \"Error\", message: String(error), fields: [] };\n\tlet standard = Object.getPrototypeOf(error);\n\tlet between;\n\twhile (standard !== null && !STANDARD_ERRORS.some((each) => each.prototype === standard)) {\n\t\tif (between === undefined) {\n\t\t\tconst toString = Object.getOwnPropertyDescriptor(standard, \"toString\");\n\t\t\tbetween = {\n\t\t\t\tfields: fieldsOf(standard, new Set([\"constructor\", \"message\"])),\n\t\t\t\t...(typeof toString?.value === \"function\" ? { toString: { enumerable: toString.enumerable === true } } : {}),\n\t\t\t};\n\t\t}\n\t\tstandard = Object.getPrototypeOf(standard);\n\t}\n\treturn {\n\t\tconstructor: standard === null ? \"Error\" : standard.constructor.name,\n\t\tmessage: String(error.message),\n\t\tfields: fieldsOf(error, LOCATION_FIELDS),\n\t\t...(between === undefined ? {} : { between }),\n\t};\n}\n\nconst prepared = new Map();\n\nfunction statement(sql) {\n\tconst cached = prepared.get(sql);\n\tif (cached !== undefined) {\n\t\tprepared.delete(sql);\n\t\tprepared.set(sql, cached);\n\t\treturn cached;\n\t}\n\tconst made = database.prepare(sql);\n\tmade.setReadBigInts(true);\n\tprepared.set(sql, made);\n\tif (prepared.size > workerData.statementCacheSize) prepared.delete(prepared.keys().next().value);\n\treturn made;\n}\n\nfunction value(each) {\n\tif (typeof each === \"bigint\") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;\n\t// A copy of its own: a view of a larger buffer would send the whole buffer.\n\treturn each instanceof Uint8Array ? new Uint8Array(each) : each;\n}\n\n// Rows cross as their column names and one array of values each, in the order the driver gives a row's fields.\nfunction table(rows) {\n\tif (rows.length === 0) return { columns: [], values: [] };\n\tconst columns = Object.keys(rows[0]);\n\treturn { columns, values: rows.map((row) => columns.map((column) => value(row[column]))) };\n}\n\nconst handlers = {\n\topen: (request) => {\n\t\tdatabase = new DatabaseSync(request.path, { readOnly: request.readOnly });\n\t\tconst location = database.location();\n\t\tif (!request.readOnly && typeof location === \"string\" && location.length > 0) {\n\t\t\twalPath = location + \"-wal\";\n\t\t\tlastWalSize = -1n;\n\t\t\tlastWalMtimeNs = -1n;\n\t\t\tdatabase.exec(\n\t\t\t\t\"PRAGMA wal_autocheckpoint=\" +\n\t\t\t\t\tworkerData.walAutoCheckpoint +\n\t\t\t\t\t\"; PRAGMA journal_size_limit=\" +\n\t\t\t\t\tworkerData.walSizeLimit,\n\t\t\t);\n\t\t}\n\t\treturn location;\n\t},\n\texec: (request) => {\n\t\tdatabase.exec(request.sql);\n\t},\n\trun: (request) => ({ changes: Number(statement(request.sql).run(...request.params).changes) }),\n\tget: (request) => {\n\t\tconst row = statement(request.sql).get(...request.params);\n\t\treturn row === undefined ? undefined : table([row]);\n\t},\n\tall: (request) => table(statement(request.sql).all(...request.params)),\n\t// A read transaction's start: BEGIN, then its leading reads, in one request. A BEGIN that fails fails the request and\n\t// leaves no transaction. The reads answer up to the first that fails, which, with the ones after it, the caller then\n\t// sends on its own in the same transaction, so it fails or answers there as it always would.\n\tread: (request) => {\n\t\tdatabase.exec(\"BEGIN\");\n\t\tconst answers = [];\n\t\tfor (const { sql, params } of request.statements) {\n\t\t\ttry {\n\t\t\t\tanswers.push(table(statement(sql).all(...params)));\n\t\t\t} catch {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn answers;\n\t},\n\t// A read transaction's end, which its caller does not wait for: COMMIT, or ROLLBACK where COMMIT fails, so the\n\t// connection is never left inside it.\n\tendRead: () => {\n\t\ttry {\n\t\t\tdatabase.exec(\"COMMIT\");\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\t} catch {}\n\t\t\tthrow error;\n\t\t}\n\t},\n\t// One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering, then the transaction's\n\t// leading statements, if any, in the same request. When writersDir and checkQueue are given, checks the\n\t// writers' queue directory first and returns { contended: true } without taking the lock if entries are present\n\t// (or the directory cannot be listed). When holderFd is given, writes the connection's holder record in place\n\t// around taking and releasing the lock.\n\tbegin: (request) => {\n\t\tif (request.writersDir !== undefined) writersDir = request.writersDir;\n\t\tif (\"holderFd\" in request) holderFd = request.holderFd;\n\t\tif (request.checkQueue === true && writersDir !== undefined && hasWriters(writersDir)) {\n\t\t\treturn { contended: true };\n\t\t}\n\t\twriteHolder(holderLine(\"want\"));\n\t\t// The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a\n\t\t// statement the calling thread runs meanwhile; settleLock gives it back once the transaction ended.\n\t\tif (request.lockState !== undefined) {\n\t\t\tconst state = new Int32Array(request.lockState);\n\t\t\tfor (;;) {\n\t\t\t\tconst found = Atomics.compareExchange(state, 0, 0, request.lockTag * 4 + 2);\n\t\t\t\tif (found === 0) break;\n\t\t\t\t// Anything but a statement of the calling thread (1) is another holder: a lock taken, as BEGIN would find.\n\t\t\t\tif (found !== 1)\n\t\t\t\t\tthrow Object.assign(new Error(\"database is locked\"), { code: \"ERR_SQLITE_ERROR\", errcode: 5, errstr: \"database is locked\" });\n\t\t\t\tAtomics.wait(state, 0, 1, 50);\n\t\t\t}\n\t\t\tAtomics.notify(state, 0);\n\t\t\tlockState = { state, held: request.lockTag * 4 + 3 };\n\t\t}\n\t\tconst configured = Number(database.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\tdatabase.exec(\"PRAGMA busy_timeout=0\");\n\t\tlet began = false;\n\t\ttry {\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\tbegan = true;\n\t\t\tholderActive = true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"PRAGMA busy_timeout=\" + configured);\n\t\t\t} catch (restoreFailure) {\n\t\t\t\tif (began) database.exec(\"ROLLBACK\");\n\t\t\t\tthrow restoreFailure;\n\t\t\t}\n\t\t}\n\t\tconst result = request.statements === undefined ? undefined : lead(request.statements);\n\t\tif (inTransaction()) writeHolder(holderLine(\"held\"));\n\t\treturn result;\n\t},\n\tlead: (request) => lead(request.statements),\n\t// \\`repeat\\`, then each statement, in one request: the statements the caller would send one at a time, in the same\n\t// order, each prepared when it is reached. The caller's abort flag is read where the caller would check its signal.\n\tsequence: (request) => {\n\t\tconst abort = request.abort === undefined ? undefined : new Int32Array(request.abort);\n\t\tconst aborted = () => abort !== undefined && Atomics.load(abort, 0) !== 0;\n\t\tlet repeated = 0;\n\t\tif (request.repeat !== undefined) {\n\t\t\tconst { statement: repeat, times, minChanges } = request.repeat;\n\t\t\twhile (repeated < times) {\n\t\t\t\tif (aborted()) return { aborted: true };\n\t\t\t\tconst before = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tstatement(repeat.sql).run(...repeat.params);\n\t\t\t\tconst after = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tif (after - before < minChanges) break;\n\t\t\t\trepeated++;\n\t\t\t}\n\t\t}\n\t\tfor (const { sql, params, script } of request.statements) {\n\t\t\tif (aborted()) return { aborted: true };\n\t\t\tif (script === true) database.exec(sql);\n\t\t\telse statement(sql).run(...params);\n\t\t}\n\t\treturn { repeated };\n\t},\n\tdataVersion: () => Number(database.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0),\n\tnow: () => Number(database.prepare(workerData.nowSql).get().now),\n\tjsonbExtract: () => {\n\t\ttry {\n\t\t\tstatement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\tthrow error;\n\t\t}\n\t},\n\tclose: () => {\n\t\tprepared.clear();\n\t\twalPath = undefined;\n\t\tdatabase?.close();\n\t\tdatabase = undefined;\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\n// A write transaction's leading statements, run in order once BEGIN IMMEDIATE took the lock: each answers with its rows\n// and the rows it changed, as all and run would, up to the first that fails; nothing after it runs. The answer says\n// whether the transaction is still open after that failure: SQLite rolls back only the statement for most failures, and\n// the whole transaction for a few (a full disk, an I/O error). A script answers nothing.\nfunction lead(statements) {\n\tconst answers = [];\n\tfor (const { sql, params, script } of statements) {\n\t\ttry {\n\t\t\tif (script === true) {\n\t\t\t\tdatabase.exec(sql);\n\t\t\t\tanswers.push({ columns: [], values: [], changes: 0 });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst rows = table(statement(sql).all(...params));\n\t\t\tanswers.push({ ...rows, changes: Number(statement(\"SELECT changes() AS changes\").get().changes) });\n\t\t} catch (error) {\n\t\t\treturn { answers, failure: failure(error), open: database.isTransaction === true };\n\t\t}\n\t}\n\treturn { answers };\n}\n\n// The file's lock word while this connection takes or holds the lock: held while a transaction is open on it, given\n// back (and the waiting threads woken) once none is, before the request that ended it is answered.\nlet lockState;\n\nfunction inTransaction() {\n\ttry {\n\t\treturn database?.isTransaction === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction settleLock() {\n\tconst open = inTransaction();\n\tif (lockState !== undefined) {\n\t\tconst { state, held } = lockState;\n\t\tif (open) {\n\t\t\tif (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);\n\t\t} else {\n\t\t\tlockState = undefined;\n\t\t\tif (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)\n\t\t\t\tAtomics.notify(state, 0);\n\t\t}\n\t}\n\tif (holderActive && !open) {\n\t\tholderActive = false;\n\t\twriteHolder(HOLDER_FREE);\n\t\tlastFreed = true;\n\t\tlastHasWaiters = writersDir !== undefined && fs.existsSync(writersDir);\n\t}\n}\n\nfunction handle(request) {\n\ttry {\n\t\treturn handlers[request.kind](request);\n\t} finally {\n\t\tsettleLock();\n\t}\n}\n\nfunction maybeCheckpoint(kind) {\n\tif (walPath === undefined || database === undefined || !CHECKPOINT_AFTER.has(kind)) return;\n\ttry {\n\t\tif (database.isTransaction !== false) return;\n\t\tconst stat = statSync(walPath, { bigint: true, throwIfNoEntry: false });\n\t\tif (stat === undefined) {\n\t\t\tlastWalSize = -1n;\n\t\t\tlastWalMtimeNs = -1n;\n\t\t\treturn;\n\t\t}\n\t\tif (stat.size <= WAL_SIZE_LIMIT_BYTES) {\n\t\t\tlastWalSize = stat.size;\n\t\t\tlastWalMtimeNs = stat.mtimeNs;\n\t\t\treturn;\n\t\t}\n\t\tif (stat.size === lastWalSize && stat.mtimeNs === lastWalMtimeNs) return;\n\t\tlastWalSize = stat.size;\n\t\tlastWalMtimeNs = stat.mtimeNs;\n\t\tdatabase.exec(\"PRAGMA wal_checkpoint(PASSIVE)\");\n\t} catch {}\n}\n\nparentPort.on(\"message\", (request) => {\n\tlet answered = false;\n\tlastFreed = false;\n\tlastHasWaiters = undefined;\n\tpendingHolderError = undefined;\n\ttry {\n\t\tconst value = handle(request);\n\t\tconst reply = { id: request.id, value, tx: inTransaction() };\n\t\tif (lastFreed) reply.freed = true;\n\t\tif (lastHasWaiters !== undefined) reply.hasWaiters = lastHasWaiters;\n\t\tif (pendingHolderError !== undefined) reply.holderError = pendingHolderError;\n\t\tparentPort.postMessage(reply);\n\t\tanswered = true;\n\t} catch (error) {\n\t\tconst reply = { id: request.id, failure: failure(error), tx: inTransaction() };\n\t\tif (lastFreed) reply.freed = true;\n\t\tif (lastHasWaiters !== undefined) reply.hasWaiters = lastHasWaiters;\n\t\tif (pendingHolderError !== undefined) reply.holderError = pendingHolderError;\n\t\tparentPort.postMessage(reply);\n\t}\n\tif (answered) maybeCheckpoint(request.kind);\n});\n`;\n\n/**\n * Statements sent as one request (see `SqliteSequence`). `abort` holds one `Int32` the caller sets to non-zero when its\n * signal aborts: the thread reads it before each run of `repeat` and before each statement.\n */\nexport interface SequenceRequest {\n\treadonly kind: \"sequence\";\n\treadonly repeat?: SqliteSequence[\"repeat\"];\n\treadonly statements: readonly SequencedStatement[];\n\treadonly abort?: SharedArrayBuffer;\n}\n\n/**\n * What a sequence request is answered with: how many runs of `repeat` changed `minChanges` rows or more, or that it\n * stopped because the caller's signal aborted.\n */\nexport type SequenceAnswer = { readonly repeated: number } | { readonly aborted: true };\n\n/** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */\nexport type ConnectionRequest =\n\t| { readonly kind: \"open\"; readonly path: string; readonly readOnly: boolean }\n\t| { readonly kind: \"exec\"; readonly sql: string }\n\t| { readonly kind: \"run\" | \"get\" | \"all\"; readonly sql: string; readonly params: readonly SqliteValue[] }\n\t| BeginRequest\n\t| LeadRequest\n\t| { readonly kind: \"dataVersion\" | \"now\" | \"jsonbExtract\" | \"close\" }\n\t| ReadTransactionRequest\n\t| SequenceRequest;\n\n/**\n * One non-blocking `BEGIN IMMEDIATE`, then, once it took the lock, `statements`, the transaction's leading statements, in\n * the same request (#6560): see the thread's `begin` and `lead`. `lockState` and `lockTag` are the file's lock word and\n * this connection's tag in it (see `node-sqlite-file-gate.ts`).\n */\nexport interface BeginRequest {\n\treadonly kind: \"begin\";\n\treadonly lockState?: SharedArrayBuffer;\n\treadonly lockTag?: number;\n\treadonly statements?: readonly SequencedStatement[];\n\t/** Open descriptor of this connection's write-lock holder record, written synchronously on the connection thread. */\n\treadonly holderFd?: number;\n\t/** Path of the cross-process writers'-queue directory, checked on the connection thread. */\n\treadonly writersDir?: string;\n\t/** When true, return `{ contended: true }` without taking the lock if `writersDir` has entries or cannot be listed. */\n\treadonly checkQueue?: boolean;\n}\n\n/** Returned by a `begin` request with `checkQueue: true` when the writers' queue directory is non-empty or unreadable. */\nexport interface BeginContendedAnswer {\n\treadonly contended: true;\n}\n\n/**\n * Statements run in one request inside an open transaction, such as a group-commit member's `SAVEPOINT` with its\n * leading statements (#6706): see the thread's `lead`.\n */\nexport interface LeadRequest {\n\treadonly kind: \"lead\";\n\treadonly statements: readonly SequencedStatement[];\n}\n\n/**\n * What a `begin` request with statements is answered with: each statement's rows and the rows it changed, in order, up\n * to the first that failed, that one's failure, and whether the transaction was still open after it; nothing after it\n * ran.\n */\nexport interface LeadAnswer {\n\treadonly answers: readonly { readonly rows: SqliteRow[]; readonly changes: number }[];\n\treadonly failure?: Error;\n\treadonly open?: boolean;\n}\n\n/**\n * A read-only transaction's start with its leading reads, and its end, which only a connection on a thread of its own\n * is sent: see the thread's `read` and `endRead`.\n */\nexport type ReadTransactionRequest =\n\t| { readonly kind: \"read\"; readonly statements: readonly SqliteStatement[] }\n\t| { readonly kind: \"endRead\" };\n\n/** Rows as they cross from a connection's thread: the column names, then each row's values in their order. */\ninterface RowTable {\n\treadonly columns: readonly string[];\n\treadonly values: readonly (readonly SqliteValue[])[];\n}\n\n/** A `LeadAnswer` as it crosses, before rows and the failure are rebuilt. */\ninterface LeadTable {\n\treadonly answers: readonly (RowTable & { readonly changes: number })[];\n\treadonly failure?: ConnectionFailure;\n\treadonly open?: boolean;\n}\n\n/** What a request's answer carries as it crosses, before rows are rebuilt. */\ntype ConnectionValue =\n\t| RowTable\n\t| readonly RowTable[]\n\t| LeadTable\n\t| BeginContendedAnswer\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/**\n * What a request is answered with: `get` a row or undefined, `all` rows, `read` the rows of each leading read up to\n * the first that failed, `run` the changes, `sequence` a `SequenceAnswer`, `open` the location, `dataVersion` and `now`\n * a number, `jsonbExtract` a boolean, the others undefined.\n */\nexport type ConnectionAnswer =\n\t| SqliteRow\n\t| SqliteRow[]\n\t| SqliteRow[][]\n\t| LeadAnswer\n\t| BeginContendedAnswer\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/** An own field that holds a plain value: its key, value and enumerability. */\ntype ConnectionField = readonly [string, string | number | boolean | bigint, boolean];\n\n/** A failure as it crosses from a connection's thread; see `failure` in the thread's source. */\ninterface ConnectionFailure {\n\treadonly constructor: string;\n\treadonly message: string;\n\treadonly fields: readonly ConnectionField[];\n\treadonly between?: {\n\t\treadonly fields: readonly ConnectionField[];\n\t\treadonly toString?: { readonly enumerable: boolean };\n\t};\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: ConnectionValue;\n\treadonly failure?: ConnectionFailure;\n\treadonly tx?: boolean;\n\treadonly freed?: boolean;\n\treadonly hasWaiters?: boolean;\n\treadonly holderError?: ConnectionFailure;\n}\n\nconst STANDARD_ERRORS: Readonly<Record<string, ErrorConstructor>> = {\n\tError,\n\tTypeError,\n\tRangeError,\n\tSyntaxError,\n\tReferenceError,\n\tEvalError,\n\tURIError,\n};\n\n/** One prototype per runtime error class seen, by what it holds: see `connectionError`. */\nconst betweenPrototypes = new Map<string, object>();\n\n/** How a runtime's error class of its own shows an error, as Bun's do: `TypeError [ERR_INVALID_ARG_VALUE]: …`. */\nfunction showWithCode(this: Error & { readonly code?: unknown }): string {\n\treturn `${this.name} [${String(this.code)}]: ${this.message}`;\n}\n\nfunction betweenPrototype(base: ErrorConstructor, between: NonNullable<ConnectionFailure[\"between\"]>): object {\n\tconst key = JSON.stringify([\n\t\tbase.name,\n\t\tbetween.fields.map(([field, value, enumerable]) => [field, String(value), enumerable]),\n\t\tbetween.toString,\n\t]);\n\tlet prototype = betweenPrototypes.get(key);\n\tif (prototype === undefined) {\n\t\tconst created: object = Object.create(base.prototype);\n\t\tfor (const [field, value, enumerable] of between.fields)\n\t\t\tObject.defineProperty(created, field, { value, enumerable, writable: true, configurable: true });\n\t\tif (between.toString !== undefined)\n\t\t\tObject.defineProperty(created, \"toString\", {\n\t\t\t\tvalue: showWithCode,\n\t\t\t\tenumerable: between.toString.enumerable,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\tbetweenPrototypes.set(key, created);\n\t\tprototype = created;\n\t}\n\treturn prototype;\n}\n\n/**\n * The driver's error, rebuilt on the calling thread as the driver threw it: an instance of the same standard error\n * class with the same message, and the same own fields (`code`, `errcode`, `errstr` for SQLite's errors) with the same\n * enumerability. A runtime's own error class between them is stood in for by a prototype that holds the same fields and\n * shows the error the same way.\n */\nfunction connectionError(failure: ConnectionFailure): Error {\n\tconst base = STANDARD_ERRORS[failure.constructor] ?? Error;\n\tconst error = new base(failure.message);\n\tif (failure.between !== undefined) Object.setPrototypeOf(error, betweenPrototype(base, failure.between));\n\tfor (const [key, value, enumerable] of failure.fields)\n\t\tObject.defineProperty(error, key, { value, enumerable, writable: true, configurable: true });\n\treturn error;\n}\n\n/** The rows of `table`, each a plain object built the way the calling-thread connection builds them. */\nfunction rowsOf(table: RowTable): SqliteRow[] {\n\tconst { columns, values } = table;\n\treturn values.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index] as SqliteValue])));\n}\n\ninterface Waiter {\n\treadonly resolve: (value: ConnectionValue) => void;\n\treadonly reject: (error: unknown) => void;\n}\n\n/** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */\nexport class ConnectionThreadEndedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ConnectionThreadEndedError\";\n\t}\n}\n\n/** Options that make every worker thread run code of the user's: a preload or a module loader. */\nconst WORKER_CODE_OPTIONS = new Set([\"--require\", \"-r\", \"--import\", \"--loader\", \"--experimental-loader\"]);\n\n/** The thread `startSpare` started for the next open, until an open takes it or `releaseSpare` ends it. */\nlet spare: ThreadConnection | undefined;\n\n/** How many prepared statements a connection keeps for reuse, least recently used first out. */\nexport const STATEMENT_CACHE_SIZE = 256;\n\n/** Safety-net automatic WAL checkpoint threshold in pages on writable file connections. */\nconst WAL_AUTO_CHECKPOINT = 10_000;\n/** Target write-ahead log size limit in bytes (4 MiB) for journal truncation and post-response checkpoints. */\nconst WAL_SIZE_LIMIT = 4 * 1024 * 1024;\n\n/** A node:sqlite connection running on its own worker thread. */\nexport class ThreadConnection {\n\tprivate readonly worker: Worker;\n\tprivate readonly waiting = new Map<number, Waiter>();\n\tprivate nextId = 1;\n\tprivate _inTransaction?: boolean;\n\tprivate _lastFreed = false;\n\tprivate _lastHasWaiters?: boolean;\n\tprivate _holderError?: Error;\n\tprivate ended?: Error;\n\tprivate closing?: Promise<undefined>;\n\n\t/** Whether SQLite had an open transaction after the thread's last answer; undefined for older connection threads. */\n\tget inTransaction(): boolean | undefined {\n\t\treturn this._inTransaction;\n\t}\n\n\t/** Consumes any connection-thread holder-record write failure reported since the last check. */\n\ttakeHolderError(): Error | undefined {\n\t\tconst error = this._holderError;\n\t\tthis._holderError = undefined;\n\t\treturn error;\n\t}\n\n\t/**\n\t * Consumes the release metadata reported by the connection thread when the transaction ended: whether the thread\n\t * already wrote the `\"free\"` holder record, and whether the writers'-queue directory existed.\n\t */\n\ttakeReleaseState(): { readonly freed: boolean; readonly hasWaiters: boolean | undefined } {\n\t\tconst state = { freed: this._lastFreed, hasWaiters: this._lastHasWaiters };\n\t\tthis._lastFreed = false;\n\t\tthis._lastHasWaiters = undefined;\n\t\treturn state;\n\t}\n\n\tprivate constructor() {\n\t\t// None of the process's own flags: the caller's preloads would run again for every connection, and its\n\t\t// `--input-type=module` would make this source a module. Whether node:sqlite is available was settled by the\n\t\t// open before it started the thread.\n\t\tthis.worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\texecArgv: [],\n\t\t\tworkerData: {\n\t\t\t\tnowSql: `SELECT ${sqliteDialect.nowMs} AS now`,\n\t\t\t\tstatementCacheSize: STATEMENT_CACHE_SIZE,\n\t\t\t\twalAutoCheckpoint: WAL_AUTO_CHECKPOINT,\n\t\t\t\twalSizeLimit: WAL_SIZE_LIMIT,\n\t\t\t},\n\t\t});\n\t\tthis.worker.on(\"message\", (reply: ConnectionReply) => this.receive(reply));\n\t\tthis.worker.on(\"error\", (error: Error) => this.end(error));\n\t\tthis.worker.on(\"exit\", (code: number) =>\n\t\t\tthis.end(new ConnectionThreadEndedError(`SQLite connection thread exited with code ${code}`)),\n\t\t);\n\t}\n\n\t/**\n\t * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure\n\t * to start the thread or to open the database rejects with its cause; the thread is gone then.\n\t */\n\tstatic async open(\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined && started.ended === undefined) {\n\t\t\ttry {\n\t\t\t\treturn await ThreadConnection.openOn(started, path, options);\n\t\t\t} catch (error) {\n\t\t\t\t// The spare thread was lost before it answered: open on a thread of its own, as without one.\n\t\t\t\tif (error !== started.ended) throw error;\n\t\t\t}\n\t\t}\n\t\treturn ThreadConnection.openOn(new ThreadConnection(), path, options);\n\t}\n\n\t/**\n\t * Starts one connection thread now, for the next open to take, so that the thread's startup overlaps whatever the\n\t * process does until then (an interactive session loads its modules meanwhile). Idle, the thread keeps nothing\n\t * alive. Nothing starts when the process runs a preload or a module loader, which every worker thread runs again,\n\t * or runs under the permission model; a thread that cannot start leaves every open as it is without one.\n\t */\n\tstatic startSpare(): void {\n\t\tif (spare !== undefined || process.permission !== undefined) return;\n\t\tif (startupNodeOptions().some((option) => WORKER_CODE_OPTIONS.has(option.name))) return;\n\t\ttry {\n\t\t\tconst started = new ThreadConnection();\n\t\t\tstarted.worker.unref();\n\t\t\tspare = started;\n\t\t} catch {\n\t\t\t// Opens start their own threads.\n\t\t}\n\t}\n\n\t/** Ends the spare thread if no open has taken it. */\n\tstatic releaseSpare(): void {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined) void started.stop();\n\t}\n\n\tprivate static async openOn(\n\t\tconnection: ThreadConnection,\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\ttry {\n\t\t\tconst location = await connection.request({\n\t\t\t\tkind: \"open\",\n\t\t\t\tpath: options.openAs ?? path,\n\t\t\t\treadOnly: options.readOnly,\n\t\t\t});\n\t\t\treturn { connection, location: typeof location === \"string\" ? location : null };\n\t\t} catch (error) {\n\t\t\tawait connection.stop();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request\n\t * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the\n\t * calling thread would not.\n\t */\n\trequest(request: ConnectionRequest): Promise<ConnectionAnswer> {\n\t\tif (request.kind === \"close\") return this.close();\n\t\tconst answer = this.send(request);\n\t\tif (request.kind === \"get\")\n\t\t\treturn answer.then((value) => (value === undefined ? undefined : rowsOf(value as RowTable)[0]));\n\t\tif (request.kind === \"all\") return answer.then((value) => rowsOf(value as RowTable));\n\t\tif (request.kind === \"read\") return answer.then((value) => (value as readonly RowTable[]).map(rowsOf));\n\t\tif (request.kind === \"lead\" || (request.kind === \"begin\" && request.statements !== undefined))\n\t\t\treturn answer.then((value): LeadAnswer | BeginContendedAnswer | undefined => {\n\t\t\t\tif (value === undefined) return undefined;\n\t\t\t\tif (typeof value === \"object\" && value !== null && \"contended\" in value)\n\t\t\t\t\treturn value as BeginContendedAnswer;\n\t\t\t\tconst { answers, failure, open } = value as LeadTable;\n\t\t\t\treturn {\n\t\t\t\t\tanswers: answers.map((each) => ({ rows: rowsOf(each), changes: each.changes })),\n\t\t\t\t\t...(failure === undefined ? {} : { failure: connectionError(failure), open: open === true }),\n\t\t\t\t};\n\t\t\t});\n\t\treturn answer as Promise<ConnectionAnswer>;\n\t}\n\n\tprivate send(request: ConnectionRequest): Promise<ConnectionValue> {\n\t\treturn new Promise<ConnectionValue>((resolve, reject) => {\n\t\t\tif (this.ended !== undefined) {\n\t\t\t\treject(this.ended);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.nextId++;\n\t\t\ttry {\n\t\t\t\tthis.worker.postMessage({ id, ...request });\n\t\t\t} catch (error) {\n\t\t\t\t// A value the thread cannot receive.\n\t\t\t\treject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tif (this.waiting.size === 1) this.worker.ref();\n\t\t});\n\t}\n\n\t/**\n\t * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A\n\t * thread already lost has nothing to close.\n\t */\n\tprivate close(): Promise<undefined> {\n\t\tthis.closing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tif (this.ended === undefined) await this.send({ kind: \"close\" });\n\t\t\t} finally {\n\t\t\t\tawait this.stop();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\treturn this.closing;\n\t}\n\n\tprivate receive(reply: ConnectionReply): void {\n\t\tif (typeof reply.tx === \"boolean\") this._inTransaction = reply.tx;\n\t\tif (reply.freed === true) {\n\t\t\tthis._lastFreed = true;\n\t\t\tthis._lastHasWaiters = reply.hasWaiters;\n\t\t}\n\t\tif (reply.holderError !== undefined) this._holderError ??= connectionError(reply.holderError);\n\t\tconst waiter = this.waiting.get(reply.id);\n\t\tif (waiter === undefined) return;\n\t\tthis.waiting.delete(reply.id);\n\t\tif (this.waiting.size === 0) this.worker.unref();\n\t\tif (reply.failure === undefined) waiter.resolve(reply.value);\n\t\telse waiter.reject(connectionError(reply.failure));\n\t}\n\n\t/** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */\n\tprivate end(cause: Error): void {\n\t\tif (this.ended !== undefined) return;\n\t\t// Kept for as long as the connection is: an error's stack, until formatted, keeps the functions of the frames it\n\t\t// names, and so whatever they hold, such as a session that closed its store.\n\t\tvoid cause.stack;\n\t\tthis.ended = cause;\n\t\tconst waiting = [...this.waiting.values()];\n\t\tthis.waiting.clear();\n\t\tthis.worker.unref();\n\t\tfor (const waiter of waiting) waiter.reject(cause);\n\t}\n\n\tprivate async stop(): Promise<void> {\n\t\tthis.end(new ConnectionThreadEndedError(\"SQLite connection closed\"));\n\t\tawait this.worker.terminate();\n\t}\n\n\t/** Calls `listener` once the connection's thread has exited, whether closed or lost. */\n\tonExit(listener: () => void): void {\n\t\tthis.worker.once(\"exit\", listener);\n\t}\n\n\t/**\n\t * Starts a spare worker for a non-interactive or storage-overridden CLI\n\t * invocation only when the real CLI/storage resolvers select a SQLite store.\n\t */\n\tstatic async startSpareIfSqlNeeded(\n\t\targs: readonly string[],\n\t\tterminal: { readonly stdinIsTTY: boolean; readonly stdoutIsTTY: boolean },\n\t\tstillBeforeMain: () => boolean,\n\t): Promise<void> {\n\t\tconst { shouldStartSpareDatabaseThread } = await import(\"../../utils/startup-database-spare.ts\");\n\t\tif (stillBeforeMain() && shouldStartSpareDatabaseThread(args, false, terminal)) {\n\t\t\tThreadConnection.startSpare();\n\t\t}\n\t}\n}\n"]}