@shware/workflow 5.0.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (487) hide show
  1. package/README.md +165 -42
  2. package/dist/_virtual/_rolldown/runtime.cjs +1 -2
  3. package/dist/apns-relay.cjs +1 -2
  4. package/dist/apns-relay.d.cts +0 -2
  5. package/dist/apns-relay.d.cts.map +1 -1
  6. package/dist/apns-relay.d.mts +0 -2
  7. package/dist/apns-relay.d.mts.map +1 -1
  8. package/dist/apns-relay.mjs +1 -2
  9. package/dist/apns.cjs +1 -2
  10. package/dist/apns.d.cts +0 -2
  11. package/dist/apns.d.cts.map +1 -1
  12. package/dist/apns.d.mts +0 -2
  13. package/dist/apns.d.mts.map +1 -1
  14. package/dist/apns.mjs +1 -2
  15. package/dist/aws/engine-step.cjs +1 -2
  16. package/dist/aws/engine-step.d.cts +0 -2
  17. package/dist/aws/engine-step.d.cts.map +1 -1
  18. package/dist/aws/engine-step.d.mts +0 -2
  19. package/dist/aws/engine-step.d.mts.map +1 -1
  20. package/dist/aws/engine-step.mjs +1 -2
  21. package/dist/aws/function-url.cjs +1 -2
  22. package/dist/aws/function-url.d.cts +0 -2
  23. package/dist/aws/function-url.d.cts.map +1 -1
  24. package/dist/aws/function-url.d.mts +0 -2
  25. package/dist/aws/function-url.d.mts.map +1 -1
  26. package/dist/aws/function-url.mjs +1 -2
  27. package/dist/aws/index.cjs +2 -3
  28. package/dist/aws/index.d.cts +0 -2
  29. package/dist/aws/index.d.cts.map +1 -1
  30. package/dist/aws/index.d.mts +0 -2
  31. package/dist/aws/index.d.mts.map +1 -1
  32. package/dist/aws/index.mjs +2 -3
  33. package/dist/aws/instances.cjs +1 -2
  34. package/dist/aws/instances.d.cts +0 -2
  35. package/dist/aws/instances.d.cts.map +1 -1
  36. package/dist/aws/instances.d.mts +0 -2
  37. package/dist/aws/instances.d.mts.map +1 -1
  38. package/dist/aws/instances.mjs +1 -2
  39. package/dist/aws/lambda-api.cjs +1 -2
  40. package/dist/aws/lambda-api.d.cts +0 -2
  41. package/dist/aws/lambda-api.d.cts.map +1 -1
  42. package/dist/aws/lambda-api.d.mts +0 -2
  43. package/dist/aws/lambda-api.d.mts.map +1 -1
  44. package/dist/aws/lambda-api.mjs +1 -2
  45. package/dist/client.cjs +46 -6
  46. package/dist/client.cjs.map +1 -1
  47. package/dist/client.d.cts +25 -5
  48. package/dist/client.d.cts.map +1 -1
  49. package/dist/client.d.mts +25 -5
  50. package/dist/client.d.mts.map +1 -1
  51. package/dist/client.mjs +46 -6
  52. package/dist/client.mjs.map +1 -1
  53. package/dist/cloudflare/bindings.cjs +1 -2
  54. package/dist/cloudflare/bindings.d.cts +0 -2
  55. package/dist/cloudflare/bindings.d.cts.map +1 -1
  56. package/dist/cloudflare/bindings.d.mts +0 -2
  57. package/dist/cloudflare/bindings.d.mts.map +1 -1
  58. package/dist/cloudflare/bindings.mjs +1 -2
  59. package/dist/cloudflare/index.cjs +2 -2
  60. package/dist/cloudflare/index.mjs +2 -2
  61. package/dist/cloudflare/runner.cjs +2 -3
  62. package/dist/cloudflare/runner.d.cts +1 -3
  63. package/dist/cloudflare/runner.d.cts.map +1 -1
  64. package/dist/cloudflare/runner.d.mts +1 -3
  65. package/dist/cloudflare/runner.d.mts.map +1 -1
  66. package/dist/cloudflare/runner.mjs +2 -3
  67. package/dist/cloudflare/worker.cjs +1 -2
  68. package/dist/cloudflare/worker.d.cts +0 -2
  69. package/dist/cloudflare/worker.d.cts.map +1 -1
  70. package/dist/cloudflare/worker.d.mts +0 -2
  71. package/dist/cloudflare/worker.d.mts.map +1 -1
  72. package/dist/cloudflare/worker.mjs +1 -2
  73. package/dist/cloudflare/workers.d.cts +0 -2
  74. package/dist/cloudflare/workers.d.cts.map +1 -1
  75. package/dist/cloudflare/workers.d.mts +0 -2
  76. package/dist/cloudflare/workers.d.mts.map +1 -1
  77. package/dist/config.cjs +25 -5
  78. package/dist/config.cjs.map +1 -1
  79. package/dist/config.d.cts +15 -11
  80. package/dist/config.d.cts.map +1 -1
  81. package/dist/config.d.mts +15 -11
  82. package/dist/config.d.mts.map +1 -1
  83. package/dist/config.mjs +26 -6
  84. package/dist/config.mjs.map +1 -1
  85. package/dist/contract.cjs +12 -2
  86. package/dist/contract.cjs.map +1 -1
  87. package/dist/contract.d.cts +28 -9
  88. package/dist/contract.d.cts.map +1 -1
  89. package/dist/contract.d.mts +28 -9
  90. package/dist/contract.d.mts.map +1 -1
  91. package/dist/contract.mjs +12 -2
  92. package/dist/contract.mjs.map +1 -1
  93. package/dist/dsl/action.cjs +1 -2
  94. package/dist/dsl/action.d.cts +0 -2
  95. package/dist/dsl/action.d.cts.map +1 -1
  96. package/dist/dsl/action.d.mts +0 -2
  97. package/dist/dsl/action.d.mts.map +1 -1
  98. package/dist/dsl/action.mjs +1 -2
  99. package/dist/dsl/base.cjs +1 -2
  100. package/dist/dsl/base.d.cts +0 -2
  101. package/dist/dsl/base.d.cts.map +1 -1
  102. package/dist/dsl/base.d.mts +0 -2
  103. package/dist/dsl/base.d.mts.map +1 -1
  104. package/dist/dsl/base.mjs +1 -2
  105. package/dist/dsl/bundle.cjs +5 -5
  106. package/dist/dsl/bundle.cjs.map +1 -1
  107. package/dist/dsl/bundle.d.cts +5 -3
  108. package/dist/dsl/bundle.d.cts.map +1 -1
  109. package/dist/dsl/bundle.d.mts +5 -3
  110. package/dist/dsl/bundle.d.mts.map +1 -1
  111. package/dist/dsl/bundle.mjs +5 -5
  112. package/dist/dsl/bundle.mjs.map +1 -1
  113. package/dist/dsl/condition.cjs +1 -2
  114. package/dist/dsl/condition.d.cts +0 -2
  115. package/dist/dsl/condition.d.cts.map +1 -1
  116. package/dist/dsl/condition.d.mts +0 -2
  117. package/dist/dsl/condition.d.mts.map +1 -1
  118. package/dist/dsl/condition.mjs +1 -2
  119. package/dist/dsl/flow.cjs +3 -3
  120. package/dist/dsl/flow.cjs.map +1 -1
  121. package/dist/dsl/flow.d.cts +1 -3
  122. package/dist/dsl/flow.d.cts.map +1 -1
  123. package/dist/dsl/flow.d.mts +1 -3
  124. package/dist/dsl/flow.d.mts.map +1 -1
  125. package/dist/dsl/flow.mjs +3 -3
  126. package/dist/dsl/flow.mjs.map +1 -1
  127. package/dist/dsl/refs.cjs +1 -2
  128. package/dist/dsl/refs.d.cts +0 -2
  129. package/dist/dsl/refs.d.cts.map +1 -1
  130. package/dist/dsl/refs.d.mts +0 -2
  131. package/dist/dsl/refs.d.mts.map +1 -1
  132. package/dist/dsl/refs.mjs +1 -2
  133. package/dist/dsl/template.cjs +1 -2
  134. package/dist/dsl/template.d.cts +0 -2
  135. package/dist/dsl/template.d.cts.map +1 -1
  136. package/dist/dsl/template.d.mts +0 -2
  137. package/dist/dsl/template.d.mts.map +1 -1
  138. package/dist/dsl/template.mjs +1 -2
  139. package/dist/dsl/trigger.cjs +1 -2
  140. package/dist/dsl/trigger.d.cts +0 -2
  141. package/dist/dsl/trigger.d.cts.map +1 -1
  142. package/dist/dsl/trigger.d.mts +0 -2
  143. package/dist/dsl/trigger.d.mts.map +1 -1
  144. package/dist/dsl/trigger.mjs +1 -2
  145. package/dist/dsl/workflow.cjs +3 -4
  146. package/dist/dsl/workflow.d.cts +0 -2
  147. package/dist/dsl/workflow.d.cts.map +1 -1
  148. package/dist/dsl/workflow.d.mts +0 -2
  149. package/dist/dsl/workflow.d.mts.map +1 -1
  150. package/dist/dsl/workflow.mjs +3 -4
  151. package/dist/email-context.cjs +1 -2
  152. package/dist/email-context.d.cts +0 -2
  153. package/dist/email-context.d.cts.map +1 -1
  154. package/dist/email-context.d.mts +0 -2
  155. package/dist/email-context.d.mts.map +1 -1
  156. package/dist/email-context.mjs +1 -2
  157. package/dist/email-sender.cjs +2 -3
  158. package/dist/email-sender.cjs.map +1 -1
  159. package/dist/email-sender.d.cts +1 -3
  160. package/dist/email-sender.d.cts.map +1 -1
  161. package/dist/email-sender.d.mts +1 -3
  162. package/dist/email-sender.d.mts.map +1 -1
  163. package/dist/email-sender.mjs +2 -3
  164. package/dist/email-sender.mjs.map +1 -1
  165. package/dist/email.cjs +33 -7
  166. package/dist/email.cjs.map +1 -1
  167. package/dist/email.d.cts +38 -11
  168. package/dist/email.d.cts.map +1 -1
  169. package/dist/email.d.mts +38 -11
  170. package/dist/email.d.mts.map +1 -1
  171. package/dist/email.mjs +33 -8
  172. package/dist/email.mjs.map +1 -1
  173. package/dist/engine/actions.cjs +1 -2
  174. package/dist/engine/actions.d.cts +0 -2
  175. package/dist/engine/actions.d.cts.map +1 -1
  176. package/dist/engine/actions.d.mts +0 -2
  177. package/dist/engine/actions.d.mts.map +1 -1
  178. package/dist/engine/actions.mjs +1 -2
  179. package/dist/engine/bucket.cjs +1 -2
  180. package/dist/engine/bucket.d.cts +0 -2
  181. package/dist/engine/bucket.d.cts.map +1 -1
  182. package/dist/engine/bucket.d.mts +0 -2
  183. package/dist/engine/bucket.d.mts.map +1 -1
  184. package/dist/engine/bucket.mjs +1 -2
  185. package/dist/engine/condition.cjs +1 -2
  186. package/dist/engine/condition.cjs.map +1 -1
  187. package/dist/engine/condition.d.cts +0 -2
  188. package/dist/engine/condition.d.cts.map +1 -1
  189. package/dist/engine/condition.d.mts +0 -2
  190. package/dist/engine/condition.d.mts.map +1 -1
  191. package/dist/engine/condition.mjs +1 -2
  192. package/dist/engine/condition.mjs.map +1 -1
  193. package/dist/engine/duration.cjs +1 -2
  194. package/dist/engine/duration.d.cts +0 -2
  195. package/dist/engine/duration.d.cts.map +1 -1
  196. package/dist/engine/duration.d.mts +0 -2
  197. package/dist/engine/duration.d.mts.map +1 -1
  198. package/dist/engine/duration.mjs +1 -2
  199. package/dist/engine/index.cjs +1 -1
  200. package/dist/engine/index.mjs +1 -1
  201. package/dist/engine/interpreter.cjs +22 -6
  202. package/dist/engine/interpreter.cjs.map +1 -1
  203. package/dist/engine/interpreter.d.cts +0 -2
  204. package/dist/engine/interpreter.d.cts.map +1 -1
  205. package/dist/engine/interpreter.d.mts +0 -2
  206. package/dist/engine/interpreter.d.mts.map +1 -1
  207. package/dist/engine/interpreter.mjs +22 -6
  208. package/dist/engine/interpreter.mjs.map +1 -1
  209. package/dist/engine/ports.d.cts +8 -4
  210. package/dist/engine/ports.d.cts.map +1 -1
  211. package/dist/engine/ports.d.mts +8 -4
  212. package/dist/engine/ports.d.mts.map +1 -1
  213. package/dist/engine/recipient.cjs +1 -2
  214. package/dist/engine/recipient.d.cts +0 -2
  215. package/dist/engine/recipient.d.cts.map +1 -1
  216. package/dist/engine/recipient.d.mts +0 -2
  217. package/dist/engine/recipient.d.mts.map +1 -1
  218. package/dist/engine/recipient.mjs +1 -2
  219. package/dist/engine/retry.cjs +1 -2
  220. package/dist/engine/retry.d.cts +0 -2
  221. package/dist/engine/retry.d.cts.map +1 -1
  222. package/dist/engine/retry.d.mts +0 -2
  223. package/dist/engine/retry.d.mts.map +1 -1
  224. package/dist/engine/retry.mjs +1 -2
  225. package/dist/engine/time-scale.cjs +1 -2
  226. package/dist/engine/time-scale.d.cts +0 -2
  227. package/dist/engine/time-scale.d.cts.map +1 -1
  228. package/dist/engine/time-scale.d.mts +0 -2
  229. package/dist/engine/time-scale.d.mts.map +1 -1
  230. package/dist/engine/time-scale.mjs +1 -2
  231. package/dist/engine/time-window.cjs +1 -2
  232. package/dist/engine/time-window.d.cts +0 -2
  233. package/dist/engine/time-window.d.cts.map +1 -1
  234. package/dist/engine/time-window.d.mts +0 -2
  235. package/dist/engine/time-window.d.mts.map +1 -1
  236. package/dist/engine/time-window.mjs +1 -2
  237. package/dist/fcm.cjs +1 -2
  238. package/dist/fcm.d.cts +0 -2
  239. package/dist/fcm.d.cts.map +1 -1
  240. package/dist/fcm.d.mts +0 -2
  241. package/dist/fcm.d.mts.map +1 -1
  242. package/dist/fcm.mjs +1 -2
  243. package/dist/hash.cjs +1 -2
  244. package/dist/hash.d.cts +0 -2
  245. package/dist/hash.d.cts.map +1 -1
  246. package/dist/hash.d.mts +0 -2
  247. package/dist/hash.d.mts.map +1 -1
  248. package/dist/hash.mjs +1 -2
  249. package/dist/host/auth.cjs +1 -2
  250. package/dist/host/auth.d.cts +0 -2
  251. package/dist/host/auth.d.cts.map +1 -1
  252. package/dist/host/auth.d.mts +0 -2
  253. package/dist/host/auth.d.mts.map +1 -1
  254. package/dist/host/auth.mjs +1 -2
  255. package/dist/host/channels.cjs +2 -3
  256. package/dist/host/channels.d.cts +0 -2
  257. package/dist/host/channels.d.cts.map +1 -1
  258. package/dist/host/channels.d.mts +0 -2
  259. package/dist/host/channels.d.mts.map +1 -1
  260. package/dist/host/channels.mjs +2 -3
  261. package/dist/host/execute.cjs +3 -4
  262. package/dist/host/execute.d.cts +1 -3
  263. package/dist/host/execute.d.cts.map +1 -1
  264. package/dist/host/execute.d.mts +1 -3
  265. package/dist/host/execute.d.mts.map +1 -1
  266. package/dist/host/execute.mjs +3 -4
  267. package/dist/host/fresh-read.cjs +1 -2
  268. package/dist/host/fresh-read.d.cts +0 -2
  269. package/dist/host/fresh-read.d.cts.map +1 -1
  270. package/dist/host/fresh-read.d.mts +0 -2
  271. package/dist/host/fresh-read.d.mts.map +1 -1
  272. package/dist/host/fresh-read.mjs +1 -2
  273. package/dist/host/http.cjs +39 -5
  274. package/dist/host/http.cjs.map +1 -1
  275. package/dist/host/http.d.cts +2 -4
  276. package/dist/host/http.d.cts.map +1 -1
  277. package/dist/host/http.d.mts +2 -4
  278. package/dist/host/http.d.mts.map +1 -1
  279. package/dist/host/http.mjs +40 -6
  280. package/dist/host/http.mjs.map +1 -1
  281. package/dist/host/ingest.cjs +129 -6
  282. package/dist/host/ingest.cjs.map +1 -1
  283. package/dist/host/ingest.d.cts +71 -2
  284. package/dist/host/ingest.d.cts.map +1 -1
  285. package/dist/host/ingest.d.mts +71 -2
  286. package/dist/host/ingest.d.mts.map +1 -1
  287. package/dist/host/ingest.mjs +126 -7
  288. package/dist/host/ingest.mjs.map +1 -1
  289. package/dist/host/journey-host.cjs +11 -10
  290. package/dist/host/journey-host.cjs.map +1 -1
  291. package/dist/host/journey-host.d.cts +0 -2
  292. package/dist/host/journey-host.d.cts.map +1 -1
  293. package/dist/host/journey-host.d.mts +0 -2
  294. package/dist/host/journey-host.d.mts.map +1 -1
  295. package/dist/host/journey-host.mjs +11 -10
  296. package/dist/host/journey-host.mjs.map +1 -1
  297. package/dist/host/platform.cjs +1 -2
  298. package/dist/host/platform.d.cts +0 -2
  299. package/dist/host/platform.d.cts.map +1 -1
  300. package/dist/host/platform.d.mts +0 -2
  301. package/dist/host/platform.d.mts.map +1 -1
  302. package/dist/host/platform.mjs +1 -2
  303. package/dist/host/senders.cjs +1 -2
  304. package/dist/host/senders.d.cts +0 -2
  305. package/dist/host/senders.d.cts.map +1 -1
  306. package/dist/host/senders.d.mts +0 -2
  307. package/dist/host/senders.d.mts.map +1 -1
  308. package/dist/host/senders.mjs +1 -2
  309. package/dist/http2-client.cjs +1 -2
  310. package/dist/http2-client.d.cts +0 -2
  311. package/dist/http2-client.d.cts.map +1 -1
  312. package/dist/http2-client.d.mts +0 -2
  313. package/dist/http2-client.d.mts.map +1 -1
  314. package/dist/http2-client.mjs +1 -2
  315. package/dist/index.cjs +5 -2
  316. package/dist/index.d.cts +5 -5
  317. package/dist/index.d.mts +5 -5
  318. package/dist/index.mjs +5 -5
  319. package/dist/ir.cjs +12 -4
  320. package/dist/ir.cjs.map +1 -1
  321. package/dist/ir.d.cts +17 -2
  322. package/dist/ir.d.cts.map +1 -1
  323. package/dist/ir.d.mts +17 -2
  324. package/dist/ir.d.mts.map +1 -1
  325. package/dist/ir.mjs +12 -5
  326. package/dist/ir.mjs.map +1 -1
  327. package/dist/jwt.cjs +1 -2
  328. package/dist/jwt.d.cts +0 -2
  329. package/dist/jwt.d.cts.map +1 -1
  330. package/dist/jwt.d.mts +0 -2
  331. package/dist/jwt.d.mts.map +1 -1
  332. package/dist/jwt.mjs +1 -2
  333. package/dist/plan.cjs +1 -2
  334. package/dist/plan.d.cts +0 -2
  335. package/dist/plan.d.cts.map +1 -1
  336. package/dist/plan.d.mts +0 -2
  337. package/dist/plan.d.mts.map +1 -1
  338. package/dist/plan.mjs +1 -2
  339. package/dist/postgres-js.cjs +1 -2
  340. package/dist/postgres-js.d.cts +0 -2
  341. package/dist/postgres-js.d.cts.map +1 -1
  342. package/dist/postgres-js.d.mts +0 -2
  343. package/dist/postgres-js.d.mts.map +1 -1
  344. package/dist/postgres-js.mjs +1 -2
  345. package/dist/provenance.cjs +1 -2
  346. package/dist/provenance.d.cts +0 -2
  347. package/dist/provenance.d.cts.map +1 -1
  348. package/dist/provenance.d.mts +0 -2
  349. package/dist/provenance.d.mts.map +1 -1
  350. package/dist/provenance.mjs +1 -2
  351. package/dist/push.cjs +1 -2
  352. package/dist/push.d.cts +0 -2
  353. package/dist/push.d.cts.map +1 -1
  354. package/dist/push.d.mts +0 -2
  355. package/dist/push.d.mts.map +1 -1
  356. package/dist/push.mjs +1 -2
  357. package/dist/react-email.cjs +1 -2
  358. package/dist/react-email.d.cts +0 -2
  359. package/dist/react-email.d.cts.map +1 -1
  360. package/dist/react-email.d.mts +0 -2
  361. package/dist/react-email.d.mts.map +1 -1
  362. package/dist/react-email.mjs +1 -2
  363. package/dist/reporting/classify.cjs +1 -2
  364. package/dist/reporting/classify.d.cts +0 -2
  365. package/dist/reporting/classify.d.cts.map +1 -1
  366. package/dist/reporting/classify.d.mts +0 -2
  367. package/dist/reporting/classify.d.mts.map +1 -1
  368. package/dist/reporting/classify.mjs +1 -2
  369. package/dist/reporting/observer.cjs +2 -2
  370. package/dist/reporting/observer.cjs.map +1 -1
  371. package/dist/reporting/observer.d.cts +0 -2
  372. package/dist/reporting/observer.d.cts.map +1 -1
  373. package/dist/reporting/observer.d.mts +0 -2
  374. package/dist/reporting/observer.d.mts.map +1 -1
  375. package/dist/reporting/observer.mjs +2 -2
  376. package/dist/reporting/observer.mjs.map +1 -1
  377. package/dist/reporting/tracking.cjs +29 -12
  378. package/dist/reporting/tracking.cjs.map +1 -1
  379. package/dist/reporting/tracking.d.cts +13 -8
  380. package/dist/reporting/tracking.d.cts.map +1 -1
  381. package/dist/reporting/tracking.d.mts +13 -8
  382. package/dist/reporting/tracking.d.mts.map +1 -1
  383. package/dist/reporting/tracking.mjs +29 -12
  384. package/dist/reporting/tracking.mjs.map +1 -1
  385. package/dist/runtime.cjs +1 -2
  386. package/dist/runtime.d.cts +0 -2
  387. package/dist/runtime.d.cts.map +1 -1
  388. package/dist/runtime.d.mts +0 -2
  389. package/dist/runtime.d.mts.map +1 -1
  390. package/dist/runtime.mjs +1 -2
  391. package/dist/store/erasure.cjs +1 -2
  392. package/dist/store/erasure.d.cts +0 -2
  393. package/dist/store/erasure.d.cts.map +1 -1
  394. package/dist/store/erasure.d.mts +0 -2
  395. package/dist/store/erasure.d.mts.map +1 -1
  396. package/dist/store/erasure.mjs +1 -2
  397. package/dist/store/facts.cjs +4 -5
  398. package/dist/store/facts.cjs.map +1 -1
  399. package/dist/store/facts.d.cts +2 -4
  400. package/dist/store/facts.d.cts.map +1 -1
  401. package/dist/store/facts.d.mts +2 -4
  402. package/dist/store/facts.d.mts.map +1 -1
  403. package/dist/store/facts.mjs +4 -5
  404. package/dist/store/facts.mjs.map +1 -1
  405. package/dist/store/index.cjs +2 -3
  406. package/dist/store/index.cjs.map +1 -1
  407. package/dist/store/index.d.cts +44 -15
  408. package/dist/store/index.d.cts.map +1 -1
  409. package/dist/store/index.d.mts +44 -15
  410. package/dist/store/index.d.mts.map +1 -1
  411. package/dist/store/index.mjs +2 -3
  412. package/dist/store/index.mjs.map +1 -1
  413. package/dist/store/postgres-reporting.cjs +31 -12
  414. package/dist/store/postgres-reporting.cjs.map +1 -1
  415. package/dist/store/postgres-reporting.d.cts +4 -4
  416. package/dist/store/postgres-reporting.d.cts.map +1 -1
  417. package/dist/store/postgres-reporting.d.mts +4 -4
  418. package/dist/store/postgres-reporting.d.mts.map +1 -1
  419. package/dist/store/postgres-reporting.mjs +31 -12
  420. package/dist/store/postgres-reporting.mjs.map +1 -1
  421. package/dist/store/postgres.cjs +40 -5
  422. package/dist/store/postgres.cjs.map +1 -1
  423. package/dist/store/postgres.d.cts +4 -4
  424. package/dist/store/postgres.d.cts.map +1 -1
  425. package/dist/store/postgres.d.mts +4 -4
  426. package/dist/store/postgres.d.mts.map +1 -1
  427. package/dist/store/postgres.mjs +41 -6
  428. package/dist/store/postgres.mjs.map +1 -1
  429. package/dist/store/sql.cjs +1 -2
  430. package/dist/store/sql.d.cts +0 -2
  431. package/dist/store/sql.d.cts.map +1 -1
  432. package/dist/store/sql.d.mts +0 -2
  433. package/dist/store/sql.d.mts.map +1 -1
  434. package/dist/store/sql.mjs +1 -2
  435. package/dist/store/tables.cjs +76 -13
  436. package/dist/store/tables.cjs.map +1 -1
  437. package/dist/store/tables.d.cts +17 -3
  438. package/dist/store/tables.d.cts.map +1 -1
  439. package/dist/store/tables.d.mts +17 -3
  440. package/dist/store/tables.d.mts.map +1 -1
  441. package/dist/store/tables.mjs +75 -14
  442. package/dist/store/tables.mjs.map +1 -1
  443. package/dist/store/user-lock.cjs +1 -2
  444. package/dist/store/user-lock.d.cts +0 -2
  445. package/dist/store/user-lock.d.cts.map +1 -1
  446. package/dist/store/user-lock.d.mts +0 -2
  447. package/dist/store/user-lock.d.mts.map +1 -1
  448. package/dist/store/user-lock.mjs +1 -2
  449. package/dist/templates.cjs +61 -9
  450. package/dist/templates.cjs.map +1 -1
  451. package/dist/templates.d.cts +101 -15
  452. package/dist/templates.d.cts.map +1 -1
  453. package/dist/templates.d.mts +101 -15
  454. package/dist/templates.d.mts.map +1 -1
  455. package/dist/templates.mjs +62 -11
  456. package/dist/templates.mjs.map +1 -1
  457. package/dist/transports/cloudflare-email.cjs +1 -2
  458. package/dist/transports/cloudflare-email.d.cts +0 -2
  459. package/dist/transports/cloudflare-email.d.cts.map +1 -1
  460. package/dist/transports/cloudflare-email.d.mts +0 -2
  461. package/dist/transports/cloudflare-email.d.mts.map +1 -1
  462. package/dist/transports/cloudflare-email.mjs +1 -2
  463. package/dist/transports/ses.cjs +1 -2
  464. package/dist/transports/ses.d.cts +0 -2
  465. package/dist/transports/ses.d.cts.map +1 -1
  466. package/dist/transports/ses.d.mts +0 -2
  467. package/dist/transports/ses.d.mts.map +1 -1
  468. package/dist/transports/ses.mjs +1 -2
  469. package/dist/transports/sigv4.cjs +1 -2
  470. package/dist/transports/sigv4.d.cts +0 -2
  471. package/dist/transports/sigv4.d.cts.map +1 -1
  472. package/dist/transports/sigv4.d.mts +0 -2
  473. package/dist/transports/sigv4.d.mts.map +1 -1
  474. package/dist/transports/sigv4.mjs +1 -2
  475. package/dist/webhooks.cjs +1 -2
  476. package/dist/webhooks.d.cts +0 -2
  477. package/dist/webhooks.d.cts.map +1 -1
  478. package/dist/webhooks.d.mts +0 -2
  479. package/dist/webhooks.d.mts.map +1 -1
  480. package/dist/webhooks.mjs +1 -2
  481. package/dist/webpush.cjs +1 -2
  482. package/dist/webpush.d.cts +0 -2
  483. package/dist/webpush.d.cts.map +1 -1
  484. package/dist/webpush.d.mts +0 -2
  485. package/dist/webpush.d.mts.map +1 -1
  486. package/dist/webpush.mjs +1 -2
  487. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../../src/store/index.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport type { BundleIR, ConditionIR, ScalarIR, WorkflowIR } from '../ir';\n\n/**\n * The journey engine's data plane. Postgres is the store (`PostgresJourneyStore`); this\n * interface is the port the host, the runner and the fact source use to persist or look\n * anything up, and what a test stub implements in its place. Execution (durable steps,\n * sleeps, wake-ups) is the workflow runtime's job and stays out of here.\n *\n * Timestamps are epoch milliseconds throughout; a store may persist them in\n * its native type as long as `sinceMs` comparisons behave.\n */\n\n/**\n * A profile patch or a stored profile. On the way in, `null` means \"remove\n * this property\" (RFC 7386 merge-patch, the only way the API has to unset\n * one); a stored profile never contains null.\n */\nexport type ProfileProps = Record<string, ScalarIR | null | undefined>;\n\nexport interface EventInput {\n /** The occurrence's identity, chosen by the sender; a second insert with the same id is a no-op. */\n id: string;\n userId: string;\n event: string;\n ts: number;\n payload: Record<string, unknown>;\n}\n\nexport interface TriggerRoute {\n workflow: string;\n hash: string;\n /** Payload gate (payload-only condition tree), or null when the trigger has none. */\n where: ConditionIR | null;\n /** Profile gate, or null. */\n filter: ConditionIR | null;\n /**\n * The code version that applied these routes (`replaceRoutesIfNewer`); absent after a forced\n * deploy. Read in the same row as the hash, so the pair is always one deploy's.\n */\n version?: string | undefined;\n}\n\nexport interface SegmentTriggerRoute {\n workflow: string;\n hash: string;\n segment: string;\n /** As `TriggerRoute.version`. */\n version?: string | undefined;\n}\n\n/**\n * A Worker version, as Cloudflare's version metadata binding names it: the bundle compiled into\n * that version goes live only over an older one (`replaceRoutesIfNewer`).\n */\nexport interface BundleVersion {\n id: string;\n /** When the version was created (epoch ms): later versions are newer. */\n createdAt: number;\n}\n\nexport interface EntryInput {\n workflow: string;\n userId: string;\n instanceId: string;\n hash: string;\n ts: number;\n /**\n * The instance's start, recorded in the same transaction as the entry — for a runtime whose\n * start is an asynchronous submit (AWS) that may have to be retried.\n */\n execution?: ExecutionStart | undefined;\n}\n\n/** How an instance is started on a runtime that submits it: replayed as is on every retry. */\nexport interface ExecutionStart {\n /** The runtime's idempotency key (the durable execution name). */\n name: string;\n /** What is invoked: a qualified function ARN, its version included. */\n target: string;\n /** The exact payload: a retried submit must send the same bytes, or the runtime refuses it. */\n input: string;\n}\n\nexport interface ExecutionRecord extends ExecutionStart {\n instanceId: string;\n workflow: string;\n userId: string;\n createdAt: number;\n submittedAt?: number | undefined;\n arn?: string | undefined;\n unresolvedAt?: number | undefined;\n callbackId?: string | undefined;\n /** Bumped by every wait the instance arms: a wake or a cleanup of an older one leaves it alone. */\n generation: number;\n deadlineAt?: number | undefined;\n checkedAt?: number | undefined;\n stoppedAt?: number | undefined;\n}\n\n/**\n * What a runtime that submits its starts and parks waits on one-shot callbacks (AWS) keeps\n * beside the entry ledger. The runtime holds the execution history; this holds only the\n * mapping from the engine's instance id to it.\n */\nexport interface ExecutionRegistry {\n get(instanceId: string): Promise<ExecutionRecord | undefined>;\n /**\n * Starts not yet confirmed and not given up on, oldest first: of one (workflow, user) entry\n * still running, or every one created before `createdBefore`.\n */\n pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]>;\n markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void>;\n markUnresolved(instanceId: string, at: number): Promise<void>;\n setArn(instanceId: string, arn: string): Promise<void>;\n /** Record the callback a wait parks on; false when a newer generation is already armed. */\n armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean>;\n /** Forget the callback — only if it is still that generation's. */\n clearCallback(instanceId: string, generation: number): Promise<void>;\n /** Submitted executions whose entry is still running, least recently checked first. */\n toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]>;\n markChecked(instanceId: string, at: number): Promise<void>;\n /** Record the first stop; a later one keeps it. */\n markStopped(instanceId: string, at: number): Promise<void>;\n}\n\n/**\n * How an entry attempt ended: a fresh row, a 'failed' row of a dead instance\n * taken over (the once policy does not bar a user over one outage), or\n * refused because the pair already entered and is still alive.\n */\nexport type EntryOutcome = 'entered' | 'reclaimed' | null;\n\n/** A device registered for pushes: its provider token belongs to the user who registered it last. */\nexport interface DeviceInput {\n userId: string;\n token: string;\n /** `ios` (APNs) or `android` (FCM): which provider the token belongs to. */\n platform: string;\n ts: number;\n}\n\n/** An instance of a user still in the ledger, and whether its runner was admitted (see `admitInstance`). */\nexport interface RunningInstance {\n instanceId: string;\n /** False until the runner admitted itself: nothing has run, and the tombstone keeps it that way. */\n admitted: boolean;\n}\n\n/** A store plus how to release what opening it acquired (a connection, say). */\nexport interface StoreLease {\n store: JourneyStore;\n close?: () => Promise<void>;\n}\n\nimport type { ErasureState } from './erasure';\n\nexport { type ErasureState, UserErasedError } from './erasure';\n\n/**\n * The live database lacks tables or columns the engine reads (an SDK upgrade added them, or the\n * host never ran the migration). Raised before a deploy writes anything.\n */\nexport class SchemaMismatchError extends Error {\n override readonly name = 'SchemaMismatchError';\n\n constructor(readonly problems: readonly string[]) {\n super(\n `the database does not match @shware/workflow's tables — regenerate the drizzle schema (workflow-ui generate) and run your migrations:\\n ${problems.join('\\n ')}`\n );\n }\n}\n\n/** A message copy as reporting records it, before it goes out. */\nexport interface MessageRecord {\n idempotencyKey: string;\n workflow: string;\n instanceId: string;\n nodeId: string;\n template: string;\n /** Where the copy lands: `email`, `push_ios`, `push_android`. */\n channel: string;\n userId: string;\n sentAt: number;\n}\n\n/** What a click is judged by. */\nexport interface ClickContext {\n url: string;\n deliveredAt: number;\n linkCount: number;\n /** The copy's clicks in the window before this one. */\n recent: { position: number; at: number }[];\n}\n\n/** An open or a click, with the verdict on who made it and where it came from. */\nexport interface Engagement {\n at: number;\n machine: boolean;\n /** The rule that called it a machine; null for a person. */\n reason: string | null;\n userAgent: string | null;\n /** The network the request came from (Cloudflare's `cf.asn`, `cf.asOrganization`, `cf.country`), never the address. */\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\n/**\n * Journey reporting: where each instance stands, every copy and how it was engaged with, segment\n * sizes. The store exposes it as `reporting`; the host records it and serves email tracking.\n * Every write is idempotent — a retried step reports again.\n */\n/** Bounds on when an event happened, both inclusive (epoch ms); an absent side is open. */\nexport interface EventWindow {\n sinceMs?: number;\n untilMs?: number;\n}\n\nexport interface JourneyReporting {\n /** The instance entered: its row exists from here, so one a guard ends at once still counts. */\n instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void>;\n nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void>;\n instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void>;\n /** The copy's row id; the row a retry already wrote, when there is one. */\n recordMessage(message: MessageRecord): Promise<string>;\n settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void>;\n /** An email's tracked links, in document order. */\n recordLinks(messageId: string, urls: readonly string[]): Promise<void>;\n /**\n * Record an open of the copy, judged by `judge` against the copy (its recipient and when it was\n * delivered — when it was sent, before the transport answered); `undefined` from the judge\n * records nothing. Read and written in one transaction. False for an unknown copy.\n */\n recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean>;\n /**\n * Record a click on the copy's link at `position`, judged by `judge` against the link, how\n * many links the copy has and its clicks of the last `windowMs`. The copy is locked for the\n * transaction, so clicks arriving together (a scanner following every link at once) are\n * judged one after another, each seeing the ones before. When the judge asks to `backdate`,\n * the window's earlier clicks are reclassified with this one's verdict. A click implies an\n * open. Undefined for an unknown link.\n */\n recordClick(\n messageId: string,\n position: number,\n at: number,\n windowMs: number,\n judge: (link: ClickContext) => { engagement: Engagement; backdate: boolean }\n ): Promise<{ url: string; engagement: Engagement } | undefined>;\n /**\n * The email copy's recipient opted out of email: recorded on the copy and as a suppression, in\n * one transaction, which also yields who the recipient is — so the caller acts on the\n * unsubscribe without a second read. Undefined for an unknown copy.\n */\n recordUnsubscribe(messageId: string, at: number): Promise<{ userId: string } | undefined>;\n /** A push copy the device reported it received. False for an unknown copy. */\n recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;\n /** Drop members of segments no longer deployed, then record every deployed segment's size. */\n snapshotSegments(at: number): Promise<{ segment: string; size: number }[]>;\n}\n\nexport interface JourneyStore {\n /** Where instances stand, every copy and its engagement, segment sizes. */\n readonly reporting: JourneyReporting;\n\n /**\n * Record that the user's data must go (a deleted account): the tombstone every write about\n * the user is conditional on, from here on and for good. Committed before anything is\n * stopped or erased, so an entry that got in before it is found by the erasure and none gets\n * in after it. Idempotent: a second request, or one for a user already erased, changes nothing.\n */\n requestErasure(userId: string, at: number): Promise<void>;\n /** Users whose erasure was requested and not carried out yet (`'erasing'`), oldest first. */\n pendingErasures(): Promise<string[]>;\n /**\n * Where the user stands: `'none'` (no tombstone), `'erasing'` (requested, their instances\n * being stopped, data still there) or `'erased'` (`forgetUser` went through). Both\n * tombstone states refuse every write about the user; the entry points read this for a fast\n * answer, and the store's conditional writes are the gate itself.\n */\n erasureState(userId: string): Promise<ErasureState>;\n /** The user's journey instances still running, by the entry ledger. */\n runningInstances(userId: string): Promise<RunningInstance[]>;\n /**\n * The runner's admission, before its first observable effect: records that the instance runs\n * (`admitted_at`, kept on replay) — unless the user has an erasure tombstone, in which case\n * nothing is recorded and the runner must not run. Mutually exclusive with `requestErasure`\n * and `forgetUser` for that user (Postgres: the user's advisory lock), so an erasure either\n * finds the instance admitted and stops it, or commits its tombstone first and the admission\n * is refused — never neither.\n *\n * A first admission needs the entry running. An instance already admitted is admitted again\n * whatever the entry's status — the legitimate replay of an instance whose finalisation was\n * cut short after the entry reached its terminal status, which resumes on its own checkpoint\n * and finishes what is left. Never a new attempt's way in: false for a terminal entry never\n * admitted, for an entry no longer in the ledger, for another user's entry, and for an\n * instance whose entry was reclaimed since (`enterJourney` resets the admission with the\n * instance id, so a superseded attempt cannot pass under the id it lost).\n */\n admitInstance(instanceId: string, userId: string): Promise<boolean>;\n /**\n * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment\n * memberships, entries and reporting — and mark the tombstone erased (`erased_at`), which\n * stays: a write that was in flight when the data went cannot bring the user back, and the\n * same id is never reactivated by ingest. Suppressions stay too: an opt-out is a compliance\n * record keyed by an opaque id, and it outlives the erasure. Run only once no instance of\n * theirs runs any more, or one could write some of it back. Idempotent. Mutually exclusive\n * with every write about the user (the user's advisory lock), so\n * the data is gone when this returns — nothing of theirs lands afterwards.\n */\n forgetUser(userId: string, at: number): Promise<void>;\n\n /** The user opted out of the channel (recorded by an unsubscribe). */\n isSuppressed(userId: string, channel: string): Promise<boolean>;\n\n /**\n * What the live database lacks against the engine's tables (read-only); a deploy refuses to\n * run while it lists anything.\n */\n checkSchema(): Promise<string[]>;\n\n /* ---------------------------------- events --------------------------------- */\n /**\n * Append the occurrence; false when its id was already in the log (nothing written). Throws\n * `UserErasedError` for a user with a tombstone, like every write about a user below.\n */\n insertEvent(input: EventInput): Promise<boolean>;\n /** Occurrences of `event` for the user, optionally only those within the window. */\n countEvents(userId: string, event: string, window?: EventWindow): Promise<number>;\n /** The payloads of those occurrences — the caller filters them with the shared evaluator. */\n listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]>;\n\n /* --------------------------------- profiles -------------------------------- */\n getProfile(userId: string): Promise<ProfileProps | undefined>;\n /**\n * Merge-patch `props` into the stored profile in one statement (a null\n * removes the property) and return the result. One statement, because a\n * read-modify-write loses one of two concurrent identifies.\n */\n mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps>;\n\n /**\n * Every user the engine knows (a profile or an event): who the segment sweep evaluates. Ids\n * come in ascending order; `after` resumes past the last id of the previous page, and `limit`\n * bounds the page (the whole list without one).\n */\n listUserIds(page?: { after?: string | undefined; limit?: number | undefined }): Promise<string[]>;\n\n /* ---------------------------------- devices --------------------------------- */\n /** The user's push devices, most recently registered first. */\n listDevices(userId: string): Promise<PushDevice[]>;\n /**\n * Register a device: one row per token, so a token registered again moves to the user who\n * registered it last (a phone signed into another account) and to the front of their list.\n */\n upsertDevice(device: DeviceInput): Promise<void>;\n /** Forget a token (reported dead by APNs / FCM); the user it belonged to, if any. */\n removeDevice(token: string): Promise<string | undefined>;\n /**\n * The user signed out on the device: the token is kept, bound to nobody, until the next sign-in\n * binds it again. The user it belonged to, if any.\n */\n unbindDevice(token: string): Promise<string | undefined>;\n\n /* ---------------------------- deployed definitions -------------------------- */\n getSegmentCondition(id: string): Promise<ConditionIR | undefined>;\n /** Every deployed segment with its definition: what the segment sweep evaluates. */\n listSegments(): Promise<{ id: string; condition: ConditionIR }[]>;\n findTriggers(event: string): Promise<TriggerRoute[]>;\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]>;\n putWorkflowIR(workflow: WorkflowIR): Promise<void>;\n getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined>;\n /**\n * Swap the routing tables (segments, event triggers, segment triggers) for\n * the bundle's — atomically, so a concurrent ingest never sees them half\n * empty. Workflow bodies are stored separately (`putWorkflowIR`) because they\n * are content-addressed and outlive the routes that point at them.\n */\n replaceRoutes(bundle: BundleIR): Promise<void>;\n /**\n * The Worker version whose bundle the routes came from, when one put them there through\n * `replaceRoutesIfNewer` (a forced deploy leaves it as it was). Read from the database itself,\n * not a cache in front of it.\n */\n liveBundleVersion(): Promise<BundleVersion | undefined>;\n /**\n * `replaceRoutes`, only when `version` is newer than the live one, recorded in the same\n * transaction: two versions serving side by side during a rollout cannot leave the older one's\n * routes in force. False, with nothing written, when a version as new or newer is live.\n */\n replaceRoutesIfNewer(bundle: BundleIR, version: BundleVersion): Promise<boolean>;\n\n /* ----------------------------- segment membership --------------------------- */\n isSegmentMember(segment: string, userId: string): Promise<boolean>;\n /** Record the membership, with the workflows its entry has to start (see segment_start). */\n addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void>;\n /** The workflows the member's entry has not started yet. */\n pendingSegmentStarts(segment: string, userId: string): Promise<string[]>;\n completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void>;\n /** Drop the membership and any start it still owed. */\n removeSegmentMember(segment: string, userId: string): Promise<void>;\n\n /* ------------------------------- entry ledger ------------------------------- */\n /**\n * Record the entry (the once policy). Atomic under concurrent ingests: of\n * two racing attempts exactly one is 'entered' (or 'reclaimed', when the\n * pair's previous instance is recorded as 'failed') and the other null.\n */\n enterJourney(entry: EntryInput): Promise<EntryOutcome>;\n removeEntry(instanceId: string): Promise<void>;\n setEntryStatus(instanceId: string, status: string): Promise<void>;\n /** Execution starts and wake callbacks, for a runtime that submits its starts (AWS). */\n readonly executions: ExecutionRegistry;\n\n /* ------------------------------ wake subscriptions --------------------------- */\n /** Distinct wake handles registered for (user, event). */\n findWakeHandles(userId: string, event: string): Promise<string[]>;\n /** Register the handle for each event; repeated registrations are idempotent. */\n subscribe(handle: string, userId: string, events: readonly string[], ts: number): Promise<void>;\n /** Drop every registration the handle holds. */\n unsubscribe(handle: string): Promise<void>;\n}\n\nexport { JourneyFactSource } from './facts';\nexport { PostgresJourneyStore } from './postgres';\nexport { PostgresReporting } from './postgres-reporting';\nexport {\n DEFAULT_SCHEMA,\n TABLES,\n renderDrizzleSchema,\n renderPostgresDdl,\n type TableSpec,\n} from './tables';\nexport type { PostgresJourneyStoreOptions, SqlClientLike } from './postgres';\n"],"mappings":";;;;;;;;;;;AA2KA,IAAa,sBAAb,cAAyC,MAAM;CAGxB;CAFrB,OAAyB;CAEzB,YAAY,UAAsC;EAChD,MACE,4IAA4I,SAAS,KAAK,MAAM,GAClK;EAHmB,KAAA,WAAA;CAIrB;AACF"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../src/store/index.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport type { BundleIR, ConditionIR, ScalarIR, WorkflowIR } from '../ir';\n\n/**\n * The journey engine's data plane. Postgres is the store (`PostgresJourneyStore`); this\n * interface is the port the host, the runner and the fact source use to persist or look\n * anything up, and what a test stub implements in its place. Execution (durable steps,\n * sleeps, wake-ups) is the workflow runtime's job and stays out of here.\n *\n * Timestamps are epoch milliseconds throughout; a store may persist them in\n * its native type as long as `sinceMs` comparisons behave.\n */\n\n/**\n * A profile patch or a stored profile. On the way in, `null` means \"remove\n * this property\" (RFC 7386 merge-patch, the only way the API has to unset\n * one); a stored profile never contains null.\n */\nexport type ProfileProps = Record<string, ScalarIR | null | undefined>;\n\nexport interface EventInput {\n /** The occurrence's identity, chosen by the sender; a second insert with the same id is a no-op. */\n id: string;\n userId: string;\n event: string;\n ts: number;\n payload: Record<string, unknown>;\n}\n\nexport interface TriggerRoute {\n workflow: string;\n hash: string;\n /** Payload gate (payload-only condition tree), or null when the trigger has none. */\n where: ConditionIR | null;\n /** Profile gate, or null. */\n filter: ConditionIR | null;\n /**\n * The code version that applied these routes (`replaceRoutesIfNewer`); absent after a forced\n * deploy. Read in the same row as the hash, so the pair is always one deploy's.\n */\n version?: string | undefined;\n}\n\nexport interface SegmentTriggerRoute {\n workflow: string;\n hash: string;\n segment: string;\n /** As `TriggerRoute.version`. */\n version?: string | undefined;\n}\n\n/**\n * A Worker version, as Cloudflare's version metadata binding names it: the bundle compiled into\n * that version goes live only over an older one (`replaceRoutesIfNewer`).\n */\nexport interface BundleVersion {\n id: string;\n /** When the version was created (epoch ms): later versions are newer. */\n createdAt: number;\n}\n\nexport interface EntryInput {\n workflow: string;\n userId: string;\n instanceId: string;\n hash: string;\n ts: number;\n /**\n * The instance's start, recorded in the same transaction as the entry — for a runtime whose\n * start is an asynchronous submit (AWS) that may have to be retried.\n */\n execution?: ExecutionStart | undefined;\n}\n\n/** How an instance is started on a runtime that submits it: replayed as is on every retry. */\nexport interface ExecutionStart {\n /** The runtime's idempotency key (the durable execution name). */\n name: string;\n /** What is invoked: a qualified function ARN, its version included. */\n target: string;\n /** The exact payload: a retried submit must send the same bytes, or the runtime refuses it. */\n input: string;\n}\n\nexport interface ExecutionRecord extends ExecutionStart {\n instanceId: string;\n workflow: string;\n userId: string;\n createdAt: number;\n submittedAt?: number | undefined;\n arn?: string | undefined;\n unresolvedAt?: number | undefined;\n callbackId?: string | undefined;\n /** Bumped by every wait the instance arms: a wake or a cleanup of an older one leaves it alone. */\n generation: number;\n deadlineAt?: number | undefined;\n checkedAt?: number | undefined;\n stoppedAt?: number | undefined;\n}\n\n/**\n * What a runtime that submits its starts and parks waits on one-shot callbacks (AWS) keeps\n * beside the entry ledger. The runtime holds the execution history; this holds only the\n * mapping from the engine's instance id to it.\n */\nexport interface ExecutionRegistry {\n get(instanceId: string): Promise<ExecutionRecord | undefined>;\n /**\n * Starts not yet confirmed and not given up on, oldest first: of one (workflow, user) entry\n * still running, or every one created before `createdBefore`.\n */\n pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]>;\n markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void>;\n markUnresolved(instanceId: string, at: number): Promise<void>;\n setArn(instanceId: string, arn: string): Promise<void>;\n /** Record the callback a wait parks on; false when a newer generation is already armed. */\n armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean>;\n /** Forget the callback — only if it is still that generation's. */\n clearCallback(instanceId: string, generation: number): Promise<void>;\n /** Submitted executions whose entry is still running, least recently checked first. */\n toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]>;\n markChecked(instanceId: string, at: number): Promise<void>;\n /** Record the first stop; a later one keeps it. */\n markStopped(instanceId: string, at: number): Promise<void>;\n}\n\n/**\n * How an entry attempt ended: a fresh row, a 'failed' row of a dead instance\n * taken over (the once policy does not bar a user over one outage), or\n * refused because the pair already entered and is still alive.\n */\nexport type EntryOutcome = 'entered' | 'reclaimed' | null;\n\n/** A device registered for pushes: its provider token belongs to the user who registered it last. */\nexport interface DeviceInput {\n userId: string;\n token: string;\n /** `ios` (APNs) or `android` (FCM): which provider the token belongs to. */\n platform: string;\n ts: number;\n}\n\n/** An instance of a user still in the ledger, and whether its runner was admitted (see `admitInstance`). */\nexport interface RunningInstance {\n instanceId: string;\n /** False until the runner admitted itself: nothing has run, and the tombstone keeps it that way. */\n admitted: boolean;\n}\n\n/** A store plus how to release what opening it acquired (a connection, say). */\nexport interface StoreLease {\n store: JourneyStore;\n close?: () => Promise<void>;\n}\n\nimport type { ErasureState } from './erasure';\n\nexport { type ErasureState, UserErasedError } from './erasure';\n\n/**\n * The live database lacks tables or columns the engine reads (an SDK upgrade added them, or the\n * host never ran the migration). Raised before a deploy writes anything.\n */\nexport class SchemaMismatchError extends Error {\n override readonly name = 'SchemaMismatchError';\n\n constructor(readonly problems: readonly string[]) {\n super(\n `the database does not match @shware/workflow's tables — regenerate the drizzle schema (workflow-ui generate) and run your migrations:\\n ${problems.join('\\n ')}`\n );\n }\n}\n\n/** A message copy as reporting records it, before it goes out. */\nexport interface MessageRecord {\n idempotencyKey: string;\n workflow: string;\n instanceId: string;\n nodeId: string;\n template: string;\n /** Where the copy lands: `email`, `push_ios`, `push_android`. */\n channel: string;\n userId: string;\n /** An email's subscription topic; null for a transactional email and for every other channel. */\n topic: string | null;\n sentAt: number;\n}\n\n/** What is known of a copy without its engagement: whose it is, where it went, its topic. */\nexport interface MessageSummary {\n userId: string;\n channel: string;\n topic: string | null;\n}\n\n/** One opt-out to set or clear: a topic of the channel, or the whole channel (`topic: null`). */\nexport interface SuppressionChange {\n topic: string | null;\n suppressed: boolean;\n}\n\n/** What a click is judged by. */\nexport interface ClickContext {\n url: string;\n deliveredAt: number;\n linkCount: number;\n /** The copy's clicks in the window before this one. */\n recent: { position: number; at: number }[];\n}\n\n/** An open or a click, with the verdict on who made it and where it came from. */\nexport interface Engagement {\n at: number;\n machine: boolean;\n /** The rule that called it a machine; null for a person. */\n reason: string | null;\n userAgent: string | null;\n /** The network the request came from (Cloudflare's `cf.asn`, `cf.asOrganization`, `cf.country`), never the address. */\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\n/**\n * Journey reporting: where each instance stands, every copy and how it was engaged with, segment\n * sizes. The store exposes it as `reporting`; the host records it and serves email tracking.\n * Every write is idempotent — a retried step reports again.\n */\n/** Bounds on when an event happened, both inclusive (epoch ms); an absent side is open. */\nexport interface EventWindow {\n sinceMs?: number;\n untilMs?: number;\n}\n\nexport interface JourneyReporting {\n /** The instance entered: its row exists from here, so one a guard ends at once still counts. */\n instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void>;\n nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void>;\n instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void>;\n /** The copy's row id; the row a retry already wrote, when there is one. */\n recordMessage(message: MessageRecord): Promise<string>;\n settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void>;\n /** An email's tracked links, in document order. */\n recordLinks(messageId: string, urls: readonly string[]): Promise<void>;\n /**\n * Record an open of the copy, judged by `judge` against the copy (its recipient and when it was\n * delivered — when it was sent, before the transport answered); `undefined` from the judge\n * records nothing. Read and written in one transaction. False for an unknown copy.\n */\n recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean>;\n /**\n * Record a click on the copy's link at `position`, judged by `judge` against the link, how\n * many links the copy has and its clicks of the last `windowMs`. The copy is locked for the\n * transaction, so clicks arriving together (a scanner following every link at once) are\n * judged one after another, each seeing the ones before. When the judge asks to `backdate`,\n * the window's earlier clicks are reclassified with this one's verdict. A click implies an\n * open. Undefined for an unknown link.\n */\n recordClick(\n messageId: string,\n position: number,\n at: number,\n windowMs: number,\n judge: (link: ClickContext) => { engagement: Engagement; backdate: boolean }\n ): Promise<{ url: string; engagement: Engagement } | undefined>;\n /**\n * The email copy's recipient opted out: of the copy's topic, or with `scope: 'all'` of every\n * email. Recorded on the copy and as a suppression (the topic's row, or the channel-wide\n * null-topic row), in one transaction, which also yields who the recipient is and the topic —\n * so the caller acts on the unsubscribe without a second read. A transactional copy\n * (`topic: null`) has nothing to opt out of: nothing is recorded, and the answer says so.\n * Undefined for an unknown copy.\n */\n recordUnsubscribe(\n messageId: string,\n at: number,\n scope?: 'topic' | 'all'\n ): Promise<{ userId: string; topic: string | null } | undefined>;\n /** The copy's owner, channel and topic; undefined for an unknown copy. */\n lookupMessage(messageId: string): Promise<MessageSummary | undefined>;\n /** A push copy the device reported it received. False for an unknown copy. */\n recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;\n /** Drop members of segments no longer deployed, then record every deployed segment's size. */\n snapshotSegments(at: number): Promise<{ segment: string; size: number }[]>;\n}\n\nexport interface JourneyStore {\n /** Where instances stand, every copy and its engagement, segment sizes. */\n readonly reporting: JourneyReporting;\n\n /**\n * Record that the user's data must go (a deleted account): the tombstone every write about\n * the user is conditional on, from here on and for good. Committed before anything is\n * stopped or erased, so an entry that got in before it is found by the erasure and none gets\n * in after it. Idempotent: a second request, or one for a user already erased, changes nothing.\n */\n requestErasure(userId: string, at: number): Promise<void>;\n /** Users whose erasure was requested and not carried out yet (`'erasing'`), oldest first. */\n pendingErasures(): Promise<string[]>;\n /**\n * Where the user stands: `'none'` (no tombstone), `'erasing'` (requested, their instances\n * being stopped, data still there) or `'erased'` (`forgetUser` went through). Both\n * tombstone states refuse every write about the user; the entry points read this for a fast\n * answer, and the store's conditional writes are the gate itself.\n */\n erasureState(userId: string): Promise<ErasureState>;\n /** The user's journey instances still running, by the entry ledger. */\n runningInstances(userId: string): Promise<RunningInstance[]>;\n /**\n * The runner's admission, before its first observable effect: records that the instance runs\n * (`admitted_at`, kept on replay) — unless the user has an erasure tombstone, in which case\n * nothing is recorded and the runner must not run. Mutually exclusive with `requestErasure`\n * and `forgetUser` for that user (Postgres: the user's advisory lock), so an erasure either\n * finds the instance admitted and stops it, or commits its tombstone first and the admission\n * is refused — never neither.\n *\n * A first admission needs the entry running. An instance already admitted is admitted again\n * whatever the entry's status — the legitimate replay of an instance whose finalisation was\n * cut short after the entry reached its terminal status, which resumes on its own checkpoint\n * and finishes what is left. Never a new attempt's way in: false for a terminal entry never\n * admitted, for an entry no longer in the ledger, for another user's entry, and for an\n * instance whose entry was reclaimed since (`enterJourney` resets the admission with the\n * instance id, so a superseded attempt cannot pass under the id it lost).\n */\n admitInstance(instanceId: string, userId: string): Promise<boolean>;\n /**\n * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment\n * memberships, entries and reporting — and mark the tombstone erased (`erased_at`), which\n * stays: a write that was in flight when the data went cannot bring the user back, and the\n * same id is never reactivated by ingest — which is also why the suppressions go with the\n * rest: nothing is ever sent to the id again, so no opt-out needs keeping. Run only once no\n * instance of theirs runs any more, or one could write some of it back. Idempotent. Mutually\n * exclusive with every write about the user (the user's advisory lock), so the data is gone\n * when this returns — nothing of theirs lands afterwards.\n */\n forgetUser(userId: string, at: number): Promise<void>;\n\n /**\n * The user opted out of the channel (recorded by an unsubscribe, or set through\n * `/subscriptions`): with a `topic`, an opt-out of that topic or of the whole channel; without\n * one, only the whole channel.\n */\n isSuppressed(userId: string, channel: string, topic?: string): Promise<boolean>;\n /** Every opt-out of the user on the channel: the topics, and `null` for the whole channel. */\n listSuppressions(userId: string, channel: string): Promise<(string | null)[]>;\n /**\n * Set or clear opt-outs, all in one transaction: a suppressed change inserts the row (keeping\n * the time of one already there), an unsuppressed one deletes it. Written whatever the user's\n * erasure state — the caller refuses an erased user first — since an opt-out is never refused.\n */\n updateSuppressions(\n userId: string,\n channel: string,\n changes: readonly SuppressionChange[],\n at: number\n ): Promise<void>;\n\n /**\n * What the live database lacks against the engine's tables (read-only); a deploy refuses to\n * run while it lists anything.\n */\n checkSchema(): Promise<string[]>;\n\n /* ---------------------------------- events --------------------------------- */\n /**\n * Append the occurrence; false when its id was already in the log (nothing written). Throws\n * `UserErasedError` for a user with a tombstone, like every write about a user below.\n */\n insertEvent(input: EventInput): Promise<boolean>;\n /** Occurrences of `event` for the user, optionally only those within the window. */\n countEvents(userId: string, event: string, window?: EventWindow): Promise<number>;\n /** The payloads of those occurrences — the caller filters them with the shared evaluator. */\n listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]>;\n\n /* --------------------------------- profiles -------------------------------- */\n getProfile(userId: string): Promise<ProfileProps | undefined>;\n /**\n * Merge-patch `props` into the stored profile in one statement (a null\n * removes the property) and return the result. One statement, because a\n * read-modify-write loses one of two concurrent identifies.\n */\n mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps>;\n\n /**\n * Every user the engine knows (a profile or an event): who the segment sweep evaluates. Ids\n * come in ascending order; `after` resumes past the last id of the previous page, and `limit`\n * bounds the page (the whole list without one).\n */\n listUserIds(page?: { after?: string | undefined; limit?: number | undefined }): Promise<string[]>;\n\n /* ---------------------------------- devices --------------------------------- */\n /** The user's push devices, most recently registered first. */\n listDevices(userId: string): Promise<PushDevice[]>;\n /**\n * Register a device: one row per token, so a token registered again moves to the user who\n * registered it last (a phone signed into another account) and to the front of their list.\n */\n upsertDevice(device: DeviceInput): Promise<void>;\n /** Forget a token (reported dead by APNs / FCM); the user it belonged to, if any. */\n removeDevice(token: string): Promise<string | undefined>;\n /**\n * The user signed out on the device: the token is kept, bound to nobody, until the next sign-in\n * binds it again. The user it belonged to, if any.\n */\n unbindDevice(token: string): Promise<string | undefined>;\n\n /* ---------------------------- deployed definitions -------------------------- */\n getSegmentCondition(id: string): Promise<ConditionIR | undefined>;\n /** Every deployed segment with its definition: what the segment sweep evaluates. */\n listSegments(): Promise<{ id: string; condition: ConditionIR }[]>;\n findTriggers(event: string): Promise<TriggerRoute[]>;\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]>;\n putWorkflowIR(workflow: WorkflowIR): Promise<void>;\n getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined>;\n /**\n * Swap the routing tables (segments, event triggers, segment triggers) for\n * the bundle's — atomically, so a concurrent ingest never sees them half\n * empty. Workflow bodies are stored separately (`putWorkflowIR`) because they\n * are content-addressed and outlive the routes that point at them.\n */\n replaceRoutes(bundle: BundleIR): Promise<void>;\n /**\n * The Worker version whose bundle the routes came from, when one put them there through\n * `replaceRoutesIfNewer` (a forced deploy leaves it as it was). Read from the database itself,\n * not a cache in front of it.\n */\n liveBundleVersion(): Promise<BundleVersion | undefined>;\n /**\n * `replaceRoutes`, only when `version` is newer than the live one, recorded in the same\n * transaction: two versions serving side by side during a rollout cannot leave the older one's\n * routes in force. False, with nothing written, when a version as new or newer is live.\n */\n replaceRoutesIfNewer(bundle: BundleIR, version: BundleVersion): Promise<boolean>;\n\n /* ----------------------------- segment membership --------------------------- */\n isSegmentMember(segment: string, userId: string): Promise<boolean>;\n /** Record the membership, with the workflows its entry has to start (see segment_start). */\n addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void>;\n /** The workflows the member's entry has not started yet. */\n pendingSegmentStarts(segment: string, userId: string): Promise<string[]>;\n completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void>;\n /** Drop the membership and any start it still owed. */\n removeSegmentMember(segment: string, userId: string): Promise<void>;\n\n /* ------------------------------- entry ledger ------------------------------- */\n /**\n * Record the entry (the once policy). Atomic under concurrent ingests: of\n * two racing attempts exactly one is 'entered' (or 'reclaimed', when the\n * pair's previous instance is recorded as 'failed') and the other null.\n */\n enterJourney(entry: EntryInput): Promise<EntryOutcome>;\n removeEntry(instanceId: string): Promise<void>;\n setEntryStatus(instanceId: string, status: string): Promise<void>;\n /** Execution starts and wake callbacks, for a runtime that submits its starts (AWS). */\n readonly executions: ExecutionRegistry;\n\n /* ------------------------------ wake subscriptions --------------------------- */\n /** Distinct wake handles registered for (user, event). */\n findWakeHandles(userId: string, event: string): Promise<string[]>;\n /** Register the handle for each event; repeated registrations are idempotent. */\n subscribe(handle: string, userId: string, events: readonly string[], ts: number): Promise<void>;\n /** Drop every registration the handle holds. */\n unsubscribe(handle: string): Promise<void>;\n}\n\nexport { JourneyFactSource } from './facts';\nexport { PostgresJourneyStore } from './postgres';\nexport { PostgresReporting } from './postgres-reporting';\nexport {\n DEFAULT_SCHEMA,\n TABLES,\n renderDrizzleSchema,\n renderPostgresDdl,\n type TableSpec,\n type UniqueConstraintSpec,\n} from './tables';\nexport type { PostgresJourneyStoreOptions, SqlClientLike } from './postgres';\n"],"mappings":";;;;;;;;;;;AA2KA,IAAa,sBAAb,cAAyC,MAAM;CAGxB;CAFrB,OAAyB;CAEzB,YAAY,UAAsC;EAChD,MACE,4IAA4I,SAAS,KAAK,MAAM,GAClK;EAHmB,KAAA,WAAA;CAIrB;AACF"}
@@ -3,10 +3,9 @@ import { PushDevice } from "../engine/ports.cjs";
3
3
  import { ErasureState, UserErasedError } from "./erasure.cjs";
4
4
  import { JourneyFactSource } from "./facts.cjs";
5
5
  import { SqlClientLike } from "./sql.cjs";
6
- import { DEFAULT_SCHEMA, TABLES, TableSpec, renderDrizzleSchema, renderPostgresDdl } from "./tables.cjs";
6
+ import { DEFAULT_SCHEMA, TABLES, TableSpec, UniqueConstraintSpec, renderDrizzleSchema, renderPostgresDdl } from "./tables.cjs";
7
7
  import { PostgresJourneyStore, PostgresJourneyStoreOptions } from "./postgres.cjs";
8
8
  import { PostgresReporting } from "./postgres-reporting.cjs";
9
- //#region src/store/index.d.ts
10
9
  /**
11
10
  * The journey engine's data plane. Postgres is the store (`PostgresJourneyStore`); this
12
11
  * interface is the port the host, the runner and the fact source use to persist or look
@@ -173,8 +172,21 @@ export interface MessageRecord {
173
172
  /** Where the copy lands: `email`, `push_ios`, `push_android`. */
174
173
  channel: string;
175
174
  userId: string;
175
+ /** An email's subscription topic; null for a transactional email and for every other channel. */
176
+ topic: string | null;
176
177
  sentAt: number;
177
178
  }
179
+ /** What is known of a copy without its engagement: whose it is, where it went, its topic. */
180
+ export interface MessageSummary {
181
+ userId: string;
182
+ channel: string;
183
+ topic: string | null;
184
+ }
185
+ /** One opt-out to set or clear: a topic of the channel, or the whole channel (`topic: null`). */
186
+ export interface SuppressionChange {
187
+ topic: string | null;
188
+ suppressed: boolean;
189
+ }
178
190
  /** What a click is judged by. */
179
191
  export interface ClickContext {
180
192
  url: string;
@@ -266,13 +278,19 @@ export interface JourneyReporting {
266
278
  engagement: Engagement;
267
279
  } | undefined>;
268
280
  /**
269
- * The email copy's recipient opted out of email: recorded on the copy and as a suppression, in
270
- * one transaction, which also yields who the recipient is — so the caller acts on the
271
- * unsubscribe without a second read. Undefined for an unknown copy.
281
+ * The email copy's recipient opted out: of the copy's topic, or with `scope: 'all'` of every
282
+ * email. Recorded on the copy and as a suppression (the topic's row, or the channel-wide
283
+ * null-topic row), in one transaction, which also yields who the recipient is and the topic —
284
+ * so the caller acts on the unsubscribe without a second read. A transactional copy
285
+ * (`topic: null`) has nothing to opt out of: nothing is recorded, and the answer says so.
286
+ * Undefined for an unknown copy.
272
287
  */
273
- recordUnsubscribe(messageId: string, at: number): Promise<{
288
+ recordUnsubscribe(messageId: string, at: number, scope?: 'topic' | 'all'): Promise<{
274
289
  userId: string;
290
+ topic: string | null;
275
291
  } | undefined>;
292
+ /** The copy's owner, channel and topic; undefined for an unknown copy. */
293
+ lookupMessage(messageId: string): Promise<MessageSummary | undefined>;
276
294
  /** A push copy the device reported it received. False for an unknown copy. */
277
295
  recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;
278
296
  /** Drop members of segments no longer deployed, then record every deployed segment's size. */
@@ -323,15 +341,27 @@ export interface JourneyStore {
323
341
  * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment
324
342
  * memberships, entries and reporting — and mark the tombstone erased (`erased_at`), which
325
343
  * stays: a write that was in flight when the data went cannot bring the user back, and the
326
- * same id is never reactivated by ingest. Suppressions stay too: an opt-out is a compliance
327
- * record keyed by an opaque id, and it outlives the erasure. Run only once no instance of
328
- * theirs runs any more, or one could write some of it back. Idempotent. Mutually exclusive
329
- * with every write about the user (the user's advisory lock), so
330
- * the data is gone when this returns — nothing of theirs lands afterwards.
344
+ * same id is never reactivated by ingest — which is also why the suppressions go with the
345
+ * rest: nothing is ever sent to the id again, so no opt-out needs keeping. Run only once no
346
+ * instance of theirs runs any more, or one could write some of it back. Idempotent. Mutually
347
+ * exclusive with every write about the user (the user's advisory lock), so the data is gone
348
+ * when this returns — nothing of theirs lands afterwards.
331
349
  */
332
350
  forgetUser(userId: string, at: number): Promise<void>;
333
- /** The user opted out of the channel (recorded by an unsubscribe). */
334
- isSuppressed(userId: string, channel: string): Promise<boolean>;
351
+ /**
352
+ * The user opted out of the channel (recorded by an unsubscribe, or set through
353
+ * `/subscriptions`): with a `topic`, an opt-out of that topic or of the whole channel; without
354
+ * one, only the whole channel.
355
+ */
356
+ isSuppressed(userId: string, channel: string, topic?: string): Promise<boolean>;
357
+ /** Every opt-out of the user on the channel: the topics, and `null` for the whole channel. */
358
+ listSuppressions(userId: string, channel: string): Promise<(string | null)[]>;
359
+ /**
360
+ * Set or clear opt-outs, all in one transaction: a suppressed change inserts the row (keeping
361
+ * the time of one already there), an unsuppressed one deletes it. Written whatever the user's
362
+ * erasure state — the caller refuses an erased user first — since an opt-out is never refused.
363
+ */
364
+ updateSuppressions(userId: string, channel: string, changes: readonly SuppressionChange[], at: number): Promise<void>;
335
365
  /**
336
366
  * What the live database lacks against the engine's tables (read-only); a deploy refuses to
337
367
  * run while it lists anything.
@@ -430,6 +460,5 @@ export interface JourneyStore {
430
460
  /** Drop every registration the handle holds. */
431
461
  unsubscribe(handle: string): Promise<void>;
432
462
  }
433
- //#endregion
434
- export { DEFAULT_SCHEMA, type ErasureState, JourneyFactSource, PostgresJourneyStore, type PostgresJourneyStoreOptions, PostgresReporting, type SqlClientLike, TABLES, type TableSpec, UserErasedError, renderDrizzleSchema, renderPostgresDdl };
463
+ export { DEFAULT_SCHEMA, type ErasureState, JourneyFactSource, PostgresJourneyStore, type PostgresJourneyStoreOptions, PostgresReporting, type SqlClientLike, TABLES, type TableSpec, type UniqueConstraintSpec, UserErasedError, renderDrizzleSchema, renderPostgresDdl };
435
464
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/store/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;YAkBY,eAAe,eAAe;iBAEzB;;EAEf;EACA;EACA;EACA;EACA,SAAS;;iBAGM;EACf;EACA;;EAEA,OAAO;;EAEP,QAAQ;;;;;EAKR;;iBAGe;EACf;EACA;EACA;;EAEA;;;;;;iBAOe;EACf;;EAEA;;iBAGe;EACf;EACA;EACA;EACA;EACA;;;;;EAKA,YAAY;;;iBAIG;;EAEf;;EAEA;;EAEA;;iBAGe,wBAAwB;EACvC;EACA;EACA;EACA;EACA;EACA;EACA;EAC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,YAAY,iBAAiB"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/store/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;YAkBY,eAAe,eAAe;iBAEzB;;EAEf;EACA;EACA;EACA;EACA,SAAS;;iBAGM;EACf;EACA;;EAEA,OAAO;;EAEP,QAAQ;;;;;EAKR;;iBAGe;EACf;EACA;EACA;;EAEA;;;;;;iBAOe;EACf;;EAEA;;iBAGe;EACf;EACA;EACA;EACA;EACA;;;;;EAKA,YAAY;;;iBAIG;;EAEf;;EAEA;;EAEA;;iBAGe,wBAAwB;EACvC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;EACA;;;;;;;iBAQe;EACf,IAAI,qBAAqB,QAAQ;;;;;EAKjC,cAAc;IACZ;IACA;IACA;IACA;MACE,QAAQ;EACZ,cAAc,oBAAoB,yBAAyB,aAAa;EACxE,eAAe,oBAAoB,aAAa;EAChD,OAAO,oBAAoB,cAAc;;EAEzC,YACE,oBACA;IAAY;IAAY;IAAoB;MAC3C;;EAEH,cAAc,oBAAoB,qBAAqB;;EAEvD,YAAY,eAAe,wBAAwB,QAAQ;EAC3D,YAAY,oBAAoB,aAAa;;EAE7C,YAAY,oBAAoB,aAAa;;;;;;;YAQnC;;iBAGK;EACf;EACA;;EAEA;EACA;;;iBAIe;EACf;;EAEA;;;iBAIe;EACf,OAAO;EACP,cAAc;;;;;;qBAWH,4BAA4B;WAGlB;WAFH;EAElB,YAAqB;;;iBAQN;EACf;EACA;EACA;EACA;EACA;;EAEA;EACA;;EAEA;EACA;;;iBAIe;EACf;EACA;EACA;;;iBAIe;EACf;EACA;;;iBAIe;EACf;EACA;EACA;;EAEA;IAAU;IAAkB;;;;iBAIb;EACf;EACA;;EAEA;EACA;;EAEA;EACA;EACA;;;;;;;;iBASe;EACf;EACA;;iBAGe;;EAEf,gBAAgB;IACd;IACA;IACA;IACA;MACE;EACJ,YAAY;IACV;IACA;IACA;IACA;IACA;MACE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IAAU;IAAY,WAAW;;EACjD,aAAa,gBAAgB,QAAQ;EACrC,uBAAuB,QAAQ;EAC/B,cAAc,UAAU,aAAa;EACrC,cAAc,sBAAsB,QAAQ;;;;;;;EAO5C,cAAc,QAAQ,WAAW;;;;;;EAMjC,qBAAqB,QAAQ;;;;;;EAM7B,qBAAqB,QAAQ,UAAU,SAAS,gBAAgB;EAGhE,gBAAgB,iBAAiB,iBAAiB;;EAElD,iBACE,iBACA,gBACA,YACA,+BACC;;EAEH,qBAAqB,iBAAiB,iBAAiB;EACvD,qBAAqB,iBAAiB,gBAAgB,mBAAmB;;EAEzE,oBAAoB,iBAAiB,iBAAiB;;;;;;EAQtD,aAAa,OAAO,aAAa,QAAQ;EACzC,YAAY,qBAAqB;EACjC,eAAe,oBAAoB,iBAAiB;;WAE3C,YAAY;;EAIrB,gBAAgB,gBAAgB,gBAAgB;;EAEhD,UAAU,gBAAgB,gBAAgB,2BAA2B,aAAa;;EAElF,YAAY,iBAAiB"}
@@ -3,10 +3,9 @@ import { PushDevice } from "../engine/ports.mjs";
3
3
  import { ErasureState, UserErasedError } from "./erasure.mjs";
4
4
  import { JourneyFactSource } from "./facts.mjs";
5
5
  import { SqlClientLike } from "./sql.mjs";
6
- import { DEFAULT_SCHEMA, TABLES, TableSpec, renderDrizzleSchema, renderPostgresDdl } from "./tables.mjs";
6
+ import { DEFAULT_SCHEMA, TABLES, TableSpec, UniqueConstraintSpec, renderDrizzleSchema, renderPostgresDdl } from "./tables.mjs";
7
7
  import { PostgresJourneyStore, PostgresJourneyStoreOptions } from "./postgres.mjs";
8
8
  import { PostgresReporting } from "./postgres-reporting.mjs";
9
- //#region src/store/index.d.ts
10
9
  /**
11
10
  * The journey engine's data plane. Postgres is the store (`PostgresJourneyStore`); this
12
11
  * interface is the port the host, the runner and the fact source use to persist or look
@@ -173,8 +172,21 @@ export interface MessageRecord {
173
172
  /** Where the copy lands: `email`, `push_ios`, `push_android`. */
174
173
  channel: string;
175
174
  userId: string;
175
+ /** An email's subscription topic; null for a transactional email and for every other channel. */
176
+ topic: string | null;
176
177
  sentAt: number;
177
178
  }
179
+ /** What is known of a copy without its engagement: whose it is, where it went, its topic. */
180
+ export interface MessageSummary {
181
+ userId: string;
182
+ channel: string;
183
+ topic: string | null;
184
+ }
185
+ /** One opt-out to set or clear: a topic of the channel, or the whole channel (`topic: null`). */
186
+ export interface SuppressionChange {
187
+ topic: string | null;
188
+ suppressed: boolean;
189
+ }
178
190
  /** What a click is judged by. */
179
191
  export interface ClickContext {
180
192
  url: string;
@@ -266,13 +278,19 @@ export interface JourneyReporting {
266
278
  engagement: Engagement;
267
279
  } | undefined>;
268
280
  /**
269
- * The email copy's recipient opted out of email: recorded on the copy and as a suppression, in
270
- * one transaction, which also yields who the recipient is — so the caller acts on the
271
- * unsubscribe without a second read. Undefined for an unknown copy.
281
+ * The email copy's recipient opted out: of the copy's topic, or with `scope: 'all'` of every
282
+ * email. Recorded on the copy and as a suppression (the topic's row, or the channel-wide
283
+ * null-topic row), in one transaction, which also yields who the recipient is and the topic —
284
+ * so the caller acts on the unsubscribe without a second read. A transactional copy
285
+ * (`topic: null`) has nothing to opt out of: nothing is recorded, and the answer says so.
286
+ * Undefined for an unknown copy.
272
287
  */
273
- recordUnsubscribe(messageId: string, at: number): Promise<{
288
+ recordUnsubscribe(messageId: string, at: number, scope?: 'topic' | 'all'): Promise<{
274
289
  userId: string;
290
+ topic: string | null;
275
291
  } | undefined>;
292
+ /** The copy's owner, channel and topic; undefined for an unknown copy. */
293
+ lookupMessage(messageId: string): Promise<MessageSummary | undefined>;
276
294
  /** A push copy the device reported it received. False for an unknown copy. */
277
295
  recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;
278
296
  /** Drop members of segments no longer deployed, then record every deployed segment's size. */
@@ -323,15 +341,27 @@ export interface JourneyStore {
323
341
  * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment
324
342
  * memberships, entries and reporting — and mark the tombstone erased (`erased_at`), which
325
343
  * stays: a write that was in flight when the data went cannot bring the user back, and the
326
- * same id is never reactivated by ingest. Suppressions stay too: an opt-out is a compliance
327
- * record keyed by an opaque id, and it outlives the erasure. Run only once no instance of
328
- * theirs runs any more, or one could write some of it back. Idempotent. Mutually exclusive
329
- * with every write about the user (the user's advisory lock), so
330
- * the data is gone when this returns — nothing of theirs lands afterwards.
344
+ * same id is never reactivated by ingest — which is also why the suppressions go with the
345
+ * rest: nothing is ever sent to the id again, so no opt-out needs keeping. Run only once no
346
+ * instance of theirs runs any more, or one could write some of it back. Idempotent. Mutually
347
+ * exclusive with every write about the user (the user's advisory lock), so the data is gone
348
+ * when this returns — nothing of theirs lands afterwards.
331
349
  */
332
350
  forgetUser(userId: string, at: number): Promise<void>;
333
- /** The user opted out of the channel (recorded by an unsubscribe). */
334
- isSuppressed(userId: string, channel: string): Promise<boolean>;
351
+ /**
352
+ * The user opted out of the channel (recorded by an unsubscribe, or set through
353
+ * `/subscriptions`): with a `topic`, an opt-out of that topic or of the whole channel; without
354
+ * one, only the whole channel.
355
+ */
356
+ isSuppressed(userId: string, channel: string, topic?: string): Promise<boolean>;
357
+ /** Every opt-out of the user on the channel: the topics, and `null` for the whole channel. */
358
+ listSuppressions(userId: string, channel: string): Promise<(string | null)[]>;
359
+ /**
360
+ * Set or clear opt-outs, all in one transaction: a suppressed change inserts the row (keeping
361
+ * the time of one already there), an unsuppressed one deletes it. Written whatever the user's
362
+ * erasure state — the caller refuses an erased user first — since an opt-out is never refused.
363
+ */
364
+ updateSuppressions(userId: string, channel: string, changes: readonly SuppressionChange[], at: number): Promise<void>;
335
365
  /**
336
366
  * What the live database lacks against the engine's tables (read-only); a deploy refuses to
337
367
  * run while it lists anything.
@@ -430,6 +460,5 @@ export interface JourneyStore {
430
460
  /** Drop every registration the handle holds. */
431
461
  unsubscribe(handle: string): Promise<void>;
432
462
  }
433
- //#endregion
434
- export { DEFAULT_SCHEMA, type ErasureState, JourneyFactSource, PostgresJourneyStore, type PostgresJourneyStoreOptions, PostgresReporting, type SqlClientLike, TABLES, type TableSpec, UserErasedError, renderDrizzleSchema, renderPostgresDdl };
463
+ export { DEFAULT_SCHEMA, type ErasureState, JourneyFactSource, PostgresJourneyStore, type PostgresJourneyStoreOptions, PostgresReporting, type SqlClientLike, TABLES, type TableSpec, type UniqueConstraintSpec, UserErasedError, renderDrizzleSchema, renderPostgresDdl };
435
464
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/store/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;YAkBY,eAAe,eAAe;iBAEzB;;EAEf;EACA;EACA;EACA;EACA,SAAS;;iBAGM;EACf;EACA;;EAEA,OAAO;;EAEP,QAAQ;;;;;EAKR;;iBAGe;EACf;EACA;EACA;;EAEA;;;;;;iBAOe;EACf;;EAEA;;iBAGe;EACf;EACA;EACA;EACA;EACA;;;;;EAKA,YAAY;;;iBAIG;;EAEf;;EAEA;;EAEA;;iBAGe,wBAAwB;EACvC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;EACA;;;;;;;iBAQe;EACf,IAAI,qBAAqB,QAAQ;;;;;EAKjC,cAAc;IACZ;IACA;IACA;IACA;MACE,QAAQ;EACZ,cAAc,oBAAoB,yBAAyB,aAAa;EACxE,eAAe,oBAAoB,aAAa;EAChD,OAAO,oBAAoB,cAAc;;EAEzC,YACE,oBACA;IAAY;IAAY;IAAoB;MAC3C;;EAEH,cAAc,oBAAoB,qBAAqB;;EAEvD,YAAY,eAAe,wBAAwB,QAAQ;EAC3D,YAAY,oBAAoB,aAAa;;EAE7C,YAAY,oBAAoB,aAAa;;;;;;;YAQnC;;iBAGK;EACf;EACA;;EAEA;EACA;;;iBAIe;EACf;;EAEA;;;iBAIe;EACf,OAAO;EACP,cAAc;;;;;;qBAWH,4BAA4B;WAGlB;WAFH;EAElB,YAAqB;;;iBAQN;EACf;EACA;EACA;EACA;EACA;;EAEA;EACA;EACA;;;i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gB,2BAA2B,aAAa;;EAElF,YAAY,iBAAiB"}
@@ -1,9 +1,9 @@
1
+ import { JourneyFactSource } from "./facts.mjs";
1
2
  import { UserErasedError } from "./erasure.mjs";
2
3
  import { PostgresReporting } from "./postgres-reporting.mjs";
3
4
  import { DEFAULT_SCHEMA, TABLES, renderDrizzleSchema, renderPostgresDdl } from "./tables.mjs";
4
5
  import { PostgresJourneyStore } from "./postgres.mjs";
5
- import { JourneyFactSource } from "./facts.mjs";
6
- //#region src/store/index.ts
6
+ // src/store/index.ts
7
7
  /**
8
8
  * The live database lacks tables or columns the engine reads (an SDK upgrade added them, or the
9
9
  * host never ran the migration). Raised before a deploy writes anything.
@@ -16,7 +16,6 @@ var SchemaMismatchError = class extends Error {
16
16
  this.problems = problems;
17
17
  }
18
18
  };
19
- //#endregion
20
19
  export { DEFAULT_SCHEMA, JourneyFactSource, PostgresJourneyStore, PostgresReporting, SchemaMismatchError, TABLES, UserErasedError, renderDrizzleSchema, renderPostgresDdl };
21
20
 
22
21
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/store/index.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport type { BundleIR, ConditionIR, ScalarIR, WorkflowIR } from '../ir';\n\n/**\n * The journey engine's data plane. Postgres is the store (`PostgresJourneyStore`); this\n * interface is the port the host, the runner and the fact source use to persist or look\n * anything up, and what a test stub implements in its place. Execution (durable steps,\n * sleeps, wake-ups) is the workflow runtime's job and stays out of here.\n *\n * Timestamps are epoch milliseconds throughout; a store may persist them in\n * its native type as long as `sinceMs` comparisons behave.\n */\n\n/**\n * A profile patch or a stored profile. On the way in, `null` means \"remove\n * this property\" (RFC 7386 merge-patch, the only way the API has to unset\n * one); a stored profile never contains null.\n */\nexport type ProfileProps = Record<string, ScalarIR | null | undefined>;\n\nexport interface EventInput {\n /** The occurrence's identity, chosen by the sender; a second insert with the same id is a no-op. */\n id: string;\n userId: string;\n event: string;\n ts: number;\n payload: Record<string, unknown>;\n}\n\nexport interface TriggerRoute {\n workflow: string;\n hash: string;\n /** Payload gate (payload-only condition tree), or null when the trigger has none. */\n where: ConditionIR | null;\n /** Profile gate, or null. */\n filter: ConditionIR | null;\n /**\n * The code version that applied these routes (`replaceRoutesIfNewer`); absent after a forced\n * deploy. Read in the same row as the hash, so the pair is always one deploy's.\n */\n version?: string | undefined;\n}\n\nexport interface SegmentTriggerRoute {\n workflow: string;\n hash: string;\n segment: string;\n /** As `TriggerRoute.version`. */\n version?: string | undefined;\n}\n\n/**\n * A Worker version, as Cloudflare's version metadata binding names it: the bundle compiled into\n * that version goes live only over an older one (`replaceRoutesIfNewer`).\n */\nexport interface BundleVersion {\n id: string;\n /** When the version was created (epoch ms): later versions are newer. */\n createdAt: number;\n}\n\nexport interface EntryInput {\n workflow: string;\n userId: string;\n instanceId: string;\n hash: string;\n ts: number;\n /**\n * The instance's start, recorded in the same transaction as the entry — for a runtime whose\n * start is an asynchronous submit (AWS) that may have to be retried.\n */\n execution?: ExecutionStart | undefined;\n}\n\n/** How an instance is started on a runtime that submits it: replayed as is on every retry. */\nexport interface ExecutionStart {\n /** The runtime's idempotency key (the durable execution name). */\n name: string;\n /** What is invoked: a qualified function ARN, its version included. */\n target: string;\n /** The exact payload: a retried submit must send the same bytes, or the runtime refuses it. */\n input: string;\n}\n\nexport interface ExecutionRecord extends ExecutionStart {\n instanceId: string;\n workflow: string;\n userId: string;\n createdAt: number;\n submittedAt?: number | undefined;\n arn?: string | undefined;\n unresolvedAt?: number | undefined;\n callbackId?: string | undefined;\n /** Bumped by every wait the instance arms: a wake or a cleanup of an older one leaves it alone. */\n generation: number;\n deadlineAt?: number | undefined;\n checkedAt?: number | undefined;\n stoppedAt?: number | undefined;\n}\n\n/**\n * What a runtime that submits its starts and parks waits on one-shot callbacks (AWS) keeps\n * beside the entry ledger. The runtime holds the execution history; this holds only the\n * mapping from the engine's instance id to it.\n */\nexport interface ExecutionRegistry {\n get(instanceId: string): Promise<ExecutionRecord | undefined>;\n /**\n * Starts not yet confirmed and not given up on, oldest first: of one (workflow, user) entry\n * still running, or every one created before `createdBefore`.\n */\n pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]>;\n markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void>;\n markUnresolved(instanceId: string, at: number): Promise<void>;\n setArn(instanceId: string, arn: string): Promise<void>;\n /** Record the callback a wait parks on; false when a newer generation is already armed. */\n armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean>;\n /** Forget the callback — only if it is still that generation's. */\n clearCallback(instanceId: string, generation: number): Promise<void>;\n /** Submitted executions whose entry is still running, least recently checked first. */\n toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]>;\n markChecked(instanceId: string, at: number): Promise<void>;\n /** Record the first stop; a later one keeps it. */\n markStopped(instanceId: string, at: number): Promise<void>;\n}\n\n/**\n * How an entry attempt ended: a fresh row, a 'failed' row of a dead instance\n * taken over (the once policy does not bar a user over one outage), or\n * refused because the pair already entered and is still alive.\n */\nexport type EntryOutcome = 'entered' | 'reclaimed' | null;\n\n/** A device registered for pushes: its provider token belongs to the user who registered it last. */\nexport interface DeviceInput {\n userId: string;\n token: string;\n /** `ios` (APNs) or `android` (FCM): which provider the token belongs to. */\n platform: string;\n ts: number;\n}\n\n/** An instance of a user still in the ledger, and whether its runner was admitted (see `admitInstance`). */\nexport interface RunningInstance {\n instanceId: string;\n /** False until the runner admitted itself: nothing has run, and the tombstone keeps it that way. */\n admitted: boolean;\n}\n\n/** A store plus how to release what opening it acquired (a connection, say). */\nexport interface StoreLease {\n store: JourneyStore;\n close?: () => Promise<void>;\n}\n\nimport type { ErasureState } from './erasure';\n\nexport { type ErasureState, UserErasedError } from './erasure';\n\n/**\n * The live database lacks tables or columns the engine reads (an SDK upgrade added them, or the\n * host never ran the migration). Raised before a deploy writes anything.\n */\nexport class SchemaMismatchError extends Error {\n override readonly name = 'SchemaMismatchError';\n\n constructor(readonly problems: readonly string[]) {\n super(\n `the database does not match @shware/workflow's tables — regenerate the drizzle schema (workflow-ui generate) and run your migrations:\\n ${problems.join('\\n ')}`\n );\n }\n}\n\n/** A message copy as reporting records it, before it goes out. */\nexport interface MessageRecord {\n idempotencyKey: string;\n workflow: string;\n instanceId: string;\n nodeId: string;\n template: string;\n /** Where the copy lands: `email`, `push_ios`, `push_android`. */\n channel: string;\n userId: string;\n sentAt: number;\n}\n\n/** What a click is judged by. */\nexport interface ClickContext {\n url: string;\n deliveredAt: number;\n linkCount: number;\n /** The copy's clicks in the window before this one. */\n recent: { position: number; at: number }[];\n}\n\n/** An open or a click, with the verdict on who made it and where it came from. */\nexport interface Engagement {\n at: number;\n machine: boolean;\n /** The rule that called it a machine; null for a person. */\n reason: string | null;\n userAgent: string | null;\n /** The network the request came from (Cloudflare's `cf.asn`, `cf.asOrganization`, `cf.country`), never the address. */\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\n/**\n * Journey reporting: where each instance stands, every copy and how it was engaged with, segment\n * sizes. The store exposes it as `reporting`; the host records it and serves email tracking.\n * Every write is idempotent — a retried step reports again.\n */\n/** Bounds on when an event happened, both inclusive (epoch ms); an absent side is open. */\nexport interface EventWindow {\n sinceMs?: number;\n untilMs?: number;\n}\n\nexport interface JourneyReporting {\n /** The instance entered: its row exists from here, so one a guard ends at once still counts. */\n instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void>;\n nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void>;\n instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void>;\n /** The copy's row id; the row a retry already wrote, when there is one. */\n recordMessage(message: MessageRecord): Promise<string>;\n settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void>;\n /** An email's tracked links, in document order. */\n recordLinks(messageId: string, urls: readonly string[]): Promise<void>;\n /**\n * Record an open of the copy, judged by `judge` against the copy (its recipient and when it was\n * delivered — when it was sent, before the transport answered); `undefined` from the judge\n * records nothing. Read and written in one transaction. False for an unknown copy.\n */\n recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean>;\n /**\n * Record a click on the copy's link at `position`, judged by `judge` against the link, how\n * many links the copy has and its clicks of the last `windowMs`. The copy is locked for the\n * transaction, so clicks arriving together (a scanner following every link at once) are\n * judged one after another, each seeing the ones before. When the judge asks to `backdate`,\n * the window's earlier clicks are reclassified with this one's verdict. A click implies an\n * open. Undefined for an unknown link.\n */\n recordClick(\n messageId: string,\n position: number,\n at: number,\n windowMs: number,\n judge: (link: ClickContext) => { engagement: Engagement; backdate: boolean }\n ): Promise<{ url: string; engagement: Engagement } | undefined>;\n /**\n * The email copy's recipient opted out of email: recorded on the copy and as a suppression, in\n * one transaction, which also yields who the recipient is — so the caller acts on the\n * unsubscribe without a second read. Undefined for an unknown copy.\n */\n recordUnsubscribe(messageId: string, at: number): Promise<{ userId: string } | undefined>;\n /** A push copy the device reported it received. False for an unknown copy. */\n recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;\n /** Drop members of segments no longer deployed, then record every deployed segment's size. */\n snapshotSegments(at: number): Promise<{ segment: string; size: number }[]>;\n}\n\nexport interface JourneyStore {\n /** Where instances stand, every copy and its engagement, segment sizes. */\n readonly reporting: JourneyReporting;\n\n /**\n * Record that the user's data must go (a deleted account): the tombstone every write about\n * the user is conditional on, from here on and for good. Committed before anything is\n * stopped or erased, so an entry that got in before it is found by the erasure and none gets\n * in after it. Idempotent: a second request, or one for a user already erased, changes nothing.\n */\n requestErasure(userId: string, at: number): Promise<void>;\n /** Users whose erasure was requested and not carried out yet (`'erasing'`), oldest first. */\n pendingErasures(): Promise<string[]>;\n /**\n * Where the user stands: `'none'` (no tombstone), `'erasing'` (requested, their instances\n * being stopped, data still there) or `'erased'` (`forgetUser` went through). Both\n * tombstone states refuse every write about the user; the entry points read this for a fast\n * answer, and the store's conditional writes are the gate itself.\n */\n erasureState(userId: string): Promise<ErasureState>;\n /** The user's journey instances still running, by the entry ledger. */\n runningInstances(userId: string): Promise<RunningInstance[]>;\n /**\n * The runner's admission, before its first observable effect: records that the instance runs\n * (`admitted_at`, kept on replay) — unless the user has an erasure tombstone, in which case\n * nothing is recorded and the runner must not run. Mutually exclusive with `requestErasure`\n * and `forgetUser` for that user (Postgres: the user's advisory lock), so an erasure either\n * finds the instance admitted and stops it, or commits its tombstone first and the admission\n * is refused — never neither.\n *\n * A first admission needs the entry running. An instance already admitted is admitted again\n * whatever the entry's status — the legitimate replay of an instance whose finalisation was\n * cut short after the entry reached its terminal status, which resumes on its own checkpoint\n * and finishes what is left. Never a new attempt's way in: false for a terminal entry never\n * admitted, for an entry no longer in the ledger, for another user's entry, and for an\n * instance whose entry was reclaimed since (`enterJourney` resets the admission with the\n * instance id, so a superseded attempt cannot pass under the id it lost).\n */\n admitInstance(instanceId: string, userId: string): Promise<boolean>;\n /**\n * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment\n * memberships, entries and reporting — and mark the tombstone erased (`erased_at`), which\n * stays: a write that was in flight when the data went cannot bring the user back, and the\n * same id is never reactivated by ingest. Suppressions stay too: an opt-out is a compliance\n * record keyed by an opaque id, and it outlives the erasure. Run only once no instance of\n * theirs runs any more, or one could write some of it back. Idempotent. Mutually exclusive\n * with every write about the user (the user's advisory lock), so\n * the data is gone when this returns — nothing of theirs lands afterwards.\n */\n forgetUser(userId: string, at: number): Promise<void>;\n\n /** The user opted out of the channel (recorded by an unsubscribe). */\n isSuppressed(userId: string, channel: string): Promise<boolean>;\n\n /**\n * What the live database lacks against the engine's tables (read-only); a deploy refuses to\n * run while it lists anything.\n */\n checkSchema(): Promise<string[]>;\n\n /* ---------------------------------- events --------------------------------- */\n /**\n * Append the occurrence; false when its id was already in the log (nothing written). Throws\n * `UserErasedError` for a user with a tombstone, like every write about a user below.\n */\n insertEvent(input: EventInput): Promise<boolean>;\n /** Occurrences of `event` for the user, optionally only those within the window. */\n countEvents(userId: string, event: string, window?: EventWindow): Promise<number>;\n /** The payloads of those occurrences — the caller filters them with the shared evaluator. */\n listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]>;\n\n /* --------------------------------- profiles -------------------------------- */\n getProfile(userId: string): Promise<ProfileProps | undefined>;\n /**\n * Merge-patch `props` into the stored profile in one statement (a null\n * removes the property) and return the result. One statement, because a\n * read-modify-write loses one of two concurrent identifies.\n */\n mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps>;\n\n /**\n * Every user the engine knows (a profile or an event): who the segment sweep evaluates. Ids\n * come in ascending order; `after` resumes past the last id of the previous page, and `limit`\n * bounds the page (the whole list without one).\n */\n listUserIds(page?: { after?: string | undefined; limit?: number | undefined }): Promise<string[]>;\n\n /* ---------------------------------- devices --------------------------------- */\n /** The user's push devices, most recently registered first. */\n listDevices(userId: string): Promise<PushDevice[]>;\n /**\n * Register a device: one row per token, so a token registered again moves to the user who\n * registered it last (a phone signed into another account) and to the front of their list.\n */\n upsertDevice(device: DeviceInput): Promise<void>;\n /** Forget a token (reported dead by APNs / FCM); the user it belonged to, if any. */\n removeDevice(token: string): Promise<string | undefined>;\n /**\n * The user signed out on the device: the token is kept, bound to nobody, until the next sign-in\n * binds it again. The user it belonged to, if any.\n */\n unbindDevice(token: string): Promise<string | undefined>;\n\n /* ---------------------------- deployed definitions -------------------------- */\n getSegmentCondition(id: string): Promise<ConditionIR | undefined>;\n /** Every deployed segment with its definition: what the segment sweep evaluates. */\n listSegments(): Promise<{ id: string; condition: ConditionIR }[]>;\n findTriggers(event: string): Promise<TriggerRoute[]>;\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]>;\n putWorkflowIR(workflow: WorkflowIR): Promise<void>;\n getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined>;\n /**\n * Swap the routing tables (segments, event triggers, segment triggers) for\n * the bundle's — atomically, so a concurrent ingest never sees them half\n * empty. Workflow bodies are stored separately (`putWorkflowIR`) because they\n * are content-addressed and outlive the routes that point at them.\n */\n replaceRoutes(bundle: BundleIR): Promise<void>;\n /**\n * The Worker version whose bundle the routes came from, when one put them there through\n * `replaceRoutesIfNewer` (a forced deploy leaves it as it was). Read from the database itself,\n * not a cache in front of it.\n */\n liveBundleVersion(): Promise<BundleVersion | undefined>;\n /**\n * `replaceRoutes`, only when `version` is newer than the live one, recorded in the same\n * transaction: two versions serving side by side during a rollout cannot leave the older one's\n * routes in force. False, with nothing written, when a version as new or newer is live.\n */\n replaceRoutesIfNewer(bundle: BundleIR, version: BundleVersion): Promise<boolean>;\n\n /* ----------------------------- segment membership --------------------------- */\n isSegmentMember(segment: string, userId: string): Promise<boolean>;\n /** Record the membership, with the workflows its entry has to start (see segment_start). */\n addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void>;\n /** The workflows the member's entry has not started yet. */\n pendingSegmentStarts(segment: string, userId: string): Promise<string[]>;\n completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void>;\n /** Drop the membership and any start it still owed. */\n removeSegmentMember(segment: string, userId: string): Promise<void>;\n\n /* ------------------------------- entry ledger ------------------------------- */\n /**\n * Record the entry (the once policy). Atomic under concurrent ingests: of\n * two racing attempts exactly one is 'entered' (or 'reclaimed', when the\n * pair's previous instance is recorded as 'failed') and the other null.\n */\n enterJourney(entry: EntryInput): Promise<EntryOutcome>;\n removeEntry(instanceId: string): Promise<void>;\n setEntryStatus(instanceId: string, status: string): Promise<void>;\n /** Execution starts and wake callbacks, for a runtime that submits its starts (AWS). */\n readonly executions: ExecutionRegistry;\n\n /* ------------------------------ wake subscriptions --------------------------- */\n /** Distinct wake handles registered for (user, event). */\n findWakeHandles(userId: string, event: string): Promise<string[]>;\n /** Register the handle for each event; repeated registrations are idempotent. */\n subscribe(handle: string, userId: string, events: readonly string[], ts: number): Promise<void>;\n /** Drop every registration the handle holds. */\n unsubscribe(handle: string): Promise<void>;\n}\n\nexport { JourneyFactSource } from './facts';\nexport { PostgresJourneyStore } from './postgres';\nexport { PostgresReporting } from './postgres-reporting';\nexport {\n DEFAULT_SCHEMA,\n TABLES,\n renderDrizzleSchema,\n renderPostgresDdl,\n type TableSpec,\n} from './tables';\nexport type { PostgresJourneyStoreOptions, SqlClientLike } from './postgres';\n"],"mappings":";;;;;;;;;;AA2KA,IAAa,sBAAb,cAAyC,MAAM;CAGxB;CAFrB,OAAyB;CAEzB,YAAY,UAAsC;EAChD,MACE,4IAA4I,SAAS,KAAK,MAAM,GAClK;EAHmB,KAAA,WAAA;CAIrB;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/store/index.ts"],"sourcesContent":["import type { PushDevice } from '../engine/ports';\nimport type { BundleIR, ConditionIR, ScalarIR, WorkflowIR } from '../ir';\n\n/**\n * The journey engine's data plane. Postgres is the store (`PostgresJourneyStore`); this\n * interface is the port the host, the runner and the fact source use to persist or look\n * anything up, and what a test stub implements in its place. Execution (durable steps,\n * sleeps, wake-ups) is the workflow runtime's job and stays out of here.\n *\n * Timestamps are epoch milliseconds throughout; a store may persist them in\n * its native type as long as `sinceMs` comparisons behave.\n */\n\n/**\n * A profile patch or a stored profile. On the way in, `null` means \"remove\n * this property\" (RFC 7386 merge-patch, the only way the API has to unset\n * one); a stored profile never contains null.\n */\nexport type ProfileProps = Record<string, ScalarIR | null | undefined>;\n\nexport interface EventInput {\n /** The occurrence's identity, chosen by the sender; a second insert with the same id is a no-op. */\n id: string;\n userId: string;\n event: string;\n ts: number;\n payload: Record<string, unknown>;\n}\n\nexport interface TriggerRoute {\n workflow: string;\n hash: string;\n /** Payload gate (payload-only condition tree), or null when the trigger has none. */\n where: ConditionIR | null;\n /** Profile gate, or null. */\n filter: ConditionIR | null;\n /**\n * The code version that applied these routes (`replaceRoutesIfNewer`); absent after a forced\n * deploy. Read in the same row as the hash, so the pair is always one deploy's.\n */\n version?: string | undefined;\n}\n\nexport interface SegmentTriggerRoute {\n workflow: string;\n hash: string;\n segment: string;\n /** As `TriggerRoute.version`. */\n version?: string | undefined;\n}\n\n/**\n * A Worker version, as Cloudflare's version metadata binding names it: the bundle compiled into\n * that version goes live only over an older one (`replaceRoutesIfNewer`).\n */\nexport interface BundleVersion {\n id: string;\n /** When the version was created (epoch ms): later versions are newer. */\n createdAt: number;\n}\n\nexport interface EntryInput {\n workflow: string;\n userId: string;\n instanceId: string;\n hash: string;\n ts: number;\n /**\n * The instance's start, recorded in the same transaction as the entry — for a runtime whose\n * start is an asynchronous submit (AWS) that may have to be retried.\n */\n execution?: ExecutionStart | undefined;\n}\n\n/** How an instance is started on a runtime that submits it: replayed as is on every retry. */\nexport interface ExecutionStart {\n /** The runtime's idempotency key (the durable execution name). */\n name: string;\n /** What is invoked: a qualified function ARN, its version included. */\n target: string;\n /** The exact payload: a retried submit must send the same bytes, or the runtime refuses it. */\n input: string;\n}\n\nexport interface ExecutionRecord extends ExecutionStart {\n instanceId: string;\n workflow: string;\n userId: string;\n createdAt: number;\n submittedAt?: number | undefined;\n arn?: string | undefined;\n unresolvedAt?: number | undefined;\n callbackId?: string | undefined;\n /** Bumped by every wait the instance arms: a wake or a cleanup of an older one leaves it alone. */\n generation: number;\n deadlineAt?: number | undefined;\n checkedAt?: number | undefined;\n stoppedAt?: number | undefined;\n}\n\n/**\n * What a runtime that submits its starts and parks waits on one-shot callbacks (AWS) keeps\n * beside the entry ledger. The runtime holds the execution history; this holds only the\n * mapping from the engine's instance id to it.\n */\nexport interface ExecutionRegistry {\n get(instanceId: string): Promise<ExecutionRecord | undefined>;\n /**\n * Starts not yet confirmed and not given up on, oldest first: of one (workflow, user) entry\n * still running, or every one created before `createdBefore`.\n */\n pendingStarts(filter: {\n workflow?: string;\n userId?: string;\n createdBefore?: number;\n limit: number;\n }): Promise<ExecutionRecord[]>;\n markSubmitted(instanceId: string, arn: string | undefined, at: number): Promise<void>;\n markUnresolved(instanceId: string, at: number): Promise<void>;\n setArn(instanceId: string, arn: string): Promise<void>;\n /** Record the callback a wait parks on; false when a newer generation is already armed. */\n armCallback(\n instanceId: string,\n callback: { id: string; generation: number; deadlineAt?: number | undefined }\n ): Promise<boolean>;\n /** Forget the callback — only if it is still that generation's. */\n clearCallback(instanceId: string, generation: number): Promise<void>;\n /** Submitted executions whose entry is still running, least recently checked first. */\n toReconcile(limit: number, checkedBefore: number): Promise<ExecutionRecord[]>;\n markChecked(instanceId: string, at: number): Promise<void>;\n /** Record the first stop; a later one keeps it. */\n markStopped(instanceId: string, at: number): Promise<void>;\n}\n\n/**\n * How an entry attempt ended: a fresh row, a 'failed' row of a dead instance\n * taken over (the once policy does not bar a user over one outage), or\n * refused because the pair already entered and is still alive.\n */\nexport type EntryOutcome = 'entered' | 'reclaimed' | null;\n\n/** A device registered for pushes: its provider token belongs to the user who registered it last. */\nexport interface DeviceInput {\n userId: string;\n token: string;\n /** `ios` (APNs) or `android` (FCM): which provider the token belongs to. */\n platform: string;\n ts: number;\n}\n\n/** An instance of a user still in the ledger, and whether its runner was admitted (see `admitInstance`). */\nexport interface RunningInstance {\n instanceId: string;\n /** False until the runner admitted itself: nothing has run, and the tombstone keeps it that way. */\n admitted: boolean;\n}\n\n/** A store plus how to release what opening it acquired (a connection, say). */\nexport interface StoreLease {\n store: JourneyStore;\n close?: () => Promise<void>;\n}\n\nimport type { ErasureState } from './erasure';\n\nexport { type ErasureState, UserErasedError } from './erasure';\n\n/**\n * The live database lacks tables or columns the engine reads (an SDK upgrade added them, or the\n * host never ran the migration). Raised before a deploy writes anything.\n */\nexport class SchemaMismatchError extends Error {\n override readonly name = 'SchemaMismatchError';\n\n constructor(readonly problems: readonly string[]) {\n super(\n `the database does not match @shware/workflow's tables — regenerate the drizzle schema (workflow-ui generate) and run your migrations:\\n ${problems.join('\\n ')}`\n );\n }\n}\n\n/** A message copy as reporting records it, before it goes out. */\nexport interface MessageRecord {\n idempotencyKey: string;\n workflow: string;\n instanceId: string;\n nodeId: string;\n template: string;\n /** Where the copy lands: `email`, `push_ios`, `push_android`. */\n channel: string;\n userId: string;\n /** An email's subscription topic; null for a transactional email and for every other channel. */\n topic: string | null;\n sentAt: number;\n}\n\n/** What is known of a copy without its engagement: whose it is, where it went, its topic. */\nexport interface MessageSummary {\n userId: string;\n channel: string;\n topic: string | null;\n}\n\n/** One opt-out to set or clear: a topic of the channel, or the whole channel (`topic: null`). */\nexport interface SuppressionChange {\n topic: string | null;\n suppressed: boolean;\n}\n\n/** What a click is judged by. */\nexport interface ClickContext {\n url: string;\n deliveredAt: number;\n linkCount: number;\n /** The copy's clicks in the window before this one. */\n recent: { position: number; at: number }[];\n}\n\n/** An open or a click, with the verdict on who made it and where it came from. */\nexport interface Engagement {\n at: number;\n machine: boolean;\n /** The rule that called it a machine; null for a person. */\n reason: string | null;\n userAgent: string | null;\n /** The network the request came from (Cloudflare's `cf.asn`, `cf.asOrganization`, `cf.country`), never the address. */\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\n/**\n * Journey reporting: where each instance stands, every copy and how it was engaged with, segment\n * sizes. The store exposes it as `reporting`; the host records it and serves email tracking.\n * Every write is idempotent — a retried step reports again.\n */\n/** Bounds on when an event happened, both inclusive (epoch ms); an absent side is open. */\nexport interface EventWindow {\n sinceMs?: number;\n untilMs?: number;\n}\n\nexport interface JourneyReporting {\n /** The instance entered: its row exists from here, so one a guard ends at once still counts. */\n instanceStarted(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n at: number;\n }): Promise<void>;\n nodeReached(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n nodeId: string;\n at: number;\n }): Promise<void>;\n instanceFinished(input: {\n workflow: string;\n instanceId: string;\n userId: string;\n status: string;\n at: number;\n convertedAt?: number;\n }): Promise<void>;\n /** The copy's row id; the row a retry already wrote, when there is one. */\n recordMessage(message: MessageRecord): Promise<string>;\n settleMessage(\n idempotencyKey: string,\n result: { delivered: true } | { delivered: false; reason: string },\n at: number\n ): Promise<void>;\n /** An email's tracked links, in document order. */\n recordLinks(messageId: string, urls: readonly string[]): Promise<void>;\n /**\n * Record an open of the copy, judged by `judge` against the copy (its recipient and when it was\n * delivered — when it was sent, before the transport answered); `undefined` from the judge\n * records nothing. Read and written in one transaction. False for an unknown copy.\n */\n recordOpen(\n messageId: string,\n judge: (message: { userId: string; deliveredAt: number }) => Engagement | undefined\n ): Promise<boolean>;\n /**\n * Record a click on the copy's link at `position`, judged by `judge` against the link, how\n * many links the copy has and its clicks of the last `windowMs`. The copy is locked for the\n * transaction, so clicks arriving together (a scanner following every link at once) are\n * judged one after another, each seeing the ones before. When the judge asks to `backdate`,\n * the window's earlier clicks are reclassified with this one's verdict. A click implies an\n * open. Undefined for an unknown link.\n */\n recordClick(\n messageId: string,\n position: number,\n at: number,\n windowMs: number,\n judge: (link: ClickContext) => { engagement: Engagement; backdate: boolean }\n ): Promise<{ url: string; engagement: Engagement } | undefined>;\n /**\n * The email copy's recipient opted out: of the copy's topic, or with `scope: 'all'` of every\n * email. Recorded on the copy and as a suppression (the topic's row, or the channel-wide\n * null-topic row), in one transaction, which also yields who the recipient is and the topic —\n * so the caller acts on the unsubscribe without a second read. A transactional copy\n * (`topic: null`) has nothing to opt out of: nothing is recorded, and the answer says so.\n * Undefined for an unknown copy.\n */\n recordUnsubscribe(\n messageId: string,\n at: number,\n scope?: 'topic' | 'all'\n ): Promise<{ userId: string; topic: string | null } | undefined>;\n /** The copy's owner, channel and topic; undefined for an unknown copy. */\n lookupMessage(messageId: string): Promise<MessageSummary | undefined>;\n /** A push copy the device reported it received. False for an unknown copy. */\n recordDeviceDelivered(messageId: string, at: number): Promise<boolean>;\n /** Drop members of segments no longer deployed, then record every deployed segment's size. */\n snapshotSegments(at: number): Promise<{ segment: string; size: number }[]>;\n}\n\nexport interface JourneyStore {\n /** Where instances stand, every copy and its engagement, segment sizes. */\n readonly reporting: JourneyReporting;\n\n /**\n * Record that the user's data must go (a deleted account): the tombstone every write about\n * the user is conditional on, from here on and for good. Committed before anything is\n * stopped or erased, so an entry that got in before it is found by the erasure and none gets\n * in after it. Idempotent: a second request, or one for a user already erased, changes nothing.\n */\n requestErasure(userId: string, at: number): Promise<void>;\n /** Users whose erasure was requested and not carried out yet (`'erasing'`), oldest first. */\n pendingErasures(): Promise<string[]>;\n /**\n * Where the user stands: `'none'` (no tombstone), `'erasing'` (requested, their instances\n * being stopped, data still there) or `'erased'` (`forgetUser` went through). Both\n * tombstone states refuse every write about the user; the entry points read this for a fast\n * answer, and the store's conditional writes are the gate itself.\n */\n erasureState(userId: string): Promise<ErasureState>;\n /** The user's journey instances still running, by the entry ledger. */\n runningInstances(userId: string): Promise<RunningInstance[]>;\n /**\n * The runner's admission, before its first observable effect: records that the instance runs\n * (`admitted_at`, kept on replay) — unless the user has an erasure tombstone, in which case\n * nothing is recorded and the runner must not run. Mutually exclusive with `requestErasure`\n * and `forgetUser` for that user (Postgres: the user's advisory lock), so an erasure either\n * finds the instance admitted and stops it, or commits its tombstone first and the admission\n * is refused — never neither.\n *\n * A first admission needs the entry running. An instance already admitted is admitted again\n * whatever the entry's status — the legitimate replay of an instance whose finalisation was\n * cut short after the entry reached its terminal status, which resumes on its own checkpoint\n * and finishes what is left. Never a new attempt's way in: false for a terminal entry never\n * admitted, for an entry no longer in the ledger, for another user's entry, and for an\n * instance whose entry was reclaimed since (`enterJourney` resets the admission with the\n * instance id, so a superseded attempt cannot pass under the id it lost).\n */\n admitInstance(instanceId: string, userId: string): Promise<boolean>;\n /**\n * Erase everything kept about the user — profile, devices, events, wake subscriptions, segment\n * memberships, entries and reporting — and mark the tombstone erased (`erased_at`), which\n * stays: a write that was in flight when the data went cannot bring the user back, and the\n * same id is never reactivated by ingest — which is also why the suppressions go with the\n * rest: nothing is ever sent to the id again, so no opt-out needs keeping. Run only once no\n * instance of theirs runs any more, or one could write some of it back. Idempotent. Mutually\n * exclusive with every write about the user (the user's advisory lock), so the data is gone\n * when this returns — nothing of theirs lands afterwards.\n */\n forgetUser(userId: string, at: number): Promise<void>;\n\n /**\n * The user opted out of the channel (recorded by an unsubscribe, or set through\n * `/subscriptions`): with a `topic`, an opt-out of that topic or of the whole channel; without\n * one, only the whole channel.\n */\n isSuppressed(userId: string, channel: string, topic?: string): Promise<boolean>;\n /** Every opt-out of the user on the channel: the topics, and `null` for the whole channel. */\n listSuppressions(userId: string, channel: string): Promise<(string | null)[]>;\n /**\n * Set or clear opt-outs, all in one transaction: a suppressed change inserts the row (keeping\n * the time of one already there), an unsuppressed one deletes it. Written whatever the user's\n * erasure state — the caller refuses an erased user first — since an opt-out is never refused.\n */\n updateSuppressions(\n userId: string,\n channel: string,\n changes: readonly SuppressionChange[],\n at: number\n ): Promise<void>;\n\n /**\n * What the live database lacks against the engine's tables (read-only); a deploy refuses to\n * run while it lists anything.\n */\n checkSchema(): Promise<string[]>;\n\n /* ---------------------------------- events --------------------------------- */\n /**\n * Append the occurrence; false when its id was already in the log (nothing written). Throws\n * `UserErasedError` for a user with a tombstone, like every write about a user below.\n */\n insertEvent(input: EventInput): Promise<boolean>;\n /** Occurrences of `event` for the user, optionally only those within the window. */\n countEvents(userId: string, event: string, window?: EventWindow): Promise<number>;\n /** The payloads of those occurrences — the caller filters them with the shared evaluator. */\n listEventPayloads(\n userId: string,\n event: string,\n window?: EventWindow\n ): Promise<Record<string, unknown>[]>;\n\n /* --------------------------------- profiles -------------------------------- */\n getProfile(userId: string): Promise<ProfileProps | undefined>;\n /**\n * Merge-patch `props` into the stored profile in one statement (a null\n * removes the property) and return the result. One statement, because a\n * read-modify-write loses one of two concurrent identifies.\n */\n mergeProfile(userId: string, props: ProfileProps): Promise<ProfileProps>;\n\n /**\n * Every user the engine knows (a profile or an event): who the segment sweep evaluates. Ids\n * come in ascending order; `after` resumes past the last id of the previous page, and `limit`\n * bounds the page (the whole list without one).\n */\n listUserIds(page?: { after?: string | undefined; limit?: number | undefined }): Promise<string[]>;\n\n /* ---------------------------------- devices --------------------------------- */\n /** The user's push devices, most recently registered first. */\n listDevices(userId: string): Promise<PushDevice[]>;\n /**\n * Register a device: one row per token, so a token registered again moves to the user who\n * registered it last (a phone signed into another account) and to the front of their list.\n */\n upsertDevice(device: DeviceInput): Promise<void>;\n /** Forget a token (reported dead by APNs / FCM); the user it belonged to, if any. */\n removeDevice(token: string): Promise<string | undefined>;\n /**\n * The user signed out on the device: the token is kept, bound to nobody, until the next sign-in\n * binds it again. The user it belonged to, if any.\n */\n unbindDevice(token: string): Promise<string | undefined>;\n\n /* ---------------------------- deployed definitions -------------------------- */\n getSegmentCondition(id: string): Promise<ConditionIR | undefined>;\n /** Every deployed segment with its definition: what the segment sweep evaluates. */\n listSegments(): Promise<{ id: string; condition: ConditionIR }[]>;\n findTriggers(event: string): Promise<TriggerRoute[]>;\n listSegmentTriggers(): Promise<SegmentTriggerRoute[]>;\n putWorkflowIR(workflow: WorkflowIR): Promise<void>;\n getWorkflowIR(contentHash: string): Promise<WorkflowIR | undefined>;\n /**\n * Swap the routing tables (segments, event triggers, segment triggers) for\n * the bundle's — atomically, so a concurrent ingest never sees them half\n * empty. Workflow bodies are stored separately (`putWorkflowIR`) because they\n * are content-addressed and outlive the routes that point at them.\n */\n replaceRoutes(bundle: BundleIR): Promise<void>;\n /**\n * The Worker version whose bundle the routes came from, when one put them there through\n * `replaceRoutesIfNewer` (a forced deploy leaves it as it was). Read from the database itself,\n * not a cache in front of it.\n */\n liveBundleVersion(): Promise<BundleVersion | undefined>;\n /**\n * `replaceRoutes`, only when `version` is newer than the live one, recorded in the same\n * transaction: two versions serving side by side during a rollout cannot leave the older one's\n * routes in force. False, with nothing written, when a version as new or newer is live.\n */\n replaceRoutesIfNewer(bundle: BundleIR, version: BundleVersion): Promise<boolean>;\n\n /* ----------------------------- segment membership --------------------------- */\n isSegmentMember(segment: string, userId: string): Promise<boolean>;\n /** Record the membership, with the workflows its entry has to start (see segment_start). */\n addSegmentMember(\n segment: string,\n userId: string,\n ts: number,\n workflows: readonly string[]\n ): Promise<void>;\n /** The workflows the member's entry has not started yet. */\n pendingSegmentStarts(segment: string, userId: string): Promise<string[]>;\n completeSegmentStart(segment: string, userId: string, workflow: string): Promise<void>;\n /** Drop the membership and any start it still owed. */\n removeSegmentMember(segment: string, userId: string): Promise<void>;\n\n /* ------------------------------- entry ledger ------------------------------- */\n /**\n * Record the entry (the once policy). Atomic under concurrent ingests: of\n * two racing attempts exactly one is 'entered' (or 'reclaimed', when the\n * pair's previous instance is recorded as 'failed') and the other null.\n */\n enterJourney(entry: EntryInput): Promise<EntryOutcome>;\n removeEntry(instanceId: string): Promise<void>;\n setEntryStatus(instanceId: string, status: string): Promise<void>;\n /** Execution starts and wake callbacks, for a runtime that submits its starts (AWS). */\n readonly executions: ExecutionRegistry;\n\n /* ------------------------------ wake subscriptions --------------------------- */\n /** Distinct wake handles registered for (user, event). */\n findWakeHandles(userId: string, event: string): Promise<string[]>;\n /** Register the handle for each event; repeated registrations are idempotent. */\n subscribe(handle: string, userId: string, events: readonly string[], ts: number): Promise<void>;\n /** Drop every registration the handle holds. */\n unsubscribe(handle: string): Promise<void>;\n}\n\nexport { JourneyFactSource } from './facts';\nexport { PostgresJourneyStore } from './postgres';\nexport { PostgresReporting } from './postgres-reporting';\nexport {\n DEFAULT_SCHEMA,\n TABLES,\n renderDrizzleSchema,\n renderPostgresDdl,\n type TableSpec,\n type UniqueConstraintSpec,\n} from './tables';\nexport type { PostgresJourneyStoreOptions, SqlClientLike } from './postgres';\n"],"mappings":";;;;;;;;;;AA2KA,IAAa,sBAAb,cAAyC,MAAM;CAGxB;CAFrB,OAAyB;CAEzB,YAAY,UAAsC;EAChD,MACE,4IAA4I,SAAS,KAAK,MAAM,GAClK;EAHmB,KAAA,WAAA;CAIrB;AACF"}
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_store_erasure = require("./erasure.cjs");
3
3
  const require_store_sql = require("./sql.cjs");
4
4
  const require_store_user_lock = require("./user-lock.cjs");
5
- //#region src/store/postgres-reporting.ts
5
+ // src/store/postgres-reporting.ts
6
6
  /**
7
7
  * Epoch milliseconds → timestamptz, and back: numbers in and out, whatever the driver maps (a
8
8
  * driver may hand a double or a bigint count back as a string).
@@ -113,8 +113,8 @@ var PostgresReporting = class {
113
113
  return this.sql.transaction(async (tx) => {
114
114
  await require_store_user_lock.lockUserTransaction(tx, this.schema, message.userId);
115
115
  const id = (await tx.query(`INSERT INTO ${this.t.message}
116
- (id, idempotency_key, workflow, instance_id, node_id, template, channel, user_id, sent_at)
117
- SELECT $1, $2, $3, $4, $5, $6, $7, $8, ${TS("$9")} ${this.notErased("$8")}
116
+ (id, idempotency_key, workflow, instance_id, node_id, template, channel, user_id, topic, sent_at)
117
+ SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9::text, ${TS("$10")} ${this.notErased("$8")}
118
118
  ON CONFLICT (idempotency_key) DO UPDATE SET idempotency_key = EXCLUDED.idempotency_key
119
119
  RETURNING id`, [
120
120
  require_store_sql.uuidv7(message.sentAt),
@@ -125,6 +125,7 @@ var PostgresReporting = class {
125
125
  message.template,
126
126
  message.channel,
127
127
  message.userId,
128
+ message.topic,
128
129
  message.sentAt
129
130
  ])).at(0)?.id;
130
131
  if (id !== void 0) return id;
@@ -241,18 +242,37 @@ var PostgresReporting = class {
241
242
  WHERE id = $1 RETURNING id`, [messageId, at])).length > 0;
242
243
  });
243
244
  }
244
- async recordUnsubscribe(messageId, at) {
245
+ async lookupMessage(messageId) {
246
+ const row = (await this.sql.query(`SELECT user_id, channel, topic FROM ${this.t.message} WHERE id = $1`, [messageId])).at(0);
247
+ return row === void 0 ? void 0 : {
248
+ userId: row.user_id,
249
+ channel: row.channel,
250
+ topic: row.topic
251
+ };
252
+ }
253
+ async recordUnsubscribe(messageId, at, scope = "topic") {
245
254
  return this.sql.transaction(async (tx) => {
246
255
  await require_store_user_lock.beginReadCommitted(tx);
247
- const owner = (await tx.query(`SELECT user_id FROM ${this.t.message} WHERE id = $1 AND channel = 'email'`, [messageId])).at(0);
256
+ const owner = (await tx.query(`SELECT user_id, topic FROM ${this.t.message} WHERE id = $1 AND channel = 'email'`, [messageId])).at(0);
248
257
  if (owner === void 0) return void 0;
258
+ if (owner.topic === null) return {
259
+ userId: owner.user_id,
260
+ topic: null
261
+ };
249
262
  await require_store_user_lock.lockUser(tx, this.schema, owner.user_id);
250
- const userId = (await tx.query(`UPDATE ${this.t.message} SET unsubscribed_at = coalesce(unsubscribed_at, ${TS("$2")})
251
- WHERE id = $1 AND channel = 'email' RETURNING user_id`, [messageId, at])).at(0)?.user_id;
252
- if (userId === void 0) return void 0;
253
- await tx.query(`INSERT INTO ${this.t.suppression} (user_id, channel, ts) VALUES ($1, 'email', ${TS("$2")})
254
- ON CONFLICT DO NOTHING`, [userId, at]);
255
- return { userId };
263
+ const row = (await tx.query(`UPDATE ${this.t.message} SET unsubscribed_at = coalesce(unsubscribed_at, ${TS("$2")})
264
+ WHERE id = $1 AND channel = 'email' RETURNING user_id, topic`, [messageId, at])).at(0);
265
+ if (row === void 0) return void 0;
266
+ await tx.query(`INSERT INTO ${this.t.suppression} (user_id, channel, topic, ts)
267
+ VALUES ($1, 'email', $2::text, ${TS("$3")}) ON CONFLICT DO NOTHING`, [
268
+ row.user_id,
269
+ scope === "all" ? null : row.topic,
270
+ at
271
+ ]);
272
+ return {
273
+ userId: row.user_id,
274
+ topic: row.topic
275
+ };
256
276
  });
257
277
  }
258
278
  async snapshotSegments(at) {
@@ -270,7 +290,6 @@ var PostgresReporting = class {
270
290
  });
271
291
  }
272
292
  };
273
- //#endregion
274
293
  exports.PostgresReporting = PostgresReporting;
275
294
 
276
295
  //# sourceMappingURL=postgres-reporting.cjs.map