@bastani/atomic 0.10.0-alpha.1 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/CHANGELOG.md +260 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +22 -0
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/CHANGELOG.md +41 -0
  6. package/dist/builtin/subagents/package.json +1 -1
  7. package/dist/builtin/subagents/skills/tmux/scripts/wait-for-text.sh +33 -3
  8. package/dist/builtin/web-access/package.json +1 -1
  9. package/dist/core/agent-session-events.d.ts.map +1 -1
  10. package/dist/core/agent-session-events.js +21 -6
  11. package/dist/core/agent-session-events.js.map +1 -1
  12. package/dist/core/lifecycle-timings.d.ts +6 -0
  13. package/dist/core/lifecycle-timings.d.ts.map +1 -1
  14. package/dist/core/lifecycle-timings.js +12 -0
  15. package/dist/core/lifecycle-timings.js.map +1 -1
  16. package/dist/core/queued-message-delivery.d.ts +41 -0
  17. package/dist/core/queued-message-delivery.d.ts.map +1 -0
  18. package/dist/core/queued-message-delivery.js +48 -0
  19. package/dist/core/queued-message-delivery.js.map +1 -0
  20. package/dist/core/storage/node-sqlite-thread.d.ts +64 -0
  21. package/dist/core/storage/node-sqlite-thread.d.ts.map +1 -0
  22. package/dist/core/storage/node-sqlite-thread.js +326 -0
  23. package/dist/core/storage/node-sqlite-thread.js.map +1 -0
  24. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  25. package/dist/core/storage/node-sqlite.js +230 -104
  26. package/dist/core/storage/node-sqlite.js.map +1 -1
  27. package/dist/core/tasks/agent-panel-source.d.ts +5 -0
  28. package/dist/core/tasks/agent-panel-source.d.ts.map +1 -1
  29. package/dist/core/tasks/agent-panel-source.js +1 -1
  30. package/dist/core/tasks/agent-panel-source.js.map +1 -1
  31. package/dist/modes/interactive/agent-view/agent-view-bridge.d.ts +8 -1
  32. package/dist/modes/interactive/agent-view/agent-view-bridge.d.ts.map +1 -1
  33. package/dist/modes/interactive/agent-view/agent-view-bridge.js.map +1 -1
  34. package/dist/modes/interactive/agent-view/agent-view-switcher.d.ts +11 -5
  35. package/dist/modes/interactive/agent-view/agent-view-switcher.d.ts.map +1 -1
  36. package/dist/modes/interactive/agent-view/agent-view-switcher.js +17 -5
  37. package/dist/modes/interactive/agent-view/agent-view-switcher.js.map +1 -1
  38. package/dist/modes/interactive/agent-view/contracts.d.ts +5 -0
  39. package/dist/modes/interactive/agent-view/contracts.d.ts.map +1 -1
  40. package/dist/modes/interactive/agent-view/contracts.js.map +1 -1
  41. package/dist/modes/interactive/agent-view/install.d.ts.map +1 -1
  42. package/dist/modes/interactive/agent-view/install.js +6 -3
  43. package/dist/modes/interactive/agent-view/install.js.map +1 -1
  44. package/dist/modes/interactive/agent-view/local-port.d.ts +5 -0
  45. package/dist/modes/interactive/agent-view/local-port.d.ts.map +1 -1
  46. package/dist/modes/interactive/agent-view/local-port.js +8 -0
  47. package/dist/modes/interactive/agent-view/local-port.js.map +1 -1
  48. package/dist/modes/interactive/agent-view/remote-port.d.ts +4 -1
  49. package/dist/modes/interactive/agent-view/remote-port.d.ts.map +1 -1
  50. package/dist/modes/interactive/agent-view/remote-port.js +22 -8
  51. package/dist/modes/interactive/agent-view/remote-port.js.map +1 -1
  52. package/dist/modes/interactive/agent-view/transcript-slot.d.ts +9 -0
  53. package/dist/modes/interactive/agent-view/transcript-slot.d.ts.map +1 -1
  54. package/dist/modes/interactive/agent-view/transcript-slot.js +141 -1
  55. package/dist/modes/interactive/agent-view/transcript-slot.js.map +1 -1
  56. package/dist/modes/interactive/components/agent-panel.d.ts +6 -0
  57. package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
  58. package/dist/modes/interactive/components/agent-panel.js +40 -10
  59. package/dist/modes/interactive/components/agent-panel.js.map +1 -1
  60. package/dist/modes/interactive/components/atomic-working-status.d.ts +15 -0
  61. package/dist/modes/interactive/components/atomic-working-status.d.ts.map +1 -1
  62. package/dist/modes/interactive/components/atomic-working-status.js +51 -3
  63. package/dist/modes/interactive/components/atomic-working-status.js.map +1 -1
  64. package/dist/modes/interactive/components/bash-execution.d.ts +2 -0
  65. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  66. package/dist/modes/interactive/components/bash-execution.js +5 -1
  67. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  68. package/dist/modes/interactive/components/branch-summary-message.d.ts +2 -0
  69. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  70. package/dist/modes/interactive/components/branch-summary-message.js +5 -1
  71. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  72. package/dist/modes/interactive/components/chat-message-renderer.d.ts +2 -0
  73. package/dist/modes/interactive/components/chat-message-renderer.d.ts.map +1 -1
  74. package/dist/modes/interactive/components/chat-message-renderer.js +17 -6
  75. package/dist/modes/interactive/components/chat-message-renderer.js.map +1 -1
  76. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  77. package/dist/modes/interactive/components/chat-session-host-events.js +35 -4
  78. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  79. package/dist/modes/interactive/components/chat-session-host-rendering.d.ts.map +1 -1
  80. package/dist/modes/interactive/components/chat-session-host-rendering.js +70 -13
  81. package/dist/modes/interactive/components/chat-session-host-rendering.js.map +1 -1
  82. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts +7 -0
  83. package/dist/modes/interactive/components/chat-session-host-runtime.d.ts.map +1 -1
  84. package/dist/modes/interactive/components/chat-session-host-runtime.js +25 -4
  85. package/dist/modes/interactive/components/chat-session-host-runtime.js.map +1 -1
  86. package/dist/modes/interactive/components/chat-session-host-state.d.ts +41 -1
  87. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  88. package/dist/modes/interactive/components/chat-session-host-state.js +24 -3
  89. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  90. package/dist/modes/interactive/components/chat-session-host-steering.d.ts.map +1 -1
  91. package/dist/modes/interactive/components/chat-session-host-steering.js +2 -1
  92. package/dist/modes/interactive/components/chat-session-host-steering.js.map +1 -1
  93. package/dist/modes/interactive/components/chat-session-host.d.ts +13 -1
  94. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  95. package/dist/modes/interactive/components/chat-session-host.js +20 -2
  96. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  97. package/dist/modes/interactive/components/chat-transcript.d.ts +15 -0
  98. package/dist/modes/interactive/components/chat-transcript.d.ts.map +1 -1
  99. package/dist/modes/interactive/components/chat-transcript.js +14 -1
  100. package/dist/modes/interactive/components/chat-transcript.js.map +1 -1
  101. package/dist/modes/interactive/components/compaction-boundary-message.d.ts +2 -0
  102. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  103. package/dist/modes/interactive/components/compaction-boundary-message.js +5 -1
  104. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  105. package/dist/modes/interactive/components/custom-entry.d.ts +2 -0
  106. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
  107. package/dist/modes/interactive/components/custom-entry.js +5 -1
  108. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  109. package/dist/modes/interactive/components/custom-message.d.ts +2 -0
  110. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  111. package/dist/modes/interactive/components/custom-message.js +5 -1
  112. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  113. package/dist/modes/interactive/components/model-column.d.ts +96 -0
  114. package/dist/modes/interactive/components/model-column.d.ts.map +1 -0
  115. package/dist/modes/interactive/components/model-column.js +207 -0
  116. package/dist/modes/interactive/components/model-column.js.map +1 -0
  117. package/dist/modes/interactive/components/prompt-slot.d.ts +73 -0
  118. package/dist/modes/interactive/components/prompt-slot.d.ts.map +1 -0
  119. package/dist/modes/interactive/components/prompt-slot.js +201 -0
  120. package/dist/modes/interactive/components/prompt-slot.js.map +1 -0
  121. package/dist/modes/interactive/components/queued-messages-view.d.ts +6 -3
  122. package/dist/modes/interactive/components/queued-messages-view.d.ts.map +1 -1
  123. package/dist/modes/interactive/components/queued-messages-view.js +7 -4
  124. package/dist/modes/interactive/components/queued-messages-view.js.map +1 -1
  125. package/dist/modes/interactive/components/session-selector.d.ts +2 -0
  126. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  127. package/dist/modes/interactive/components/session-selector.js +4 -0
  128. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  129. package/dist/modes/interactive/components/skill-invocation-message.d.ts +2 -0
  130. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  131. package/dist/modes/interactive/components/skill-invocation-message.js +5 -1
  132. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  133. package/dist/modes/interactive/components/task-board.d.ts +12 -3
  134. package/dist/modes/interactive/components/task-board.d.ts.map +1 -1
  135. package/dist/modes/interactive/components/task-board.js +33 -17
  136. package/dist/modes/interactive/components/task-board.js.map +1 -1
  137. package/dist/modes/interactive/components/task-inspector.d.ts +6 -1
  138. package/dist/modes/interactive/components/task-inspector.d.ts.map +1 -1
  139. package/dist/modes/interactive/components/task-inspector.js +27 -7
  140. package/dist/modes/interactive/components/task-inspector.js.map +1 -1
  141. package/dist/modes/interactive/components/task-row.d.ts +4 -0
  142. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  143. package/dist/modes/interactive/components/task-row.js +7 -1
  144. package/dist/modes/interactive/components/task-row.js.map +1 -1
  145. package/dist/modes/interactive/components/task-transcript-page.d.ts +5 -0
  146. package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
  147. package/dist/modes/interactive/components/task-transcript-page.js +25 -0
  148. package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
  149. package/dist/modes/interactive/components/tool-execution.d.ts +7 -0
  150. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  151. package/dist/modes/interactive/components/tool-execution.js +19 -2
  152. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  153. package/dist/modes/interactive/components/tool-group-tracker.d.ts +20 -3
  154. package/dist/modes/interactive/components/tool-group-tracker.d.ts.map +1 -1
  155. package/dist/modes/interactive/components/tool-group-tracker.js +34 -7
  156. package/dist/modes/interactive/components/tool-group-tracker.js.map +1 -1
  157. package/dist/modes/interactive/components/transcript-block-clicks.d.ts +14 -2
  158. package/dist/modes/interactive/components/transcript-block-clicks.d.ts.map +1 -1
  159. package/dist/modes/interactive/components/transcript-block-clicks.js +23 -2
  160. package/dist/modes/interactive/components/transcript-block-clicks.js.map +1 -1
  161. package/dist/modes/interactive/interactive-agent-events.js +10 -2
  162. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  163. package/dist/modes/interactive/interactive-extension-runtime.d.ts +12 -1
  164. package/dist/modes/interactive/interactive-extension-runtime.d.ts.map +1 -1
  165. package/dist/modes/interactive/interactive-extension-runtime.js +37 -5
  166. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  167. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  168. package/dist/modes/interactive/interactive-input-handling.js +70 -46
  169. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  170. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  171. package/dist/modes/interactive/interactive-mode-base.js +7 -1
  172. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  173. package/dist/modes/interactive/interactive-prompt-turn.js +17 -9
  174. package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
  175. package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
  176. package/dist/modes/interactive/interactive-queueing.js +2 -1
  177. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  178. package/dist/modes/interactive/interactive-render-chat.d.ts +18 -1
  179. package/dist/modes/interactive/interactive-render-chat.d.ts.map +1 -1
  180. package/dist/modes/interactive/interactive-render-chat.js +90 -10
  181. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  182. package/dist/modes/interactive/interactive-session-routing.js +2 -0
  183. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  184. package/dist/modes/interactive/interactive-task-projection.js +2 -2
  185. package/dist/modes/interactive/interactive-task-projection.js.map +1 -1
  186. package/dist/modes/interactive/screen-hold.d.ts +41 -0
  187. package/dist/modes/interactive/screen-hold.d.ts.map +1 -0
  188. package/dist/modes/interactive/screen-hold.js +80 -0
  189. package/dist/modes/interactive/screen-hold.js.map +1 -0
  190. package/dist/modes/interactive/started-run-echo.d.ts +66 -0
  191. package/dist/modes/interactive/started-run-echo.d.ts.map +1 -0
  192. package/dist/modes/interactive/started-run-echo.js +75 -0
  193. package/dist/modes/interactive/started-run-echo.js.map +1 -0
  194. package/dist/modes/interactive-engine/engine-custom-ui.d.ts +1 -0
  195. package/dist/modes/interactive-engine/engine-custom-ui.d.ts.map +1 -1
  196. package/dist/modes/interactive-engine/engine-custom-ui.js +25 -1
  197. package/dist/modes/interactive-engine/engine-custom-ui.js.map +1 -1
  198. package/dist/modes/interactive-engine/engine-quit-intent.d.ts.map +1 -1
  199. package/dist/modes/interactive-engine/engine-quit-intent.js +3 -0
  200. package/dist/modes/interactive-engine/engine-quit-intent.js.map +1 -1
  201. package/dist/modes/interactive-engine/protocol.d.ts +5 -0
  202. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  203. package/dist/modes/interactive-engine/protocol.js +7 -1
  204. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  205. package/dist/modes/interactive-engine/remote-component.d.ts +10 -2
  206. package/dist/modes/interactive-engine/remote-component.d.ts.map +1 -1
  207. package/dist/modes/interactive-engine/remote-component.js +19 -2
  208. package/dist/modes/interactive-engine/remote-component.js.map +1 -1
  209. package/dist/modes/interactive-engine/remote-renderer.d.ts +10 -0
  210. package/dist/modes/interactive-engine/remote-renderer.d.ts.map +1 -1
  211. package/dist/modes/interactive-engine/remote-renderer.js +24 -4
  212. package/dist/modes/interactive-engine/remote-renderer.js.map +1 -1
  213. package/dist/modes/interactive-engine/transcript-frame-layout.d.ts +50 -0
  214. package/dist/modes/interactive-engine/transcript-frame-layout.d.ts.map +1 -0
  215. package/dist/modes/interactive-engine/transcript-frame-layout.js +95 -0
  216. package/dist/modes/interactive-engine/transcript-frame-layout.js.map +1 -0
  217. package/dist/modes/rpc/agent-panel-bridge.d.ts.map +1 -1
  218. package/dist/modes/rpc/agent-panel-bridge.js +16 -0
  219. package/dist/modes/rpc/agent-panel-bridge.js.map +1 -1
  220. package/dist/modes/rpc/agent-view-engine-registry.d.ts.map +1 -1
  221. package/dist/modes/rpc/agent-view-engine-registry.js +36 -1
  222. package/dist/modes/rpc/agent-view-engine-registry.js.map +1 -1
  223. package/dist/modes/rpc/agent-view-rpc-panel.d.ts.map +1 -1
  224. package/dist/modes/rpc/agent-view-rpc-panel.js +5 -1
  225. package/dist/modes/rpc/agent-view-rpc-panel.js.map +1 -1
  226. package/dist/modes/rpc/task-ui-bridge.js +1 -1
  227. package/dist/modes/rpc/task-ui-bridge.js.map +1 -1
  228. package/docs/background-tasks.md +1 -1
  229. package/docs/development.md +2 -0
  230. package/docs/extensions/authoring.md +1 -1
  231. package/docs/keybindings.md +2 -2
  232. package/docs/storage.md +1 -0
  233. package/npm-shrinkwrap.json +49 -49
  234. package/package.json +6 -6
@@ -0,0 +1,48 @@
1
+ const sessions = new WeakMap();
2
+ const listedWith = new WeakMap();
3
+ /** The turn took `text` out of `session`'s `lane` queue; its `message_start` has not reached the listeners yet. */
4
+ export function beginQueuedMessageDelivery(session, lane, text) {
5
+ let deliveries = sessions.get(session);
6
+ if (deliveries === undefined) {
7
+ deliveries = { taken: 0, underWay: new Set() };
8
+ sessions.set(session, deliveries);
9
+ }
10
+ const delivery = { lane, text, order: ++deliveries.taken };
11
+ deliveries.underWay.add(delivery);
12
+ return delivery;
13
+ }
14
+ /**
15
+ * The message's `message_start` is reaching the listeners now, or never will (a hook failed, or the session already
16
+ * shows the input): it is no longer under way.
17
+ */
18
+ export function endQueuedMessageDelivery(session, delivery) {
19
+ if (delivery === undefined)
20
+ return;
21
+ const deliveries = sessions.get(session);
22
+ if (deliveries === undefined || !deliveries.underWay.delete(delivery))
23
+ return;
24
+ // A later delivery starts a new record, which an event sent before it never reaches.
25
+ if (deliveries.underWay.size === 0)
26
+ sessions.delete(session);
27
+ }
28
+ /** Record with `event`, a `queue_update` `session` is about to send, which deliveries are under way now. */
29
+ export function noteQueueUpdateDeliveries(session, event) {
30
+ const deliveries = sessions.get(session);
31
+ if (deliveries !== undefined)
32
+ listedWith.set(event, { session: deliveries, through: deliveries.taken });
33
+ }
34
+ /** The deliveries `event`, a `queue_update`, lists; undefined when none was under way as it was sent. */
35
+ export function queueUpdateDeliveries(event) {
36
+ return listedWith.get(event);
37
+ }
38
+ /** The texts of `lane` that `listed` still has under way, in the order the turns took them. */
39
+ export function queuedTextsUnderWay(listed, lane) {
40
+ if (listed === undefined)
41
+ return [];
42
+ const texts = [];
43
+ for (const delivery of listed.session.underWay)
44
+ if (delivery.lane === lane && delivery.order <= listed.through)
45
+ texts.push(delivery.text);
46
+ return texts;
47
+ }
48
+ //# sourceMappingURL=queued-message-delivery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queued-message-delivery.js","sourceRoot":"","sources":["../../src/core/queued-message-delivery.ts"],"names":[],"mappings":"AA6BA,MAAM,QAAQ,GAAG,IAAI,OAAO,EAA6B,CAAC;AAC1D,MAAM,UAAU,GAAG,IAAI,OAAO,EAAiC,CAAC;AAEhE,mHAAmH;AACnH,MAAM,UAAU,0BAA0B,CACzC,OAAe,EACf,IAAmC,EACnC,IAAY;IAEZ,IAAI,UAAU,GAAG,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACvC,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;QAC9B,UAAU,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,IAAI,GAAG,EAAE,EAAE,CAAC;QAC/C,QAAQ,CAAC,GAAG,CAAC,OAAO,EA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AK,MAAM,QAAQ,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ;QAC7C,IAAI,QAAQ,CAAC,IAAI,KAAK,IAAI,IAAI,QAAQ,CAAC,KAAK,IAAI,MAAM,CAAC,OAAO;YAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC3F,OAAO,KAAK,CAAC;AACd,CAAC","sourcesContent":["/**\n * A queued message from the moment its turn takes it out of the session's queue until its own `message_start`\n * reaches the session's listeners. Between the two, the session runs the extensions' `message_start` hooks, and the\n * `queue_update` it sent when the turn took the message already lists the queue without it. A chat in this process\n * keeps showing such a message as queued until its own row is in the transcript, so the message is never off screen.\n *\n * Nothing here changes a public event or its order, and nothing crosses a process boundary. Only deliveries still\n * under way are reachable: an event a listener keeps reaches the session's deliveries in flight, never the text of\n * one that ended, and each `queue_update` records a number, not a copy.\n */\nexport interface QueuedMessageDelivery {\n\treadonly lane: \"steer\" | \"followUp\";\n\treadonly text: string;\n\t/** Its place in the order the session's turns took messages. */\n\treadonly order: number;\n}\n\n/** One session's deliveries under way, in the order its turns took them; dropped once none is left. */\ninterface SessionDeliveries {\n\ttaken: number;\n\treadonly underWay: Set<QueuedMessageDelivery>;\n}\n\n/** The deliveries a `queue_update` lists: those of `session` the turns had taken when it was sent, while under way. */\nexport interface QueueUpdateDeliveries {\n\treadonly session: SessionDeliveries;\n\treadonly through: number;\n}\n\nconst sessions = new WeakMap<object, SessionDeliveries>();\nconst listedWith = new WeakMap<object, QueueUpdateDeliveries>();\n\n/** The turn took `text` out of `session`'s `lane` queue; its `message_start` has not reached the listeners yet. */\nexport function beginQueuedMessageDelivery(\n\tsession: object,\n\tlane: QueuedMessageDelivery[\"lane\"],\n\ttext: string,\n): QueuedMessageDelivery {\n\tlet deliveries = sessions.get(session);\n\tif (deliveries === undefined) {\n\t\tdeliveries = { taken: 0, underWay: new Set() };\n\t\tsessions.set(session, deliveries);\n\t}\n\tconst delivery: QueuedMessageDelivery = { lane, text, order: ++deliveries.taken };\n\tdeliveries.underWay.add(delivery);\n\treturn delivery;\n}\n\n/**\n * The message's `message_start` is reaching the listeners now, or never will (a hook failed, or the session already\n * shows the input): it is no longer under way.\n */\nexport function endQueuedMessageDelivery(session: object, delivery: QueuedMessageDelivery | undefined): void {\n\tif (delivery === undefined) return;\n\tconst deliveries = sessions.get(session);\n\tif (deliveries === undefined || !deliveries.underWay.delete(delivery)) return;\n\t// A later delivery starts a new record, which an event sent before it never reaches.\n\tif (deliveries.underWay.size === 0) sessions.delete(session);\n}\n\n/** Record with `event`, a `queue_update` `session` is about to send, which deliveries are under way now. */\nexport function noteQueueUpdateDeliveries(session: object, event: object): void {\n\tconst deliveries = sessions.get(session);\n\tif (deliveries !== undefined) listedWith.set(event, { session: deliveries, through: deliveries.taken });\n}\n\n/** The deliveries `event`, a `queue_update`, lists; undefined when none was under way as it was sent. */\nexport function queueUpdateDeliveries(event: object): QueueUpdateDeliveries | undefined {\n\treturn listedWith.get(event);\n}\n\n/** The texts of `lane` that `listed` still has under way, in the order the turns took them. */\nexport function queuedTextsUnderWay(\n\tlisted: QueueUpdateDeliveries | undefined,\n\tlane: QueuedMessageDelivery[\"lane\"],\n): string[] {\n\tif (listed === undefined) return [];\n\tconst texts: string[] = [];\n\tfor (const delivery of listed.session.underWay)\n\t\tif (delivery.lane === lane && delivery.order <= listed.through) texts.push(delivery.text);\n\treturn texts;\n}\n"]}
@@ -0,0 +1,64 @@
1
+ import type { SqliteRow, SqliteValue } from "./database.js";
2
+ /** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */
3
+ export type ConnectionRequest = {
4
+ readonly kind: "open";
5
+ readonly path: string;
6
+ readonly readOnly: boolean;
7
+ } | {
8
+ readonly kind: "exec";
9
+ readonly sql: string;
10
+ } | {
11
+ readonly kind: "run" | "get" | "all";
12
+ readonly sql: string;
13
+ readonly params: readonly SqliteValue[];
14
+ } | {
15
+ readonly kind: "begin" | "dataVersion" | "now" | "jsonbExtract" | "close";
16
+ };
17
+ /**
18
+ * What a request is answered with: `get` a row or undefined, `all` rows, `run` the changes, `open` the location,
19
+ * `dataVersion` and `now` a number, `jsonbExtract` a boolean, the others undefined.
20
+ */
21
+ export type ConnectionAnswer = SqliteRow | SqliteRow[] | {
22
+ readonly changes: number;
23
+ } | string | number | boolean | null | undefined;
24
+ /** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */
25
+ export declare class ConnectionThreadEndedError extends Error {
26
+ constructor(message: string);
27
+ }
28
+ /** A node:sqlite connection running on its own worker thread. */
29
+ export declare class ThreadConnection {
30
+ private readonly worker;
31
+ private readonly waiting;
32
+ private nextId;
33
+ private ended?;
34
+ private closing?;
35
+ private constructor();
36
+ /**
37
+ * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure
38
+ * to start the thread or to open the database rejects with its cause; the thread is gone then.
39
+ */
40
+ static open(path: string, options: {
41
+ readonly readOnly: boolean;
42
+ readonly openAs?: string;
43
+ }): Promise<{
44
+ readonly connection: ThreadConnection;
45
+ readonly location: string | null;
46
+ }>;
47
+ /**
48
+ * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request
49
+ * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the
50
+ * calling thread would not.
51
+ */
52
+ request(request: ConnectionRequest): Promise<ConnectionAnswer>;
53
+ private send;
54
+ /**
55
+ * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A
56
+ * thread already lost has nothing to close.
57
+ */
58
+ private close;
59
+ private receive;
60
+ /** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */
61
+ private end;
62
+ private stop;
63
+ }
64
+ //# sourceMappingURL=node-sqlite-thread.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-sqlite-thread.d.ts","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-thread.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,eAAe,CA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QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,GAC/D,OAAO,CAAC;QAAE,QAAQ,CAAC,UAAU,EAAE,gBAAgB,CAAC;QAAC,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAatF;IAED;;;;OAIG;IACH,OAAO,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAO7D;IAED,OAAO,CAAC,IAAI;IAmBZ;;;OAGG;IACH,OAAO,CAAC,KAAK;IAYb,OAAO,CAAC,OAAO;IASf,yGAAyG;IACzG,OAAO,CAAC,GAAG;YAYG,IAAI;CAIlB"}
@@ -0,0 +1,326 @@
1
+ import { Worker } from "node:worker_threads";
2
+ import { sqliteDialect } from "./dialect.js";
3
+ /**
4
+ * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the
5
+ * calling thread sends it one request at a time and receives each answer as a message, so no statement, lock wait or
6
+ * synced commit runs on the caller's event loop. SQLite's busy handler waits on the connection's own thread, so a
7
+ * statement waiting for a lock that another connection of the same process holds never stops that connection from
8
+ * finishing.
9
+ */
10
+ const CONNECTION_SOURCE = `
11
+ const { parentPort, workerData } = require("node:worker_threads");
12
+ process.emitWarning = () => {};
13
+ const { DatabaseSync } = require("node:sqlite");
14
+ let database;
15
+
16
+ const STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];
17
+ // Bun stamps every error with where it was thrown; the caller's copy gets its own.
18
+ const LOCATION_FIELDS = new Set(["stack", "message", "line", "column", "originalLine", "originalColumn", "sourceURL"]);
19
+
20
+ // An object's own fields that hold plain values, with their enumerability.
21
+ function fieldsOf(object, skip) {
22
+ const fields = [];
23
+ for (const key of Object.getOwnPropertyNames(object)) {
24
+ if (skip.has(key)) continue;
25
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
26
+ const value = descriptor?.value;
27
+ if (value === null || (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean" && typeof value !== "bigint")) continue;
28
+ fields.push([key, value, descriptor.enumerable === true]);
29
+ }
30
+ return fields;
31
+ }
32
+
33
+ // A thrown error as it crosses to the caller: the standard constructor it descends from, its message, and its own
34
+ // fields with their enumerability. A runtime's error class of its own between the error and that constructor (Bun's
35
+ // node:sqlite errors have one holding name, code and toString) is described by its fields and whether it has a
36
+ // toString of its own, and how it shows.
37
+ function failure(error) {
38
+ if (!(error instanceof Error)) return { constructor: "Error", message: String(error), fields: [] };
39
+ let standard = Object.getPrototypeOf(error);
40
+ let between;
41
+ while (standard !== null && !STANDARD_ERRORS.some((each) => each.prototype === standard)) {
42
+ if (between === undefined) {
43
+ const toString = Object.getOwnPropertyDescriptor(standard, "toString");
44
+ between = {
45
+ fields: fieldsOf(standard, new Set(["constructor", "message"])),
46
+ ...(typeof toString?.value === "function" ? { toString: { enumerable: toString.enumerable === true } } : {}),
47
+ };
48
+ }
49
+ standard = Object.getPrototypeOf(standard);
50
+ }
51
+ return {
52
+ constructor: standard === null ? "Error" : standard.constructor.name,
53
+ message: String(error.message),
54
+ fields: fieldsOf(error, LOCATION_FIELDS),
55
+ ...(between === undefined ? {} : { between }),
56
+ };
57
+ }
58
+
59
+ function statement(sql) {
60
+ const prepared = database.prepare(sql);
61
+ prepared.setReadBigInts(true);
62
+ return prepared;
63
+ }
64
+
65
+ // Node 22 binds an empty Uint8Array that arrived in a message as NULL; a new empty one binds as a zero-length blob.
66
+ function bind(params) {
67
+ return params.map((value) => (value instanceof Uint8Array && value.byteLength === 0 ? new Uint8Array(0) : value));
68
+ }
69
+
70
+ function value(each) {
71
+ if (typeof each === "bigint") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;
72
+ // A copy of its own: a view of a larger buffer would send the whole buffer.
73
+ return each instanceof Uint8Array ? new Uint8Array(each) : each;
74
+ }
75
+
76
+ // Rows cross as their column names and one array of values each, in the order the driver gives a row's fields.
77
+ function table(rows) {
78
+ if (rows.length === 0) return { columns: [], values: [] };
79
+ const columns = Object.keys(rows[0]);
80
+ return { columns, values: rows.map((row) => columns.map((column) => value(row[column]))) };
81
+ }
82
+
83
+ const handlers = {
84
+ open: (request) => {
85
+ database = new DatabaseSync(request.path, { readOnly: request.readOnly });
86
+ return database.location();
87
+ },
88
+ exec: (request) => {
89
+ database.exec(request.sql);
90
+ },
91
+ run: (request) => ({ changes: Number(statement(request.sql).run(...bind(request.params)).changes) }),
92
+ get: (request) => {
93
+ const row = statement(request.sql).get(...bind(request.params));
94
+ return row === undefined ? undefined : table([row]);
95
+ },
96
+ all: (request) => table(statement(request.sql).all(...bind(request.params))),
97
+ // One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.
98
+ begin: () => {
99
+ const configured = Number(database.prepare("PRAGMA busy_timeout").get()?.timeout ?? 0);
100
+ database.exec("PRAGMA busy_timeout=0");
101
+ let began = false;
102
+ try {
103
+ database.exec("BEGIN IMMEDIATE");
104
+ began = true;
105
+ } finally {
106
+ try {
107
+ database.exec("PRAGMA busy_timeout=" + configured);
108
+ } catch (restoreFailure) {
109
+ if (began) database.exec("ROLLBACK");
110
+ throw restoreFailure;
111
+ }
112
+ }
113
+ },
114
+ dataVersion: () => Number(database.prepare("PRAGMA data_version").get()?.data_version ?? 0),
115
+ now: () => Number(database.prepare(workerData.nowSql).get().now),
116
+ jsonbExtract: () => {
117
+ try {
118
+ statement("SELECT jsonb_extract('[]', '$')");
119
+ return true;
120
+ } catch (error) {
121
+ if (error instanceof Error && error.message === "no such function: jsonb_extract") return false;
122
+ throw error;
123
+ }
124
+ },
125
+ close: () => {
126
+ database?.close();
127
+ globalThis.Bun?.gc?.(true);
128
+ },
129
+ };
130
+
131
+ parentPort.on("message", (request) => {
132
+ try {
133
+ parentPort.postMessage({ id: request.id, value: handlers[request.kind](request) });
134
+ } catch (error) {
135
+ parentPort.postMessage({ id: request.id, failure: failure(error) });
136
+ }
137
+ });
138
+ `;
139
+ const STANDARD_ERRORS = {
140
+ Error,
141
+ TypeError,
142
+ RangeError,
143
+ SyntaxError,
144
+ ReferenceError,
145
+ EvalError,
146
+ URIError,
147
+ };
148
+ /** One prototype per runtime error class seen, by what it holds: see `connectionError`. */
149
+ const betweenPrototypes = new Map();
150
+ /** How a runtime's error class of its own shows an error, as Bun's do: `TypeError [ERR_INVALID_ARG_VALUE]: …`. */
151
+ function showWithCode() {
152
+ return `${this.name} [${String(this.code)}]: ${this.message}`;
153
+ }
154
+ function betweenPrototype(base, between) {
155
+ const key = JSON.stringify([
156
+ base.name,
157
+ between.fields.map(([field, value, enumerable]) => [field, String(value), enumerable]),
158
+ between.toString,
159
+ ]);
160
+ let prototype = betweenPrototypes.get(key);
161
+ if (prototype === undefined) {
162
+ const created = Object.create(base.prototype);
163
+ for (const [field, value, enumerable] of between.fields)
164
+ Object.defineProperty(created, field, { value, enumerable, writable: true, configurable: true });
165
+ if (between.toString !== undefined)
166
+ Object.defineProperty(created, "toString", {
167
+ value: showWithCode,
168
+ enumerable: between.toString.enumerable,
169
+ writable: true,
170
+ configurable: true,
171
+ });
172
+ betweenPrototypes.set(key, created);
173
+ prototype = created;
174
+ }
175
+ return prototype;
176
+ }
177
+ /**
178
+ * The driver's error, rebuilt on the calling thread as the driver threw it: an instance of the same standard error
179
+ * class with the same message, and the same own fields (`code`, `errcode`, `errstr` for SQLite's errors) with the same
180
+ * enumerability. A runtime's own error class between them is stood in for by a prototype that holds the same fields and
181
+ * shows the error the same way.
182
+ */
183
+ function connectionError(failure) {
184
+ const base = STANDARD_ERRORS[failure.constructor] ?? Error;
185
+ const error = new base(failure.message);
186
+ if (failure.between !== undefined)
187
+ Object.setPrototypeOf(error, betweenPrototype(base, failure.between));
188
+ for (const [key, value, enumerable] of failure.fields)
189
+ Object.defineProperty(error, key, { value, enumerable, writable: true, configurable: true });
190
+ return error;
191
+ }
192
+ /** The rows of `table`, each a plain object built the way the calling-thread connection builds them. */
193
+ function rowsOf(table) {
194
+ const { columns, values } = table;
195
+ return values.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index]])));
196
+ }
197
+ /** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */
198
+ export class ConnectionThreadEndedError extends Error {
199
+ constructor(message) {
200
+ super(message);
201
+ this.name = "ConnectionThreadEndedError";
202
+ }
203
+ }
204
+ /** A node:sqlite connection running on its own worker thread. */
205
+ export class ThreadConnection {
206
+ worker;
207
+ waiting = new Map();
208
+ nextId = 1;
209
+ ended;
210
+ closing;
211
+ constructor() {
212
+ // None of the process's own flags: an `--input-type=module` would make this CommonJS source a module, and the
213
+ // caller's preloads would run again for every connection. Whether node:sqlite is available was settled by the
214
+ // open before it started the thread.
215
+ this.worker = new Worker(CONNECTION_SOURCE, {
216
+ eval: true,
217
+ execArgv: [],
218
+ workerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now` },
219
+ });
220
+ this.worker.on("message", (reply) => this.receive(reply));
221
+ this.worker.on("error", (error) => this.end(error));
222
+ this.worker.on("exit", (code) => this.end(new ConnectionThreadEndedError(`SQLite connection thread exited with code ${code}`)));
223
+ }
224
+ /**
225
+ * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure
226
+ * to start the thread or to open the database rejects with its cause; the thread is gone then.
227
+ */
228
+ static async open(path, options) {
229
+ const connection = new ThreadConnection();
230
+ try {
231
+ const location = await connection.request({
232
+ kind: "open",
233
+ path: options.openAs ?? path,
234
+ readOnly: options.readOnly,
235
+ });
236
+ return { connection, location: typeof location === "string" ? location : null };
237
+ }
238
+ catch (error) {
239
+ await connection.stop();
240
+ throw error;
241
+ }
242
+ }
243
+ /**
244
+ * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request
245
+ * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the
246
+ * calling thread would not.
247
+ */
248
+ request(request) {
249
+ if (request.kind === "close")
250
+ return this.close();
251
+ const answer = this.send(request);
252
+ if (request.kind === "get")
253
+ return answer.then((value) => (value === undefined ? undefined : rowsOf(value)[0]));
254
+ if (request.kind === "all")
255
+ return answer.then((value) => rowsOf(value));
256
+ return answer;
257
+ }
258
+ send(request) {
259
+ return new Promise((resolve, reject) => {
260
+ if (this.ended !== undefined) {
261
+ reject(this.ended);
262
+ return;
263
+ }
264
+ const id = this.nextId++;
265
+ try {
266
+ this.worker.postMessage({ id, ...request });
267
+ }
268
+ catch (error) {
269
+ // A value the thread cannot receive.
270
+ reject(error);
271
+ return;
272
+ }
273
+ this.waiting.set(id, { resolve, reject });
274
+ if (this.waiting.size === 1)
275
+ this.worker.ref();
276
+ });
277
+ }
278
+ /**
279
+ * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A
280
+ * thread already lost has nothing to close.
281
+ */
282
+ close() {
283
+ this.closing ??= (async () => {
284
+ try {
285
+ if (this.ended === undefined)
286
+ await this.send({ kind: "close" });
287
+ }
288
+ finally {
289
+ await this.stop();
290
+ }
291
+ return undefined;
292
+ })();
293
+ return this.closing;
294
+ }
295
+ receive(reply) {
296
+ const waiter = this.waiting.get(reply.id);
297
+ if (waiter === undefined)
298
+ return;
299
+ this.waiting.delete(reply.id);
300
+ if (this.waiting.size === 0)
301
+ this.worker.unref();
302
+ if (reply.failure === undefined)
303
+ waiter.resolve(reply.value);
304
+ else
305
+ waiter.reject(connectionError(reply.failure));
306
+ }
307
+ /** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */
308
+ end(cause) {
309
+ if (this.ended !== undefined)
310
+ return;
311
+ // Kept for as long as the connection is: an error's stack, until formatted, keeps the functions of the frames it
312
+ // names, and so whatever they hold, such as a session that closed its store.
313
+ void cause.stack;
314
+ this.ended = cause;
315
+ const waiting = [...this.waiting.values()];
316
+ this.waiting.clear();
317
+ this.worker.unref();
318
+ for (const waiter of waiting)
319
+ waiter.reject(cause);
320
+ }
321
+ async stop() {
322
+ this.end(new ConnectionThreadEndedError("SQLite connection closed"));
323
+ await this.worker.terminate();
324
+ }
325
+ }
326
+ //# sourceMappingURL=node-sqlite-thread.js.map
@@ -0,0 +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;AAE7C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgIzB,CAAC;AAoDF,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,kHAAkH;AAClH,SAAS,YAAY;IACpB,OAAO,GAAG,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;AAC/D,CAAC;AAED,SAAS,gBAAgB,CAAC,IAAsB,EAAE,OAAkD;IACnG,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC;QAC1B,IAAI,CAAC,IAAI;QACT,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,UAAU,CAAC,CAAC;QACtF,OAAO,CAAC,QAAQ;KAChB,CAAC,CAAC;IACH,IAAI,SAAS,GAAG,iBAAiB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC3C,IAAI,SAAS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AC;QACrE,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;IAC/B,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport type { SqliteRow, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.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 = `\nconst { parentPort, workerData } = require(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = require(\"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\nfunction statement(sql) {\n\tconst prepared = database.prepare(sql);\n\tprepared.setReadBigInts(true);\n\treturn prepared;\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// One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.\n\tbegin: () => {\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\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\tdatabase?.close();\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\nparentPort.on(\"message\", (request) => {\n\ttry {\n\t\tparentPort.postMessage({ id: request.id, value: handlers[request.kind](request) });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: request.id, failure: failure(error) });\n\t}\n});\n`;\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\" | \"dataVersion\" | \"now\" | \"jsonbExtract\" | \"close\" };\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 = RowTable | { readonly changes: number } | string | number | boolean | null | undefined;\n\n/**\n * What a request is answered with: `get` a row or undefined, `all` rows, `run` the changes, `open` the location,\n * `dataVersion` and `now` a number, `jsonbExtract` a boolean, the others undefined.\n */\nexport type ConnectionAnswer =\n\t| SqliteRow\n\t| SqliteRow[]\n\t| { readonly changes: number }\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/** 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: an `--input-type=module` would make this CommonJS source a module, and the\n\t\t// caller's preloads would run again for every connection. 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` },\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 connection = new ThreadConnection();\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\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"]}
@@ -1 +1 @@
1
- {"version":3,"file":"node-sqlite.d.ts","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAIhD,OAAO,KAAK,EACX,cAAc,EAMd,MAAM,eAAe,CAAC;AAEvB,OAAO,EAaN,+BAA+B,EAI/B,MAAM,aAAa,CAAC;AAkmBrB,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAE/D;AAwWD;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,MAAM,CAAC;AA0BhD,mHAAmH;AACnH,MAAM,WAAW,gBAAgB;IAChC,sHAAsH;IACtH,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,oHAAoH;IACpH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,wGAAwG;IACxG,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,0FAA0F;IAC1F,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,6DAA6D;IAC7D,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;CAClC;AA+xBD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,MAAM,CAGjG;AAED,2GAA2G;AAC3G,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,CAAC,GAAG,CAAC,CAK1E;AAiBD,wBAAsB,sBAA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