@shware/workflow 0.0.0-stage → 0.1.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 (442) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +154 -2
  3. package/dist/_virtual/_rolldown/runtime.cjs +23 -0
  4. package/dist/apns-relay.cjs +105 -0
  5. package/dist/apns-relay.cjs.map +1 -0
  6. package/dist/apns-relay.d.cts +28 -0
  7. package/dist/apns-relay.d.cts.map +1 -0
  8. package/dist/apns-relay.d.mts +28 -0
  9. package/dist/apns-relay.d.mts.map +1 -0
  10. package/dist/apns-relay.mjs +104 -0
  11. package/dist/apns-relay.mjs.map +1 -0
  12. package/dist/apns.cjs +121 -0
  13. package/dist/apns.cjs.map +1 -0
  14. package/dist/apns.d.cts +63 -0
  15. package/dist/apns.d.cts.map +1 -0
  16. package/dist/apns.d.mts +63 -0
  17. package/dist/apns.d.mts.map +1 -0
  18. package/dist/apns.mjs +116 -0
  19. package/dist/apns.mjs.map +1 -0
  20. package/dist/client.cjs +125 -0
  21. package/dist/client.cjs.map +1 -0
  22. package/dist/client.d.cts +108 -0
  23. package/dist/client.d.cts.map +1 -0
  24. package/dist/client.d.mts +108 -0
  25. package/dist/client.d.mts.map +1 -0
  26. package/dist/client.mjs +122 -0
  27. package/dist/client.mjs.map +1 -0
  28. package/dist/cloudflare/bindings.cjs +28 -0
  29. package/dist/cloudflare/bindings.cjs.map +1 -0
  30. package/dist/cloudflare/bindings.d.cts +144 -0
  31. package/dist/cloudflare/bindings.d.cts.map +1 -0
  32. package/dist/cloudflare/bindings.d.mts +144 -0
  33. package/dist/cloudflare/bindings.d.mts.map +1 -0
  34. package/dist/cloudflare/bindings.mjs +25 -0
  35. package/dist/cloudflare/bindings.mjs.map +1 -0
  36. package/dist/cloudflare/channels.cjs +164 -0
  37. package/dist/cloudflare/channels.cjs.map +1 -0
  38. package/dist/cloudflare/channels.d.cts +29 -0
  39. package/dist/cloudflare/channels.d.cts.map +1 -0
  40. package/dist/cloudflare/channels.d.mts +29 -0
  41. package/dist/cloudflare/channels.d.mts.map +1 -0
  42. package/dist/cloudflare/channels.mjs +161 -0
  43. package/dist/cloudflare/channels.mjs.map +1 -0
  44. package/dist/cloudflare/d1-env.cjs +17 -0
  45. package/dist/cloudflare/d1-env.cjs.map +1 -0
  46. package/dist/cloudflare/d1-env.d.cts +12 -0
  47. package/dist/cloudflare/d1-env.d.cts.map +1 -0
  48. package/dist/cloudflare/d1-env.d.mts +12 -0
  49. package/dist/cloudflare/d1-env.d.mts.map +1 -0
  50. package/dist/cloudflare/d1-env.mjs +16 -0
  51. package/dist/cloudflare/d1-env.mjs.map +1 -0
  52. package/dist/cloudflare/index.cjs +54 -0
  53. package/dist/cloudflare/index.d.cts +19 -0
  54. package/dist/cloudflare/index.d.mts +19 -0
  55. package/dist/cloudflare/index.mjs +16 -0
  56. package/dist/cloudflare/router.cjs +516 -0
  57. package/dist/cloudflare/router.cjs.map +1 -0
  58. package/dist/cloudflare/router.d.cts +157 -0
  59. package/dist/cloudflare/router.d.cts.map +1 -0
  60. package/dist/cloudflare/router.d.mts +157 -0
  61. package/dist/cloudflare/router.d.mts.map +1 -0
  62. package/dist/cloudflare/router.mjs +503 -0
  63. package/dist/cloudflare/router.mjs.map +1 -0
  64. package/dist/cloudflare/runner.cjs +225 -0
  65. package/dist/cloudflare/runner.cjs.map +1 -0
  66. package/dist/cloudflare/runner.d.cts +73 -0
  67. package/dist/cloudflare/runner.d.cts.map +1 -0
  68. package/dist/cloudflare/runner.d.mts +73 -0
  69. package/dist/cloudflare/runner.d.mts.map +1 -0
  70. package/dist/cloudflare/runner.mjs +224 -0
  71. package/dist/cloudflare/runner.mjs.map +1 -0
  72. package/dist/cloudflare/schema.sql +127 -0
  73. package/dist/cloudflare/senders.cjs +114 -0
  74. package/dist/cloudflare/senders.cjs.map +1 -0
  75. package/dist/cloudflare/senders.d.cts +68 -0
  76. package/dist/cloudflare/senders.d.cts.map +1 -0
  77. package/dist/cloudflare/senders.d.mts +68 -0
  78. package/dist/cloudflare/senders.d.mts.map +1 -0
  79. package/dist/cloudflare/senders.mjs +108 -0
  80. package/dist/cloudflare/senders.mjs.map +1 -0
  81. package/dist/cloudflare/worker.cjs +228 -0
  82. package/dist/cloudflare/worker.cjs.map +1 -0
  83. package/dist/cloudflare/worker.d.cts +92 -0
  84. package/dist/cloudflare/worker.d.cts.map +1 -0
  85. package/dist/cloudflare/worker.d.mts +92 -0
  86. package/dist/cloudflare/worker.d.mts.map +1 -0
  87. package/dist/cloudflare/worker.mjs +224 -0
  88. package/dist/cloudflare/worker.mjs.map +1 -0
  89. package/dist/cloudflare/workers.d.cjs +0 -0
  90. package/dist/cloudflare/workers.d.cts +44 -0
  91. package/dist/cloudflare/workers.d.cts.map +1 -0
  92. package/dist/cloudflare/workers.d.mts +44 -0
  93. package/dist/cloudflare/workers.d.mts.map +1 -0
  94. package/dist/config.cjs +151 -0
  95. package/dist/config.cjs.map +1 -0
  96. package/dist/config.d.cts +149 -0
  97. package/dist/config.d.cts.map +1 -0
  98. package/dist/config.d.mts +149 -0
  99. package/dist/config.d.mts.map +1 -0
  100. package/dist/config.mjs +143 -0
  101. package/dist/config.mjs.map +1 -0
  102. package/dist/contract.cjs +212 -0
  103. package/dist/contract.cjs.map +1 -0
  104. package/dist/contract.d.cts +90 -0
  105. package/dist/contract.d.cts.map +1 -0
  106. package/dist/contract.d.mts +90 -0
  107. package/dist/contract.d.mts.map +1 -0
  108. package/dist/contract.mjs +206 -0
  109. package/dist/contract.mjs.map +1 -0
  110. package/dist/dsl/action.cjs +29 -0
  111. package/dist/dsl/action.cjs.map +1 -0
  112. package/dist/dsl/action.d.cts +64 -0
  113. package/dist/dsl/action.d.cts.map +1 -0
  114. package/dist/dsl/action.d.mts +64 -0
  115. package/dist/dsl/action.d.mts.map +1 -0
  116. package/dist/dsl/action.mjs +28 -0
  117. package/dist/dsl/action.mjs.map +1 -0
  118. package/dist/dsl/base.cjs +34 -0
  119. package/dist/dsl/base.cjs.map +1 -0
  120. package/dist/dsl/base.d.cts +45 -0
  121. package/dist/dsl/base.d.cts.map +1 -0
  122. package/dist/dsl/base.d.mts +45 -0
  123. package/dist/dsl/base.d.mts.map +1 -0
  124. package/dist/dsl/base.mjs +30 -0
  125. package/dist/dsl/base.mjs.map +1 -0
  126. package/dist/dsl/bundle.cjs +207 -0
  127. package/dist/dsl/bundle.cjs.map +1 -0
  128. package/dist/dsl/bundle.d.cts +19 -0
  129. package/dist/dsl/bundle.d.cts.map +1 -0
  130. package/dist/dsl/bundle.d.mts +19 -0
  131. package/dist/dsl/bundle.d.mts.map +1 -0
  132. package/dist/dsl/bundle.mjs +206 -0
  133. package/dist/dsl/bundle.mjs.map +1 -0
  134. package/dist/dsl/condition.cjs +177 -0
  135. package/dist/dsl/condition.cjs.map +1 -0
  136. package/dist/dsl/condition.d.cts +140 -0
  137. package/dist/dsl/condition.d.cts.map +1 -0
  138. package/dist/dsl/condition.d.mts +140 -0
  139. package/dist/dsl/condition.d.mts.map +1 -0
  140. package/dist/dsl/condition.mjs +156 -0
  141. package/dist/dsl/condition.mjs.map +1 -0
  142. package/dist/dsl/flow.cjs +228 -0
  143. package/dist/dsl/flow.cjs.map +1 -0
  144. package/dist/dsl/flow.d.cts +223 -0
  145. package/dist/dsl/flow.d.cts.map +1 -0
  146. package/dist/dsl/flow.d.mts +223 -0
  147. package/dist/dsl/flow.d.mts.map +1 -0
  148. package/dist/dsl/flow.mjs +226 -0
  149. package/dist/dsl/flow.mjs.map +1 -0
  150. package/dist/dsl/index.cjs +38 -0
  151. package/dist/dsl/index.d.cts +10 -0
  152. package/dist/dsl/index.d.mts +10 -0
  153. package/dist/dsl/index.mjs +9 -0
  154. package/dist/dsl/refs.cjs +59 -0
  155. package/dist/dsl/refs.cjs.map +1 -0
  156. package/dist/dsl/refs.d.cts +88 -0
  157. package/dist/dsl/refs.d.cts.map +1 -0
  158. package/dist/dsl/refs.d.mts +88 -0
  159. package/dist/dsl/refs.d.mts.map +1 -0
  160. package/dist/dsl/refs.mjs +55 -0
  161. package/dist/dsl/refs.mjs.map +1 -0
  162. package/dist/dsl/template.cjs +65 -0
  163. package/dist/dsl/template.cjs.map +1 -0
  164. package/dist/dsl/template.d.cts +75 -0
  165. package/dist/dsl/template.d.cts.map +1 -0
  166. package/dist/dsl/template.d.mts +75 -0
  167. package/dist/dsl/template.d.mts.map +1 -0
  168. package/dist/dsl/template.mjs +63 -0
  169. package/dist/dsl/template.mjs.map +1 -0
  170. package/dist/dsl/trigger.cjs +40 -0
  171. package/dist/dsl/trigger.cjs.map +1 -0
  172. package/dist/dsl/trigger.d.cts +65 -0
  173. package/dist/dsl/trigger.d.cts.map +1 -0
  174. package/dist/dsl/trigger.d.mts +65 -0
  175. package/dist/dsl/trigger.d.mts.map +1 -0
  176. package/dist/dsl/trigger.mjs +39 -0
  177. package/dist/dsl/trigger.mjs.map +1 -0
  178. package/dist/dsl/workflow.cjs +121 -0
  179. package/dist/dsl/workflow.cjs.map +1 -0
  180. package/dist/dsl/workflow.d.cts +59 -0
  181. package/dist/dsl/workflow.d.cts.map +1 -0
  182. package/dist/dsl/workflow.d.mts +59 -0
  183. package/dist/dsl/workflow.d.mts.map +1 -0
  184. package/dist/dsl/workflow.mjs +120 -0
  185. package/dist/dsl/workflow.mjs.map +1 -0
  186. package/dist/engine/actions.cjs +27 -0
  187. package/dist/engine/actions.cjs.map +1 -0
  188. package/dist/engine/actions.d.cts +40 -0
  189. package/dist/engine/actions.d.cts.map +1 -0
  190. package/dist/engine/actions.d.mts +40 -0
  191. package/dist/engine/actions.d.mts.map +1 -0
  192. package/dist/engine/actions.mjs +26 -0
  193. package/dist/engine/actions.mjs.map +1 -0
  194. package/dist/engine/bucket.cjs +72 -0
  195. package/dist/engine/bucket.cjs.map +1 -0
  196. package/dist/engine/bucket.d.cts +32 -0
  197. package/dist/engine/bucket.d.cts.map +1 -0
  198. package/dist/engine/bucket.d.mts +32 -0
  199. package/dist/engine/bucket.d.mts.map +1 -0
  200. package/dist/engine/bucket.mjs +69 -0
  201. package/dist/engine/bucket.mjs.map +1 -0
  202. package/dist/engine/condition.cjs +166 -0
  203. package/dist/engine/condition.cjs.map +1 -0
  204. package/dist/engine/condition.d.cts +52 -0
  205. package/dist/engine/condition.d.cts.map +1 -0
  206. package/dist/engine/condition.d.mts +52 -0
  207. package/dist/engine/condition.d.mts.map +1 -0
  208. package/dist/engine/condition.mjs +161 -0
  209. package/dist/engine/condition.mjs.map +1 -0
  210. package/dist/engine/index.cjs +20 -0
  211. package/dist/engine/index.d.cts +8 -0
  212. package/dist/engine/index.d.mts +8 -0
  213. package/dist/engine/index.mjs +7 -0
  214. package/dist/engine/interpreter.cjs +428 -0
  215. package/dist/engine/interpreter.cjs.map +1 -0
  216. package/dist/engine/interpreter.d.cts +6 -0
  217. package/dist/engine/interpreter.d.cts.map +1 -0
  218. package/dist/engine/interpreter.d.mts +6 -0
  219. package/dist/engine/interpreter.d.mts.map +1 -0
  220. package/dist/engine/interpreter.mjs +427 -0
  221. package/dist/engine/interpreter.mjs.map +1 -0
  222. package/dist/engine/ports.cjs +0 -0
  223. package/dist/engine/ports.d.cts +252 -0
  224. package/dist/engine/ports.d.cts.map +1 -0
  225. package/dist/engine/ports.d.mts +252 -0
  226. package/dist/engine/ports.d.mts.map +1 -0
  227. package/dist/engine/ports.mjs +1 -0
  228. package/dist/engine/recipient.cjs +23 -0
  229. package/dist/engine/recipient.cjs.map +1 -0
  230. package/dist/engine/recipient.d.cts +13 -0
  231. package/dist/engine/recipient.d.cts.map +1 -0
  232. package/dist/engine/recipient.d.mts +13 -0
  233. package/dist/engine/recipient.d.mts.map +1 -0
  234. package/dist/engine/recipient.mjs +22 -0
  235. package/dist/engine/recipient.mjs.map +1 -0
  236. package/dist/engine/time-scale.cjs +54 -0
  237. package/dist/engine/time-scale.cjs.map +1 -0
  238. package/dist/engine/time-scale.d.cts +31 -0
  239. package/dist/engine/time-scale.d.cts.map +1 -0
  240. package/dist/engine/time-scale.d.mts +31 -0
  241. package/dist/engine/time-scale.d.mts.map +1 -0
  242. package/dist/engine/time-scale.mjs +52 -0
  243. package/dist/engine/time-scale.mjs.map +1 -0
  244. package/dist/engine/time-window.cjs +149 -0
  245. package/dist/engine/time-window.cjs.map +1 -0
  246. package/dist/engine/time-window.d.cts +22 -0
  247. package/dist/engine/time-window.d.cts.map +1 -0
  248. package/dist/engine/time-window.d.mts +22 -0
  249. package/dist/engine/time-window.d.mts.map +1 -0
  250. package/dist/engine/time-window.mjs +147 -0
  251. package/dist/engine/time-window.mjs.map +1 -0
  252. package/dist/fcm.cjs +125 -0
  253. package/dist/fcm.cjs.map +1 -0
  254. package/dist/fcm.d.cts +48 -0
  255. package/dist/fcm.d.cts.map +1 -0
  256. package/dist/fcm.d.mts +48 -0
  257. package/dist/fcm.d.mts.map +1 -0
  258. package/dist/fcm.mjs +121 -0
  259. package/dist/fcm.mjs.map +1 -0
  260. package/dist/hash.cjs +245 -0
  261. package/dist/hash.cjs.map +1 -0
  262. package/dist/hash.d.cts +30 -0
  263. package/dist/hash.d.cts.map +1 -0
  264. package/dist/hash.d.mts +30 -0
  265. package/dist/hash.d.mts.map +1 -0
  266. package/dist/hash.mjs +239 -0
  267. package/dist/hash.mjs.map +1 -0
  268. package/dist/index.cjs +100 -0
  269. package/dist/index.d.cts +18 -0
  270. package/dist/index.d.mts +18 -0
  271. package/dist/index.mjs +17 -0
  272. package/dist/ir.cjs +366 -0
  273. package/dist/ir.cjs.map +1 -0
  274. package/dist/ir.d.cts +486 -0
  275. package/dist/ir.d.cts.map +1 -0
  276. package/dist/ir.d.mts +486 -0
  277. package/dist/ir.d.mts.map +1 -0
  278. package/dist/ir.mjs +344 -0
  279. package/dist/ir.mjs.map +1 -0
  280. package/dist/jwt.cjs +22 -0
  281. package/dist/jwt.cjs.map +1 -0
  282. package/dist/jwt.d.cts +9 -0
  283. package/dist/jwt.d.cts.map +1 -0
  284. package/dist/jwt.d.mts +9 -0
  285. package/dist/jwt.d.mts.map +1 -0
  286. package/dist/jwt.mjs +20 -0
  287. package/dist/jwt.mjs.map +1 -0
  288. package/dist/plan.cjs +223 -0
  289. package/dist/plan.cjs.map +1 -0
  290. package/dist/plan.d.cts +68 -0
  291. package/dist/plan.d.cts.map +1 -0
  292. package/dist/plan.d.mts +68 -0
  293. package/dist/plan.d.mts.map +1 -0
  294. package/dist/plan.mjs +221 -0
  295. package/dist/plan.mjs.map +1 -0
  296. package/dist/postgres-js.cjs +42 -0
  297. package/dist/postgres-js.cjs.map +1 -0
  298. package/dist/postgres-js.d.cts +28 -0
  299. package/dist/postgres-js.d.cts.map +1 -0
  300. package/dist/postgres-js.d.mts +28 -0
  301. package/dist/postgres-js.d.mts.map +1 -0
  302. package/dist/postgres-js.mjs +38 -0
  303. package/dist/postgres-js.mjs.map +1 -0
  304. package/dist/provenance.cjs +67 -0
  305. package/dist/provenance.cjs.map +1 -0
  306. package/dist/provenance.d.cts +41 -0
  307. package/dist/provenance.d.cts.map +1 -0
  308. package/dist/provenance.d.mts +41 -0
  309. package/dist/provenance.d.mts.map +1 -0
  310. package/dist/provenance.mjs +65 -0
  311. package/dist/provenance.mjs.map +1 -0
  312. package/dist/push.cjs +14 -0
  313. package/dist/push.cjs.map +1 -0
  314. package/dist/push.d.cts +16 -0
  315. package/dist/push.d.cts.map +1 -0
  316. package/dist/push.d.mts +16 -0
  317. package/dist/push.d.mts.map +1 -0
  318. package/dist/push.mjs +13 -0
  319. package/dist/push.mjs.map +1 -0
  320. package/dist/react-email.cjs +48 -0
  321. package/dist/react-email.cjs.map +1 -0
  322. package/dist/react-email.d.cts +7 -0
  323. package/dist/react-email.d.cts.map +1 -0
  324. package/dist/react-email.d.mts +7 -0
  325. package/dist/react-email.d.mts.map +1 -0
  326. package/dist/react-email.mjs +47 -0
  327. package/dist/react-email.mjs.map +1 -0
  328. package/dist/reporting/classify.cjs +42 -0
  329. package/dist/reporting/classify.cjs.map +1 -0
  330. package/dist/reporting/classify.d.cts +60 -0
  331. package/dist/reporting/classify.d.cts.map +1 -0
  332. package/dist/reporting/classify.d.mts +60 -0
  333. package/dist/reporting/classify.d.mts.map +1 -0
  334. package/dist/reporting/classify.mjs +38 -0
  335. package/dist/reporting/classify.mjs.map +1 -0
  336. package/dist/reporting/observer.cjs +63 -0
  337. package/dist/reporting/observer.cjs.map +1 -0
  338. package/dist/reporting/observer.d.cts +18 -0
  339. package/dist/reporting/observer.d.cts.map +1 -0
  340. package/dist/reporting/observer.d.mts +18 -0
  341. package/dist/reporting/observer.d.mts.map +1 -0
  342. package/dist/reporting/observer.mjs +62 -0
  343. package/dist/reporting/observer.mjs.map +1 -0
  344. package/dist/reporting/tracking.cjs +153 -0
  345. package/dist/reporting/tracking.cjs.map +1 -0
  346. package/dist/reporting/tracking.d.cts +43 -0
  347. package/dist/reporting/tracking.d.cts.map +1 -0
  348. package/dist/reporting/tracking.d.mts +43 -0
  349. package/dist/reporting/tracking.d.mts.map +1 -0
  350. package/dist/reporting/tracking.mjs +151 -0
  351. package/dist/reporting/tracking.mjs.map +1 -0
  352. package/dist/runtime.cjs +19 -0
  353. package/dist/runtime.cjs.map +1 -0
  354. package/dist/runtime.d.cts +30 -0
  355. package/dist/runtime.d.cts.map +1 -0
  356. package/dist/runtime.d.mts +30 -0
  357. package/dist/runtime.d.mts.map +1 -0
  358. package/dist/runtime.mjs +18 -0
  359. package/dist/runtime.mjs.map +1 -0
  360. package/dist/store/d1.cjs +185 -0
  361. package/dist/store/d1.cjs.map +1 -0
  362. package/dist/store/d1.d.cts +55 -0
  363. package/dist/store/d1.d.cts.map +1 -0
  364. package/dist/store/d1.d.mts +55 -0
  365. package/dist/store/d1.d.mts.map +1 -0
  366. package/dist/store/d1.mjs +184 -0
  367. package/dist/store/d1.mjs.map +1 -0
  368. package/dist/store/facts.cjs +60 -0
  369. package/dist/store/facts.cjs.map +1 -0
  370. package/dist/store/facts.d.cts +38 -0
  371. package/dist/store/facts.d.cts.map +1 -0
  372. package/dist/store/facts.d.mts +38 -0
  373. package/dist/store/facts.d.mts.map +1 -0
  374. package/dist/store/facts.mjs +58 -0
  375. package/dist/store/facts.mjs.map +1 -0
  376. package/dist/store/index.cjs +31 -0
  377. package/dist/store/index.cjs.map +1 -0
  378. package/dist/store/index.d.cts +291 -0
  379. package/dist/store/index.d.cts.map +1 -0
  380. package/dist/store/index.d.mts +291 -0
  381. package/dist/store/index.d.mts.map +1 -0
  382. package/dist/store/index.mjs +22 -0
  383. package/dist/store/index.mjs.map +1 -0
  384. package/dist/store/postgres-reporting.cjs +213 -0
  385. package/dist/store/postgres-reporting.cjs.map +1 -0
  386. package/dist/store/postgres-reporting.d.cts +63 -0
  387. package/dist/store/postgres-reporting.d.cts.map +1 -0
  388. package/dist/store/postgres-reporting.d.mts +63 -0
  389. package/dist/store/postgres-reporting.d.mts.map +1 -0
  390. package/dist/store/postgres-reporting.mjs +212 -0
  391. package/dist/store/postgres-reporting.mjs.map +1 -0
  392. package/dist/store/postgres.cjs +309 -0
  393. package/dist/store/postgres.cjs.map +1 -0
  394. package/dist/store/postgres.d.cts +77 -0
  395. package/dist/store/postgres.d.cts.map +1 -0
  396. package/dist/store/postgres.d.mts +77 -0
  397. package/dist/store/postgres.d.mts.map +1 -0
  398. package/dist/store/postgres.mjs +306 -0
  399. package/dist/store/postgres.mjs.map +1 -0
  400. package/dist/store/sql.cjs +24 -0
  401. package/dist/store/sql.cjs.map +1 -0
  402. package/dist/store/sql.d.cts +25 -0
  403. package/dist/store/sql.d.cts.map +1 -0
  404. package/dist/store/sql.d.mts +25 -0
  405. package/dist/store/sql.d.mts.map +1 -0
  406. package/dist/store/sql.mjs +23 -0
  407. package/dist/store/sql.mjs.map +1 -0
  408. package/dist/store/tables.cjs +404 -0
  409. package/dist/store/tables.cjs.map +1 -0
  410. package/dist/store/tables.d.cts +81 -0
  411. package/dist/store/tables.d.cts.map +1 -0
  412. package/dist/store/tables.d.mts +81 -0
  413. package/dist/store/tables.d.mts.map +1 -0
  414. package/dist/store/tables.mjs +399 -0
  415. package/dist/store/tables.mjs.map +1 -0
  416. package/dist/templates.cjs +247 -0
  417. package/dist/templates.cjs.map +1 -0
  418. package/dist/templates.d.cts +187 -0
  419. package/dist/templates.d.cts.map +1 -0
  420. package/dist/templates.d.mts +187 -0
  421. package/dist/templates.d.mts.map +1 -0
  422. package/dist/templates.mjs +230 -0
  423. package/dist/templates.mjs.map +1 -0
  424. package/dist/webhooks.cjs +96 -0
  425. package/dist/webhooks.cjs.map +1 -0
  426. package/dist/webhooks.d.cts +25 -0
  427. package/dist/webhooks.d.cts.map +1 -0
  428. package/dist/webhooks.d.mts +25 -0
  429. package/dist/webhooks.d.mts.map +1 -0
  430. package/dist/webhooks.mjs +94 -0
  431. package/dist/webhooks.mjs.map +1 -0
  432. package/dist/webpush.cjs +180 -0
  433. package/dist/webpush.cjs.map +1 -0
  434. package/dist/webpush.d.cts +53 -0
  435. package/dist/webpush.d.cts.map +1 -0
  436. package/dist/webpush.d.mts +53 -0
  437. package/dist/webpush.d.mts.map +1 -0
  438. package/dist/webpush.mjs +175 -0
  439. package/dist/webpush.mjs.map +1 -0
  440. package/package.json +189 -3
  441. package/src/cloudflare/schema.sql +127 -0
  442. package/src/cloudflare/workers.d.ts +44 -0
@@ -0,0 +1,19 @@
1
+ import { JourneyObserver, MessageTracking, OutboundMessage, PushDevice, SendResult } from "../engine/ports.mjs";
2
+ import { EmailAddress } from "../config.mjs";
3
+ import { D1DatabaseLike, EmailBindingLike, JourneyEnv, JourneyParams, KVNamespaceLike, WAKE_EVENT_TYPE, WAKE_TIMEOUT_TOLERANCE_MS, WorkflowBindingLike, WorkflowInstanceLike, wakeExpired } from "./bindings.mjs";
4
+ import { D1JourneyStore } from "../store/d1.mjs";
5
+ import { JourneyFactSource } from "../store/facts.mjs";
6
+ import { SqlClientLike } from "../store/sql.mjs";
7
+ import { PostgresJourneyStore, PostgresJourneyStoreOptions } from "../store/postgres.mjs";
8
+ import { PostgresReporting } from "../store/postgres-reporting.mjs";
9
+ import { Engagement, EntryInput, EntryOutcome, EventInput, JourneyReporting, JourneyStore, MessageRecord, ProfileProps, SchemaMismatchError, SegmentTriggerRoute, StoreLease, TriggerRoute } from "../store/index.mjs";
10
+ import { d1Store } from "./d1-env.mjs";
11
+ import { BundleIntegrityError, DeployResult, DeviceRegistration, IdentifyResult, IngestInput, IngestResult, SweepResult, deployBundle, forgetUser, handleRequest, identifyUser, ingestEvent, registerDevice, removeDevice, sweepSegments, unbindDevice } from "./router.mjs";
12
+ import { JourneyRunner } from "./runner.mjs";
13
+ import { CfEmailOptions, CfEmailSender, EmailRenderer, LogMessageSender, WebhookMessageSender, routeByChannel, routeByPlatform, trackEmail } from "./senders.mjs";
14
+ import { ChannelsConfig, channelsFromConfig, journeyMode, runtimeFromConfig } from "./channels.mjs";
15
+ import { reportingObserver } from "../reporting/observer.mjs";
16
+ import { TrackingOptions, handleTracking, recordPushOpen } from "../reporting/tracking.mjs";
17
+ import { BURST_WINDOW_MS, ClassifyOptions, ClickFacts, DEFAULT_QUICK_MS, RequestFacts, Verdict, classifyClick, classifyOpen } from "../reporting/classify.mjs";
18
+ import { EnvValidationError, ExecutionContextLike, JourneyWorker, JourneyWorkerOptions, journeyWorker } from "./worker.mjs";
19
+ export { BURST_WINDOW_MS, BundleIntegrityError, type CfEmailOptions, CfEmailSender, type ChannelsConfig, type ClassifyOptions, type ClickFacts, type D1DatabaseLike, D1JourneyStore, DEFAULT_QUICK_MS, type DeployResult, type DeviceRegistration, type EmailAddress, type EmailBindingLike, type EmailRenderer, type Engagement, type EntryInput, type EntryOutcome, EnvValidationError, type EventInput, type ExecutionContextLike, type IdentifyResult, type IngestInput, type IngestResult, type JourneyEnv, JourneyFactSource, type JourneyObserver, type JourneyParams, type JourneyReporting, JourneyRunner, type JourneyStore, type JourneyWorker, type JourneyWorkerOptions, type KVNamespaceLike, LogMessageSender, type MessageRecord, type MessageTracking, type OutboundMessage, PostgresJourneyStore, type PostgresJourneyStoreOptions, PostgresReporting, type ProfileProps, type PushDevice, type RequestFacts, SchemaMismatchError, type SegmentTriggerRoute, type SendResult, type SqlClientLike, type StoreLease, type SweepResult, type TrackingOptions, type TriggerRoute, type Verdict, WAKE_EVENT_TYPE, WAKE_TIMEOUT_TOLERANCE_MS, WebhookMessageSender, type WorkflowBindingLike, type WorkflowInstanceLike, channelsFromConfig, classifyClick, classifyOpen, d1Store, deployBundle, forgetUser, handleRequest, handleTracking, identifyUser, ingestEvent, journeyMode, journeyWorker, recordPushOpen, registerDevice, removeDevice, reportingObserver, routeByChannel, routeByPlatform, runtimeFromConfig, sweepSegments, trackEmail, unbindDevice, wakeExpired };
@@ -0,0 +1,16 @@
1
+ import { PostgresReporting } from "../store/postgres-reporting.mjs";
2
+ import { PostgresJourneyStore } from "../store/postgres.mjs";
3
+ import { WAKE_EVENT_TYPE, WAKE_TIMEOUT_TOLERANCE_MS, wakeExpired } from "./bindings.mjs";
4
+ import { BURST_WINDOW_MS, DEFAULT_QUICK_MS, classifyClick, classifyOpen } from "../reporting/classify.mjs";
5
+ import { handleTracking, recordPushOpen } from "../reporting/tracking.mjs";
6
+ import { JourneyFactSource } from "../store/facts.mjs";
7
+ import { D1JourneyStore } from "../store/d1.mjs";
8
+ import { SchemaMismatchError } from "../store/index.mjs";
9
+ import { d1Store } from "./d1-env.mjs";
10
+ import { BundleIntegrityError, deployBundle, forgetUser, handleRequest, identifyUser, ingestEvent, registerDevice, removeDevice, sweepSegments, unbindDevice } from "./router.mjs";
11
+ import { CfEmailSender, LogMessageSender, WebhookMessageSender, routeByChannel, routeByPlatform, trackEmail } from "./senders.mjs";
12
+ import { channelsFromConfig, journeyMode, runtimeFromConfig } from "./channels.mjs";
13
+ import { JourneyRunner } from "./runner.mjs";
14
+ import { reportingObserver } from "../reporting/observer.mjs";
15
+ import { EnvValidationError, journeyWorker } from "./worker.mjs";
16
+ export { BURST_WINDOW_MS, BundleIntegrityError, CfEmailSender, D1JourneyStore, DEFAULT_QUICK_MS, EnvValidationError, JourneyFactSource, JourneyRunner, LogMessageSender, PostgresJourneyStore, PostgresReporting, SchemaMismatchError, WAKE_EVENT_TYPE, WAKE_TIMEOUT_TOLERANCE_MS, WebhookMessageSender, channelsFromConfig, classifyClick, classifyOpen, d1Store, deployBundle, forgetUser, handleRequest, handleTracking, identifyUser, ingestEvent, journeyMode, journeyWorker, recordPushOpen, registerDevice, removeDevice, reportingObserver, routeByChannel, routeByPlatform, runtimeFromConfig, sweepSegments, trackEmail, unbindDevice, wakeExpired };
@@ -0,0 +1,516 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_runtime = require("../_virtual/_rolldown/runtime.cjs");
3
+ const require_hash = require("../hash.cjs");
4
+ const require_ir = require("../ir.cjs");
5
+ const require_contract = require("../contract.cjs");
6
+ const require_cloudflare_bindings = require("./bindings.cjs");
7
+ const require_engine_bucket = require("../engine/bucket.cjs");
8
+ const require_engine_condition = require("../engine/condition.cjs");
9
+ const require_reporting_tracking = require("../reporting/tracking.cjs");
10
+ const require_store_facts = require("../store/facts.cjs");
11
+ const require_store_index = require("../store/index.cjs");
12
+ const require_cloudflare_d1_env = require("./d1-env.cjs");
13
+ let zod_mini = require("zod/mini");
14
+ zod_mini = require_runtime.__toESM(zod_mini, 1);
15
+ //#region src/cloudflare/router.ts
16
+ async function ingestEvent(env, input, store = require_cloudflare_d1_env.d1Store(env)) {
17
+ if (input.event.startsWith("$")) throw new Error(`event name '${input.event}' is reserved ('$' prefix is internal)`);
18
+ const ts = input.ts ?? Date.now();
19
+ const payload = input.payload ?? {};
20
+ const id = input.id ?? crypto.randomUUID();
21
+ const stored = await store.insertEvent({
22
+ id,
23
+ userId: input.userId,
24
+ event: input.event,
25
+ ts,
26
+ payload
27
+ });
28
+ const woke = await wakeSubscribers(env, store, input.userId, input.event);
29
+ const started = await startTriggeredJourneys(env, store, {
30
+ ...input,
31
+ payload
32
+ }, ts);
33
+ started.push(...await refreshSegmentTriggers(env, store, input.userId, ts));
34
+ return {
35
+ id,
36
+ stored,
37
+ woke,
38
+ started
39
+ };
40
+ }
41
+ async function wakeSubscribers(env, store, userId, event) {
42
+ let woke = 0;
43
+ for (const handle of await store.findWakeHandles(userId, event)) {
44
+ let instance;
45
+ try {
46
+ instance = await env.JOURNEY.get(handle);
47
+ } catch {
48
+ await store.unsubscribe(handle);
49
+ continue;
50
+ }
51
+ try {
52
+ await instance.sendEvent({
53
+ type: require_cloudflare_bindings.WAKE_EVENT_TYPE,
54
+ payload: { event }
55
+ });
56
+ woke++;
57
+ } catch {}
58
+ }
59
+ return woke;
60
+ }
61
+ async function startTriggeredJourneys(env, store, input, ts) {
62
+ const started = [];
63
+ for (const route of await store.findTriggers(input.event)) {
64
+ if (route.where !== null && !require_engine_condition.matchesWhere(input.payload, route.where)) continue;
65
+ if (route.filter !== null) {
66
+ const facts = new require_store_facts.JourneyFactSource(store, input.userId);
67
+ if (!await require_engine_condition.evaluateCondition(route.filter, facts, ts)) continue;
68
+ }
69
+ const instanceId = await startJourney(env, store, route.workflow, route.hash, input.userId, ts, {
70
+ event: input.event,
71
+ payload: input.payload
72
+ });
73
+ if (instanceId !== null) started.push(instanceId);
74
+ }
75
+ return started;
76
+ }
77
+ /**
78
+ * Segment-entry triggers, maintained lazily: on each ingest/identify for a
79
+ * user, re-evaluate every trigger-routed segment for that user and act on the
80
+ * membership transition (enter → start journeys, leave → drop membership so a
81
+ * later re-entry is observable). Purely time-driven drift (an inactivity
82
+ * segment turning true by clock alone) has no event to ride on: the scheduled
83
+ * sweep catches it (`sweepSegments`).
84
+ */
85
+ async function refreshSegmentTriggers(env, store, userId, ts) {
86
+ return refreshSegments(env, store, userId, ts, await store.listSegmentTriggers());
87
+ }
88
+ /**
89
+ * Re-evaluate segments for one user — the routed ones only, or with `segments` every one named —
90
+ * and act on each membership transition: entering records the membership and starts the
91
+ * segment's routed workflows, leaving drops it. A segment trigger therefore starts journeys for
92
+ * users who enter after it is deployed; a user already a member is not entered again.
93
+ */
94
+ async function refreshSegments(env, store, userId, ts, routes, segments = [], definitions = /* @__PURE__ */ new Map()) {
95
+ const bySegment = new Map(segments.map((name) => [name, []]));
96
+ for (const route of routes) {
97
+ const list = bySegment.get(route.segment) ?? [];
98
+ list.push({
99
+ workflow: route.workflow,
100
+ hash: route.hash
101
+ });
102
+ bySegment.set(route.segment, list);
103
+ }
104
+ if (bySegment.size === 0) return [];
105
+ const facts = new require_store_facts.JourneyFactSource(store, userId);
106
+ const started = [];
107
+ const failures = [];
108
+ for (const [segmentId, segmentRoutes] of bySegment) {
109
+ if (!definitions.has(segmentId)) definitions.set(segmentId, await store.getSegmentCondition(segmentId));
110
+ const definition = definitions.get(segmentId);
111
+ if (definition === void 0) continue;
112
+ const matches = await require_engine_condition.evaluateCondition(definition, facts, ts);
113
+ const member = await store.isSegmentMember(segmentId, userId);
114
+ if (matches && !member) await store.addSegmentMember(segmentId, userId, ts, segmentRoutes.map((route) => route.workflow));
115
+ else if (!matches && member) {
116
+ await store.removeSegmentMember(segmentId, userId);
117
+ continue;
118
+ }
119
+ if (!matches) continue;
120
+ const pending = new Set(await store.pendingSegmentStarts(segmentId, userId));
121
+ for (const route of segmentRoutes) {
122
+ if (!pending.has(route.workflow)) continue;
123
+ try {
124
+ const instanceId = await startJourney(env, store, route.workflow, route.hash, userId, ts, {
125
+ event: "$segment_entry",
126
+ payload: { segment: segmentId }
127
+ });
128
+ if (instanceId !== null) started.push(instanceId);
129
+ await store.completeSegmentStart(segmentId, userId, route.workflow);
130
+ } catch (error) {
131
+ failures.push(error);
132
+ }
133
+ }
134
+ }
135
+ if (failures.length > 0) throw failures[0];
136
+ return started;
137
+ }
138
+ /**
139
+ * The scheduled sweep: every deployed segment evaluated for every known user — the evaluator a
140
+ * journey's conditions run on, so a member is exactly who a journey would see in it. Membership
141
+ * follows (joiners keep the time they joined, leavers are removed), segment triggers start the
142
+ * journeys of whoever entered by the clock alone, and the store records each segment's size.
143
+ * It walks users one by one: fine for thousands, a large audience wants SQL-side evaluation.
144
+ */
145
+ async function sweepSegments(env, store, now = Date.now()) {
146
+ const erasing = /* @__PURE__ */ new Set();
147
+ for (const userId of await store.pendingErasures()) try {
148
+ const { erased } = await eraseUser(env, userId, store);
149
+ if (!erased) erasing.add(userId);
150
+ } catch (error) {
151
+ erasing.add(userId);
152
+ console.error(`[workflow] erasure of ${userId} failed`, error);
153
+ }
154
+ const segments = (await store.listSegments()).map((segment) => segment.id);
155
+ const routes = await store.listSegmentTriggers();
156
+ const users = (await store.listUserIds()).filter((userId) => !erasing.has(userId));
157
+ const started = [];
158
+ const definitions = /* @__PURE__ */ new Map();
159
+ for (const userId of users) try {
160
+ started.push(...await refreshSegments(env, store, userId, now, routes, segments, definitions));
161
+ } catch (error) {
162
+ console.error(`[workflow] segment refresh for ${userId} failed`, error);
163
+ }
164
+ const sizes = await store.reporting?.snapshotSegments(now) ?? [];
165
+ return {
166
+ users: users.length,
167
+ started,
168
+ sizes
169
+ };
170
+ }
171
+ /**
172
+ * Create one journey instance behind the entry ledger. Returns null when the
173
+ * once-policy blocks the entry (the store's attempt is atomic, so concurrent
174
+ * ingests cannot double-enter). A pair whose previous instance is recorded as
175
+ * 'failed' is reclaimed rather than barred forever over one outage.
176
+ */
177
+ async function startJourney(env, store, workflow, hash, userId, ts, trigger) {
178
+ const instanceId = buildInstanceId(workflow, hash, userId, ts);
179
+ const params = {
180
+ workflowId: workflow,
181
+ contentHash: hash,
182
+ userId,
183
+ trigger
184
+ };
185
+ const outcome = await store.enterJourney({
186
+ workflow,
187
+ userId,
188
+ instanceId,
189
+ hash,
190
+ ts
191
+ });
192
+ if (outcome === null) return null;
193
+ try {
194
+ await env.JOURNEY.create({
195
+ id: instanceId,
196
+ params
197
+ });
198
+ } catch (error) {
199
+ if (outcome === "reclaimed") await store.setEntryStatus(instanceId, "failed");
200
+ else await store.removeEntry(instanceId);
201
+ throw error;
202
+ }
203
+ return instanceId;
204
+ }
205
+ const utf8 = new TextEncoder();
206
+ /**
207
+ * Instance id: addressable (the router gets it directly to wake it), ≤100
208
+ * chars, legal charset. The murmur3 fingerprint keeps ids distinct when the
209
+ * sanitized/truncated userId alone would collide.
210
+ */
211
+ function buildInstanceId(workflow, hash, userId, ts) {
212
+ const uid = userId.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 24);
213
+ const fingerprint = require_engine_bucket.murmur3(utf8.encode(userId)).toString(36);
214
+ return `${workflow.slice(0, 32)}-${hash.slice(0, 8)}-${uid}-${fingerprint}-${ts.toString(36)}`;
215
+ }
216
+ /**
217
+ * Merge-patch profile properties (a null removes one), then wake property waits
218
+ * and re-evaluate segment triggers. The merge is one statement in the store, so
219
+ * two identifies landing together cannot lose each other's fields.
220
+ */
221
+ async function identifyUser(env, userId, props, store = require_cloudflare_d1_env.d1Store(env)) {
222
+ const ts = Date.now();
223
+ return {
224
+ ok: true,
225
+ props: await store.mergeProfile(userId, props),
226
+ woke: await wakeSubscribers(env, store, userId, require_engine_condition.PROFILE_UPDATED_EVENT),
227
+ started: await refreshSegmentTriggers(env, store, userId, ts)
228
+ };
229
+ }
230
+ /**
231
+ * A push token registered for the user (or moved to them from another account: a token belongs
232
+ * to one user at a time). Wakes the waits that read devices (`reachable('push')` inside
233
+ * `waitUntil`), for the new owner and the previous one.
234
+ */
235
+ async function registerDevice(env, device, store = require_cloudflare_d1_env.d1Store(env)) {
236
+ const previous = await store.removeDevice(device.token);
237
+ await store.upsertDevice({
238
+ ...device,
239
+ ts: device.ts ?? Date.now()
240
+ });
241
+ let woke = await wakeSubscribers(env, store, device.userId, require_engine_condition.DEVICES_UPDATED_EVENT);
242
+ if (previous !== void 0 && previous !== device.userId) woke += await wakeSubscribers(env, store, previous, require_engine_condition.DEVICES_UPDATED_EVENT);
243
+ return {
244
+ ok: true,
245
+ woke
246
+ };
247
+ }
248
+ /**
249
+ * A deleted account: everything the engine keeps about the user is erased and the journeys still
250
+ * running for them are terminated, so nothing more is sent. Idempotent.
251
+ */
252
+ /** Workflow instance states that will never run another step. */
253
+ const STOPPED_STATUSES = /* @__PURE__ */ new Set([
254
+ "complete",
255
+ "errored",
256
+ "terminated"
257
+ ]);
258
+ /**
259
+ * Stop one instance for good; true once it is known not to run again. An instance the platform
260
+ * no longer knows, or one already finished (terminate refuses those), counts as stopped. Any other
261
+ * failure is not taken for "already gone": it answers false, and the erasure waits for a retry.
262
+ */
263
+ async function stopInstance(env, instanceId) {
264
+ let instance;
265
+ try {
266
+ instance = await env.JOURNEY.get(instanceId);
267
+ } catch (error) {
268
+ if (/not[_ ]found/i.test(String(error))) return true;
269
+ console.warn(`[workflow] looking up ${instanceId} to stop it failed`, error);
270
+ return false;
271
+ }
272
+ if (instance.terminate === void 0) return false;
273
+ try {
274
+ await instance.terminate();
275
+ return true;
276
+ } catch (error) {
277
+ const status = await instance.status?.().catch(() => void 0);
278
+ if (status !== void 0 && STOPPED_STATUSES.has(status.status)) return true;
279
+ console.warn(`[workflow] terminating ${instanceId} failed`, error);
280
+ return false;
281
+ }
282
+ }
283
+ /**
284
+ * Carry out a recorded erasure: stop every running instance of the user, and only once all have
285
+ * stopped erase their data (the request with it). Stopping first means no step can write rows
286
+ * back after the erase; erasing nothing until then keeps the entries that name the instances
287
+ * still to stop, so a retry can finish the job.
288
+ */
289
+ async function eraseUser(env, userId, store) {
290
+ const pending = [];
291
+ for (const instanceId of await store.runningInstances(userId)) if (!await stopInstance(env, instanceId)) pending.push(instanceId);
292
+ if (pending.length > 0) return {
293
+ erased: false,
294
+ pending
295
+ };
296
+ await store.forgetUser(userId);
297
+ return {
298
+ erased: true,
299
+ pending
300
+ };
301
+ }
302
+ /**
303
+ * Forget a user (a deleted account): the request is recorded first, then carried out. An
304
+ * instance that will not stop leaves it pending — nothing erased yet — and the scheduled sweep
305
+ * retries it; `erased: false` says so.
306
+ */
307
+ async function forgetUser(env, userId, store = require_cloudflare_d1_env.d1Store(env), now = Date.now()) {
308
+ await store.requestErasure(userId, now);
309
+ return {
310
+ ok: true,
311
+ ...await eraseUser(env, userId, store)
312
+ };
313
+ }
314
+ /**
315
+ * The user signed out on the device: the token stays registered, bound to nobody, so the next
316
+ * sign-in only has to bind it again. Wakes the former owner's device waits (`reachable('push')`
317
+ * may no longer hold).
318
+ */
319
+ async function unbindDevice(env, token, store = require_cloudflare_d1_env.d1Store(env)) {
320
+ const owner = await store.unbindDevice(token);
321
+ return {
322
+ ok: true,
323
+ woke: owner === void 0 ? 0 : await wakeSubscribers(env, store, owner, require_engine_condition.DEVICES_UPDATED_EVENT)
324
+ };
325
+ }
326
+ /** A push token forgotten for good (the push service reports it gone); wakes its owner's device waits. */
327
+ async function removeDevice(env, token, store = require_cloudflare_d1_env.d1Store(env)) {
328
+ const owner = await store.removeDevice(token);
329
+ return {
330
+ ok: true,
331
+ woke: owner === void 0 ? 0 : await wakeSubscribers(env, store, owner, require_engine_condition.DEVICES_UPDATED_EVENT)
332
+ };
333
+ }
334
+ /** A bundle whose declared hashes do not describe its contents — rejected before anything is written. */
335
+ var BundleIntegrityError = class extends Error {
336
+ constructor(message) {
337
+ super(message);
338
+ this.name = "BundleIntegrityError";
339
+ }
340
+ };
341
+ /**
342
+ * Recompute every declared contentHash and refuse the bundle if one disagrees.
343
+ *
344
+ * The contentHash is the address an in-flight journey reads its IR from, so
345
+ * a hash that does not describe its own content is a way to change what a
346
+ * pinned instance executes: submit an edited flow under the old hash and the
347
+ * next replay picks it up. The compiler always computes the hash it ships, so
348
+ * a mismatch means a hand-rolled payload or a stale client — neither should be
349
+ * able to overwrite a version that journeys are running.
350
+ *
351
+ * Each hash is recomputed exactly the way its compiler produced it: a workflow
352
+ * hashes its whole IR (contentHash strips itself), a segment hashes only its
353
+ * condition. Mirroring them is load-bearing — recomputing a segment over the
354
+ * whole record would reject every honest deploy.
355
+ */
356
+ function verifyBundleHashes(parsed) {
357
+ const mismatched = [];
358
+ for (const workflow of parsed.workflows) if (require_hash.semanticHash(workflow) !== workflow.contentHash) mismatched.push(`workflow '${workflow.id}'`);
359
+ for (const segment of parsed.segments) if (require_hash.semanticHash(segment.condition) !== segment.contentHash) mismatched.push(`segment '${segment.id}'`);
360
+ if (mismatched.length > 0) throw new BundleIntegrityError(`contentHash does not match content for ${mismatched.join(", ")} — recompile the bundle instead of editing it by hand`);
361
+ }
362
+ /** Bundle deploy, terraform-apply style: workflow bodies first (content-addressed, so a failed deploy leaves only harmless orphans), then the routing swap. */
363
+ async function deployBundle(env, bundle, store = require_cloudflare_d1_env.d1Store(env)) {
364
+ const parsed = require_ir.BundleIR.parse(bundle);
365
+ verifyBundleHashes(parsed);
366
+ const problems = await store.checkSchema?.() ?? [];
367
+ if (problems.length > 0) throw new require_store_index.SchemaMismatchError(problems);
368
+ for (const workflow of parsed.workflows) await store.putWorkflowIR(workflow);
369
+ await store.replaceRoutes(parsed);
370
+ const unrouted = parsed.workflows.filter((workflow) => workflow.trigger.type === "date" || workflow.trigger.type === "webhook").map((workflow) => ({
371
+ workflow: workflow.id,
372
+ trigger: workflow.trigger.type
373
+ }));
374
+ return {
375
+ workflows: parsed.workflows.map((w) => `${w.id}@${w.contentHash.slice(0, 8)}`),
376
+ unrouted
377
+ };
378
+ }
379
+ /**
380
+ * Request bodies are untrusted JSON. They are read as unknown fields and
381
+ * checked, never cast into the shape they are supposed to have: a cast only
382
+ * silences the compiler, and what arrives here reaches SQL parameters.
383
+ */
384
+ async function readBody(request) {
385
+ const body = await request.json();
386
+ return isPlainObject(body) ? body : {};
387
+ }
388
+ function isPlainObject(value) {
389
+ return typeof value === "object" && value !== null && !Array.isArray(value);
390
+ }
391
+ function isNonEmptyString(value) {
392
+ return typeof value === "string" && value.length > 0;
393
+ }
394
+ async function handleRequest(request, env, store = require_cloudflare_d1_env.d1Store(env), validation = {}) {
395
+ const url = new URL(request.url);
396
+ const json = (body, status = 200) => new Response(JSON.stringify(body), {
397
+ status,
398
+ headers: { "content-type": "application/json" }
399
+ });
400
+ const { contract } = validation;
401
+ const enforce = validation.mode !== "report";
402
+ /** The contract's verdict: the value to use, or the response refusing the request. */
403
+ const checked = (result, original, what) => {
404
+ if (result.ok) return { value: result.data };
405
+ const issues = result.issues.map((i) => `${i.path || "(root)"}: ${i.message}`);
406
+ if (!enforce) {
407
+ console.warn(`[workflow router] contract would refuse ${what}: ${issues.join("; ")}`);
408
+ return { value: original };
409
+ }
410
+ return { refused: json({
411
+ error: `${what} refused by the contract`,
412
+ issues: result.issues
413
+ }, 400) };
414
+ };
415
+ if (request.method === "GET" && url.pathname === "/health") return json({ ok: true });
416
+ if (env.API_TOKEN !== void 0) {
417
+ if (request.headers.get("authorization") !== `Bearer ${env.API_TOKEN}`) return json({ error: "unauthorized" }, 401);
418
+ }
419
+ try {
420
+ if (request.method === "POST" && url.pathname === "/events") {
421
+ const { id, userId, event, payload, ts } = await readBody(request);
422
+ if (!isNonEmptyString(userId) || !isNonEmptyString(event)) return json({ error: "userId and event required" }, 400);
423
+ if (event.startsWith("$")) return json({ error: "event names starting with $ are reserved" }, 400);
424
+ if (id !== void 0 && !isNonEmptyString(id)) return json({ error: "id must be a non-empty string" }, 400);
425
+ if (ts !== void 0 && typeof ts !== "number") return json({ error: "ts must be a number" }, 400);
426
+ if (payload !== void 0 && !isPlainObject(payload)) return json({ error: "payload must be an object" }, 400);
427
+ let accepted = payload;
428
+ if (contract !== void 0) {
429
+ const verdict = checked(require_contract.checkEvent(contract, event, payload ?? {}), accepted ?? {}, `event '${event}'${typeof id === "string" ? ` (${id})` : ""}`);
430
+ if ("refused" in verdict) return verdict.refused;
431
+ accepted = verdict.value;
432
+ }
433
+ return json(await ingestEvent(env, {
434
+ id,
435
+ userId,
436
+ event,
437
+ payload: accepted,
438
+ ts
439
+ }, store));
440
+ }
441
+ if (request.method === "POST" && url.pathname === "/identify") {
442
+ const { userId, props } = await readBody(request);
443
+ if (!isNonEmptyString(userId)) return json({ error: "userId required" }, 400);
444
+ if (!isPlainObject(props)) return json({ error: "props must be an object" }, 400);
445
+ let patch = props;
446
+ if (contract !== void 0) {
447
+ const verdict = checked(contract.parseProfilePatch(props), patch, "identify");
448
+ if ("refused" in verdict) return verdict.refused;
449
+ patch = verdict.value;
450
+ }
451
+ return json(await identifyUser(env, userId, patch, store));
452
+ }
453
+ if (request.method === "POST" && url.pathname === "/devices") {
454
+ const { userId, token, platform, ts } = await readBody(request);
455
+ if (!isNonEmptyString(userId)) return json({ error: "userId required" }, 400);
456
+ if (!isNonEmptyString(token)) return json({ error: "token required" }, 400);
457
+ if (platform !== "ios" && platform !== "android" && platform !== "web") return json({ error: "platform must be 'ios', 'android' or 'web'" }, 400);
458
+ if (ts !== void 0 && typeof ts !== "number") return json({ error: "ts must be a number" }, 400);
459
+ return json(await registerDevice(env, {
460
+ userId,
461
+ token,
462
+ platform,
463
+ ...ts === void 0 ? {} : { ts }
464
+ }, store));
465
+ }
466
+ if (request.method === "POST" && url.pathname === "/messages/opened") {
467
+ const { userId, messageId } = await readBody(request);
468
+ if (!isNonEmptyString(userId)) return json({ error: "userId required" }, 400);
469
+ if (!isNonEmptyString(messageId)) return json({ error: "messageId required" }, 400);
470
+ return json({
471
+ ok: true,
472
+ recorded: store.reporting !== void 0 && await require_reporting_tracking.recordPushOpen(store.reporting, userId, messageId)
473
+ });
474
+ }
475
+ if (request.method === "POST" && url.pathname === "/users/forget") {
476
+ const { userId } = await readBody(request);
477
+ if (!isNonEmptyString(userId)) return json({ error: "userId required" }, 400);
478
+ return json(await forgetUser(env, userId, store));
479
+ }
480
+ if (request.method === "POST" && url.pathname === "/devices/unbind") {
481
+ const { token } = await readBody(request);
482
+ if (!isNonEmptyString(token)) return json({ error: "token required" }, 400);
483
+ return json(await unbindDevice(env, token, store));
484
+ }
485
+ if (request.method === "POST" && url.pathname === "/devices/remove") {
486
+ const { token } = await readBody(request);
487
+ if (!isNonEmptyString(token)) return json({ error: "token required" }, 400);
488
+ return json(await removeDevice(env, token, store));
489
+ }
490
+ if (request.method === "POST" && url.pathname === "/deploy") return json(await deployBundle(env, await request.json(), store));
491
+ return json({ error: "not found" }, 404);
492
+ } catch (error) {
493
+ if (error instanceof zod_mini.core.$ZodError) return json({ error: `invalid payload: ${error.message}` }, 400);
494
+ if (error instanceof BundleIntegrityError) return json({ error: error.message }, 400);
495
+ if (error instanceof require_store_index.SchemaMismatchError) return json({
496
+ error: error.message,
497
+ problems: error.problems
498
+ }, 503);
499
+ console.error("[workflow router]", error);
500
+ return json({ error: "internal error" }, 500);
501
+ }
502
+ }
503
+ //#endregion
504
+ exports.BundleIntegrityError = BundleIntegrityError;
505
+ exports.deployBundle = deployBundle;
506
+ exports.forgetUser = forgetUser;
507
+ exports.handleRequest = handleRequest;
508
+ exports.identifyUser = identifyUser;
509
+ exports.ingestEvent = ingestEvent;
510
+ exports.refreshSegmentTriggers = refreshSegmentTriggers;
511
+ exports.registerDevice = registerDevice;
512
+ exports.removeDevice = removeDevice;
513
+ exports.sweepSegments = sweepSegments;
514
+ exports.unbindDevice = unbindDevice;
515
+
516
+ //# sourceMappingURL=router.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.cjs","names":["d1Store","WAKE_EVENT_TYPE","matchesWhere","JourneyFactSource","evaluateCondition","murmur3","PROFILE_UPDATED_EVENT","DEVICES_UPDATED_EVENT","semanticHash","BundleIR","SchemaMismatchError","checkEvent","recordPushOpen","z"],"sources":["../../src/cloudflare/router.ts"],"sourcesContent":["import * as z from 'zod/mini';\nimport { type Contract, type ContractResult, checkEvent } from '../contract';\nimport { murmur3 } from '../engine/bucket';\nimport {\n DEVICES_UPDATED_EVENT,\n PROFILE_UPDATED_EVENT,\n evaluateCondition,\n matchesWhere,\n} from '../engine/condition';\nimport { semanticHash } from '../hash';\nimport { BundleIR, type ConditionIR, type TriggerIR } from '../ir';\nimport { recordPushOpen } from '../reporting/tracking';\nimport { JourneyFactSource } from '../store/facts';\nimport {\n type JourneyStore,\n type ProfileProps,\n SchemaMismatchError,\n type SegmentTriggerRoute,\n} from '../store/index';\nimport {\n type JourneyEnv,\n type JourneyParams,\n WAKE_EVENT_TYPE,\n type WorkflowInstanceLike,\n} from './bindings';\nimport { d1Store } from './d1-env';\n\n/**\n * Ingest router. An incoming event does four things: it is stored, it wakes\n * waiting instances, it is matched against event triggers, and it re-evaluates\n * segment-trigger membership. Plus /deploy (persist a bundle) and /identify\n * (merge a profile — which wakes property-condition waits via\n * PROFILE_UPDATED_EVENT and re-evaluates segment triggers too).\n *\n * Storage goes through a JourneyStore; the `store` argument defaults to the\n * D1 + KV store built from the env's bindings, so a Worker that only has those\n * calls these functions exactly as before.\n */\n\nexport interface IngestInput {\n userId: string;\n event: string;\n payload?: Record<string, unknown>;\n ts?: number;\n /**\n * This occurrence's identity, and with it the idempotency of sending it.\n *\n * Only the sender can know whether two deliveries describe one occurrence or\n * two, so the engine does not decide: an id it has already stored makes the\n * second delivery a no-op. That matters because ingest is reachable from two\n * retrying callers — an HTTP client retrying a 500, and the interpreter's\n * send_event step being retried after it already committed its row — and a\n * second copy of an event silently changes every count- and window-based\n * condition that reads the log.\n *\n * Callers that retry should send an id they can reproduce. Omitting it gets\n * a fresh one, which records the event as its own occurrence.\n */\n id?: string;\n}\n\nexport interface IngestResult {\n /** The occurrence's identity: the caller's `id`, or the one minted for it. */\n id: string;\n /** False when that id was already in the log: nothing was written this time. */\n stored: boolean;\n woke: number;\n started: string[];\n}\n\nexport async function ingestEvent(\n env: JourneyEnv,\n input: IngestInput,\n store: JourneyStore = d1Store(env)\n): Promise<IngestResult> {\n if (input.event.startsWith('$')) {\n throw new Error(`event name '${input.event}' is reserved ('$' prefix is internal)`);\n }\n const ts = input.ts ?? Date.now();\n const payload = input.payload ?? {};\n // No id means the sender is not claiming this is a repeat of anything, which\n // a fresh one states truthfully — unlike a key derived from the contents,\n // which would silently collapse two identical events a second apart.\n const id = input.id ?? crypto.randomUUID();\n\n const stored = await store.insertEvent({\n id,\n userId: input.userId,\n event: input.event,\n ts,\n payload,\n });\n\n /*\n * The rest runs even for a duplicate. A retry arrives precisely because the\n * first attempt did not finish — it committed the row and then failed — so\n * returning early would strand the journeys the retry exists to start. Both\n * halves are independently idempotent: waking an instance that already moved\n * on is a no-op, and the entry ledger refuses a second entry.\n */\n const woke = await wakeSubscribers(env, store, input.userId, input.event);\n const started = await startTriggeredJourneys(env, store, { ...input, payload }, ts);\n started.push(...(await refreshSegmentTriggers(env, store, input.userId, ts)));\n return { id, stored, woke, started };\n}\n\nasync function wakeSubscribers(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n event: string\n): Promise<number> {\n let woke = 0;\n for (const handle of await store.findWakeHandles(userId, event)) {\n let instance: WorkflowInstanceLike;\n try {\n instance = await env.JOURNEY.get(handle);\n } catch {\n // Unknown instance (errored out without cleanup): drop the dangling subscription\n await store.unsubscribe(handle);\n continue;\n }\n try {\n await instance.sendEvent({ type: WAKE_EVENT_TYPE, payload: { event } });\n woke++;\n } catch {\n // Transient send failure (or an instance finishing right now): keep the\n // subscription — a later event retries it, and the wait's own timeout\n // bounds the damage. Deleting here would silence all future wake-ups.\n }\n }\n return woke;\n}\n\nasync function startTriggeredJourneys(\n env: JourneyEnv,\n store: JourneyStore,\n input: IngestInput & { payload: Record<string, unknown> },\n ts: number\n): Promise<string[]> {\n const started: string[] = [];\n for (const route of await store.findTriggers(input.event)) {\n // where: the payload gate — evaluated against the incoming event first\n if (route.where !== null && !matchesWhere(input.payload, route.where)) continue;\n\n // filter: the profile gate\n if (route.filter !== null) {\n const facts = new JourneyFactSource(store, input.userId);\n if (!(await evaluateCondition(route.filter, facts, ts))) continue;\n }\n\n const instanceId = await startJourney(\n env,\n store,\n route.workflow,\n route.hash,\n input.userId,\n ts,\n {\n event: input.event,\n payload: input.payload,\n }\n );\n if (instanceId !== null) started.push(instanceId);\n }\n return started;\n}\n\n/**\n * Segment-entry triggers, maintained lazily: on each ingest/identify for a\n * user, re-evaluate every trigger-routed segment for that user and act on the\n * membership transition (enter → start journeys, leave → drop membership so a\n * later re-entry is observable). Purely time-driven drift (an inactivity\n * segment turning true by clock alone) has no event to ride on: the scheduled\n * sweep catches it (`sweepSegments`).\n */\nexport async function refreshSegmentTriggers(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n ts: number\n): Promise<string[]> {\n return refreshSegments(env, store, userId, ts, await store.listSegmentTriggers());\n}\n\n/**\n * Re-evaluate segments for one user — the routed ones only, or with `segments` every one named —\n * and act on each membership transition: entering records the membership and starts the\n * segment's routed workflows, leaving drops it. A segment trigger therefore starts journeys for\n * users who enter after it is deployed; a user already a member is not entered again.\n */\nasync function refreshSegments(\n env: JourneyEnv,\n store: JourneyStore,\n userId: string,\n ts: number,\n routes: readonly SegmentTriggerRoute[],\n segments: readonly string[] = [],\n // A sweep loads each definition once for all its users, not once per user\n definitions = new Map<string, ConditionIR | undefined>()\n): Promise<string[]> {\n const bySegment = new Map<string, { workflow: string; hash: string }[]>(\n segments.map((name) => [name, []])\n );\n for (const route of routes) {\n const list = bySegment.get(route.segment) ?? [];\n list.push({ workflow: route.workflow, hash: route.hash });\n bySegment.set(route.segment, list);\n }\n if (bySegment.size === 0) return [];\n\n const facts = new JourneyFactSource(store, userId);\n const started: string[] = [];\n const failures: unknown[] = [];\n for (const [segmentId, segmentRoutes] of bySegment) {\n if (!definitions.has(segmentId)) {\n definitions.set(segmentId, await store.getSegmentCondition(segmentId));\n }\n const definition = definitions.get(segmentId);\n if (definition === undefined) continue; // route without a definition: broken deploy, skip\n\n const matches = await evaluateCondition(definition, facts, ts);\n const member = await store.isSegmentMember(segmentId, userId);\n\n if (matches && !member) {\n // Entry transition: the membership and the starts it owes, recorded together\n await store.addSegmentMember(\n segmentId,\n userId,\n ts,\n segmentRoutes.map((route) => route.workflow)\n );\n } else if (!matches && member) {\n await store.removeSegmentMember(segmentId, userId);\n continue;\n }\n if (!matches) continue;\n\n // Every start the entry still owes — a fresh entry's, or one an earlier evaluation failed on.\n // Each is crossed off once its instance exists, so one workflow failing neither blocks the\n // others nor gets lost: the next evaluation (the sweep, the user's next event) retries it.\n const pending = new Set(await store.pendingSegmentStarts(segmentId, userId));\n for (const route of segmentRoutes) {\n if (!pending.has(route.workflow)) continue;\n try {\n const instanceId = await startJourney(env, store, route.workflow, route.hash, userId, ts, {\n event: '$segment_entry',\n payload: { segment: segmentId },\n });\n if (instanceId !== null) started.push(instanceId);\n await store.completeSegmentStart(segmentId, userId, route.workflow);\n } catch (error) {\n failures.push(error);\n }\n }\n }\n // Surface a failure to the caller (an ingest answers 500) once every start had its chance\n if (failures.length > 0) throw failures[0];\n return started;\n}\n\nexport interface SweepResult {\n users: number;\n /** Journeys the segments' entries started. */\n started: string[];\n /** Each deployed segment's size after the sweep (empty when the store keeps no reporting). */\n sizes: { segment: string; size: number }[];\n}\n\n/**\n * The scheduled sweep: every deployed segment evaluated for every known user — the evaluator a\n * journey's conditions run on, so a member is exactly who a journey would see in it. Membership\n * follows (joiners keep the time they joined, leavers are removed), segment triggers start the\n * journeys of whoever entered by the clock alone, and the store records each segment's size.\n * It walks users one by one: fine for thousands, a large audience wants SQL-side evaluation.\n */\nexport async function sweepSegments(\n env: JourneyEnv,\n store: JourneyStore,\n now = Date.now()\n): Promise<SweepResult> {\n // Erasures left unfinished (an instance would not stop) first: their users are not evaluated\n const erasing = new Set<string>();\n for (const userId of await store.pendingErasures()) {\n try {\n const { erased } = await eraseUser(env, userId, store);\n if (!erased) erasing.add(userId);\n } catch (error) {\n // Still pending: the next sweep tries again, and the rest of this one goes on\n erasing.add(userId);\n console.error(`[workflow] erasure of ${userId} failed`, error);\n }\n }\n const segments = (await store.listSegments()).map((segment) => segment.id);\n const routes = await store.listSegmentTriggers();\n const users = (await store.listUserIds()).filter((userId) => !erasing.has(userId));\n const started: string[] = [];\n const definitions = new Map<string, ConditionIR | undefined>();\n for (const userId of users) {\n try {\n started.push(\n ...(await refreshSegments(env, store, userId, now, routes, segments, definitions))\n );\n } catch (error) {\n // One user's failed start is kept for the next sweep; it must not stop everyone else's\n console.error(`[workflow] segment refresh for ${userId} failed`, error);\n }\n }\n const sizes = (await store.reporting?.snapshotSegments(now)) ?? [];\n return { users: users.length, started, sizes };\n}\n\n/**\n * Create one journey instance behind the entry ledger. Returns null when the\n * once-policy blocks the entry (the store's attempt is atomic, so concurrent\n * ingests cannot double-enter). A pair whose previous instance is recorded as\n * 'failed' is reclaimed rather than barred forever over one outage.\n */\nasync function startJourney(\n env: JourneyEnv,\n store: JourneyStore,\n workflow: string,\n hash: string,\n userId: string,\n ts: number,\n trigger: { event: string; payload: Record<string, unknown> }\n): Promise<string | null> {\n const instanceId = buildInstanceId(workflow, hash, userId, ts);\n const params: JourneyParams = { workflowId: workflow, contentHash: hash, userId, trigger };\n\n const outcome = await store.enterJourney({ workflow, userId, instanceId, hash, ts });\n if (outcome === null) return null; // already entered, and still alive\n\n try {\n await env.JOURNEY.create({ id: instanceId, params });\n } catch (error) {\n if (outcome === 'reclaimed') {\n // Put the corpse back rather than deleting it: the entry is still a\n // failure, and dropping the row would erase that from the ledger.\n await store.setEntryStatus(instanceId, 'failed');\n } else {\n // Roll the ledger back so a retried ingest can enter — otherwise the\n // once-policy would permanently record an entry that never ran.\n await store.removeEntry(instanceId);\n }\n throw error;\n }\n return instanceId;\n}\n\nconst utf8 = new TextEncoder();\n\n/**\n * Instance id: addressable (the router gets it directly to wake it), ≤100\n * chars, legal charset. The murmur3 fingerprint keeps ids distinct when the\n * sanitized/truncated userId alone would collide.\n */\nfunction buildInstanceId(workflow: string, hash: string, userId: string, ts: number): string {\n const uid = userId.replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 24);\n const fingerprint = murmur3(utf8.encode(userId)).toString(36);\n return `${workflow.slice(0, 32)}-${hash.slice(0, 8)}-${uid}-${fingerprint}-${ts.toString(36)}`;\n}\n\n/* --------------------------------- identify --------------------------------- */\n\nexport interface IdentifyResult {\n ok: true;\n props: ProfileProps;\n woke: number;\n started: string[];\n}\n\n/**\n * Merge-patch profile properties (a null removes one), then wake property waits\n * and re-evaluate segment triggers. The merge is one statement in the store, so\n * two identifies landing together cannot lose each other's fields.\n */\nexport async function identifyUser(\n env: JourneyEnv,\n userId: string,\n props: ProfileProps,\n store: JourneyStore = d1Store(env)\n): Promise<IdentifyResult> {\n const ts = Date.now();\n const merged = await store.mergeProfile(userId, props);\n // Property-condition waits subscribe to this reserved event (see relevantEvents)\n const woke = await wakeSubscribers(env, store, userId, PROFILE_UPDATED_EVENT);\n // A profile change can move the user into (or out of) a trigger-routed segment\n const started = await refreshSegmentTriggers(env, store, userId, ts);\n return { ok: true, props: merged, woke, started };\n}\n\nexport interface DeviceRegistration {\n userId: string;\n token: string;\n platform: string;\n ts?: number;\n}\n\n/**\n * A push token registered for the user (or moved to them from another account: a token belongs\n * to one user at a time). Wakes the waits that read devices (`reachable('push')` inside\n * `waitUntil`), for the new owner and the previous one.\n */\nexport async function registerDevice(\n env: JourneyEnv,\n device: DeviceRegistration,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n const previous = await store.removeDevice(device.token);\n await store.upsertDevice({ ...device, ts: device.ts ?? Date.now() });\n let woke = await wakeSubscribers(env, store, device.userId, DEVICES_UPDATED_EVENT);\n if (previous !== undefined && previous !== device.userId) {\n woke += await wakeSubscribers(env, store, previous, DEVICES_UPDATED_EVENT);\n }\n return { ok: true, woke };\n}\n\n/**\n * A deleted account: everything the engine keeps about the user is erased and the journeys still\n * running for them are terminated, so nothing more is sent. Idempotent.\n */\n/** Workflow instance states that will never run another step. */\nconst STOPPED_STATUSES = new Set(['complete', 'errored', 'terminated']);\n\n/**\n * Stop one instance for good; true once it is known not to run again. An instance the platform\n * no longer knows, or one already finished (terminate refuses those), counts as stopped. Any other\n * failure is not taken for \"already gone\": it answers false, and the erasure waits for a retry.\n */\nasync function stopInstance(env: JourneyEnv, instanceId: string): Promise<boolean> {\n let instance: WorkflowInstanceLike;\n try {\n instance = await env.JOURNEY.get(instanceId);\n } catch (error) {\n if (/not[_ ]found/i.test(String(error))) return true;\n console.warn(`[workflow] looking up ${instanceId} to stop it failed`, error);\n return false;\n }\n if (instance.terminate === undefined) return false;\n try {\n await instance.terminate();\n return true;\n } catch (error) {\n const status = await instance.status?.().catch(() => undefined);\n if (status !== undefined && STOPPED_STATUSES.has(status.status)) return true;\n console.warn(`[workflow] terminating ${instanceId} failed`, error);\n return false;\n }\n}\n\n/**\n * Carry out a recorded erasure: stop every running instance of the user, and only once all have\n * stopped erase their data (the request with it). Stopping first means no step can write rows\n * back after the erase; erasing nothing until then keeps the entries that name the instances\n * still to stop, so a retry can finish the job.\n */\nasync function eraseUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore\n): Promise<{ erased: boolean; pending: string[] }> {\n const pending: string[] = [];\n for (const instanceId of await store.runningInstances(userId)) {\n if (!(await stopInstance(env, instanceId))) pending.push(instanceId);\n }\n if (pending.length > 0) return { erased: false, pending };\n await store.forgetUser(userId);\n return { erased: true, pending };\n}\n\n/**\n * Forget a user (a deleted account): the request is recorded first, then carried out. An\n * instance that will not stop leaves it pending — nothing erased yet — and the scheduled sweep\n * retries it; `erased: false` says so.\n */\nexport async function forgetUser(\n env: JourneyEnv,\n userId: string,\n store: JourneyStore = d1Store(env),\n now = Date.now()\n): Promise<{ ok: true; erased: boolean; pending: string[] }> {\n await store.requestErasure(userId, now);\n return { ok: true, ...(await eraseUser(env, userId, store)) };\n}\n\n/**\n * The user signed out on the device: the token stays registered, bound to nobody, so the next\n * sign-in only has to bind it again. Wakes the former owner's device waits (`reachable('push')`\n * may no longer hold).\n */\nexport async function unbindDevice(\n env: JourneyEnv,\n token: string,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n const owner = await store.unbindDevice(token);\n const woke =\n owner === undefined ? 0 : await wakeSubscribers(env, store, owner, DEVICES_UPDATED_EVENT);\n return { ok: true, woke };\n}\n\n/** A push token forgotten for good (the push service reports it gone); wakes its owner's device waits. */\nexport async function removeDevice(\n env: JourneyEnv,\n token: string,\n store: JourneyStore = d1Store(env)\n): Promise<{ ok: true; woke: number }> {\n const owner = await store.removeDevice(token);\n const woke =\n owner === undefined ? 0 : await wakeSubscribers(env, store, owner, DEVICES_UPDATED_EVENT);\n return { ok: true, woke };\n}\n\n/* ---------------------------------- deploy ---------------------------------- */\n\nexport interface DeployResult {\n workflows: string[];\n /**\n * Workflows whose trigger type has no runtime routing yet — they deploy (the\n * IR is stored and versioned) but will never start until the routing lands.\n * Currently: date (TODO — needs cron + Queues, instance creation is\n * rate-limited and a date trigger fans out to the whole audience at once)\n * and webhook (TODO — needs endpoint allocation).\n */\n unrouted: { workflow: string; trigger: TriggerIR['type'] }[];\n}\n\n/** A bundle whose declared hashes do not describe its contents — rejected before anything is written. */\nexport class BundleIntegrityError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BundleIntegrityError';\n }\n}\n\n/**\n * Recompute every declared contentHash and refuse the bundle if one disagrees.\n *\n * The contentHash is the address an in-flight journey reads its IR from, so\n * a hash that does not describe its own content is a way to change what a\n * pinned instance executes: submit an edited flow under the old hash and the\n * next replay picks it up. The compiler always computes the hash it ships, so\n * a mismatch means a hand-rolled payload or a stale client — neither should be\n * able to overwrite a version that journeys are running.\n *\n * Each hash is recomputed exactly the way its compiler produced it: a workflow\n * hashes its whole IR (contentHash strips itself), a segment hashes only its\n * condition. Mirroring them is load-bearing — recomputing a segment over the\n * whole record would reject every honest deploy.\n */\nfunction verifyBundleHashes(parsed: BundleIR): void {\n const mismatched: string[] = [];\n for (const workflow of parsed.workflows) {\n if (semanticHash(workflow) !== workflow.contentHash) {\n mismatched.push(`workflow '${workflow.id}'`);\n }\n }\n for (const segment of parsed.segments) {\n if (semanticHash(segment.condition) !== segment.contentHash) {\n mismatched.push(`segment '${segment.id}'`);\n }\n }\n if (mismatched.length > 0) {\n throw new BundleIntegrityError(\n `contentHash does not match content for ${mismatched.join(', ')} — recompile the bundle instead of editing it by hand`\n );\n }\n}\n\n/** Bundle deploy, terraform-apply style: workflow bodies first (content-addressed, so a failed deploy leaves only harmless orphans), then the routing swap. */\nexport async function deployBundle(\n env: JourneyEnv,\n bundle: unknown,\n store: JourneyStore = d1Store(env)\n): Promise<DeployResult> {\n const parsed = BundleIR.parse(bundle);\n // Before any write: a bad hash must not reach the store, where it would address content it does not describe\n verifyBundleHashes(parsed);\n // Nor a bundle the database cannot hold: the host migrates, the engine only checks\n const problems = (await store.checkSchema?.()) ?? [];\n if (problems.length > 0) throw new SchemaMismatchError(problems);\n\n for (const workflow of parsed.workflows) await store.putWorkflowIR(workflow);\n await store.replaceRoutes(parsed);\n\n const unrouted = parsed.workflows\n .filter((workflow) => workflow.trigger.type === 'date' || workflow.trigger.type === 'webhook')\n .map((workflow) => ({ workflow: workflow.id, trigger: workflow.trigger.type }));\n\n return {\n workflows: parsed.workflows.map((w) => `${w.id}@${w.contentHash.slice(0, 8)}`),\n unrouted,\n };\n}\n\n/* ----------------------------------- http ----------------------------------- */\n\n/**\n * Request bodies are untrusted JSON. They are read as unknown fields and\n * checked, never cast into the shape they are supposed to have: a cast only\n * silences the compiler, and what arrives here reaches SQL parameters.\n */\nasync function readBody(request: Request): Promise<Record<string, unknown>> {\n const body: unknown = await request.json();\n return isPlainObject(body) ? body : {};\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0;\n}\n\n/**\n * How the ingest API applies a contract: 'enforce' refuses an invalid event or\n * patch with a 400 before anything is stored, woken or started; 'report' logs\n * the issues (event id, name, field paths — never the payload) and accepts it,\n * for checking real producers before turning enforcement on.\n */\nexport interface IngestValidation {\n contract?: Contract | undefined;\n mode?: 'enforce' | 'report' | undefined;\n}\n\nexport async function handleRequest(\n request: Request,\n env: JourneyEnv,\n store: JourneyStore = d1Store(env),\n validation: IngestValidation = {}\n): Promise<Response> {\n const url = new URL(request.url);\n const json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n const { contract } = validation;\n const enforce = validation.mode !== 'report';\n /** The contract's verdict: the value to use, or the response refusing the request. */\n const checked = <T>(\n result: ContractResult<T>,\n original: T,\n what: string\n ): { value: T } | { refused: Response } => {\n if (result.ok) return { value: result.data };\n const issues = result.issues.map((i) => `${i.path || '(root)'}: ${i.message}`);\n if (!enforce) {\n console.warn(`[workflow router] contract would refuse ${what}: ${issues.join('; ')}`);\n return { value: original };\n }\n return {\n refused: json({ error: `${what} refused by the contract`, issues: result.issues }, 400),\n };\n };\n\n if (request.method === 'GET' && url.pathname === '/health') {\n return json({ ok: true });\n }\n\n // Bearer auth on everything mutating. An unset token means an open dev\n // instance (see JourneyEnv.API_TOKEN) — production must configure it.\n if (env.API_TOKEN !== undefined) {\n if (request.headers.get('authorization') !== `Bearer ${env.API_TOKEN}`) {\n return json({ error: 'unauthorized' }, 401);\n }\n }\n\n try {\n if (request.method === 'POST' && url.pathname === '/events') {\n const { id, userId, event, payload, ts } = await readBody(request);\n if (!isNonEmptyString(userId) || !isNonEmptyString(event)) {\n return json({ error: 'userId and event required' }, 400);\n }\n if (event.startsWith('$')) {\n return json({ error: 'event names starting with $ are reserved' }, 400);\n }\n // An empty id is rejected rather than treated as absent: a caller that\n // sent one meant to identify the occurrence, and silently minting a\n // different one would turn their retry into a duplicate.\n if (id !== undefined && !isNonEmptyString(id)) {\n return json({ error: 'id must be a non-empty string' }, 400);\n }\n if (ts !== undefined && typeof ts !== 'number') {\n return json({ error: 'ts must be a number' }, 400);\n }\n if (payload !== undefined && !isPlainObject(payload)) {\n return json({ error: 'payload must be an object' }, 400);\n }\n let accepted = payload;\n if (contract !== undefined) {\n const verdict = checked(\n checkEvent(contract, event, payload ?? {}),\n accepted ?? {},\n `event '${event}'${typeof id === 'string' ? ` (${id})` : ''}`\n );\n if ('refused' in verdict) return verdict.refused;\n accepted = verdict.value;\n }\n return json(await ingestEvent(env, { id, userId, event, payload: accepted, ts }, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/identify') {\n const { userId, props } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n if (!isPlainObject(props)) return json({ error: 'props must be an object' }, 400);\n let patch = props as ProfileProps;\n if (contract !== undefined) {\n const verdict = checked(contract.parseProfilePatch(props), patch, 'identify');\n if ('refused' in verdict) return verdict.refused;\n patch = verdict.value as ProfileProps;\n }\n return json(await identifyUser(env, userId, patch, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/devices') {\n const { userId, token, platform, ts } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n if (!isNonEmptyString(token)) return json({ error: 'token required' }, 400);\n if (platform !== 'ios' && platform !== 'android' && platform !== 'web') {\n return json({ error: \"platform must be 'ios', 'android' or 'web'\" }, 400);\n }\n if (ts !== undefined && typeof ts !== 'number')\n return json({ error: 'ts must be a number' }, 400);\n return json(\n await registerDevice(\n env,\n { userId, token, platform, ...(ts === undefined ? {} : { ts }) },\n store\n )\n );\n }\n\n if (request.method === 'POST' && url.pathname === '/messages/opened') {\n const { userId, messageId } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n if (!isNonEmptyString(messageId)) return json({ error: 'messageId required' }, 400);\n const recorded =\n store.reporting !== undefined && (await recordPushOpen(store.reporting, userId, messageId));\n return json({ ok: true, recorded });\n }\n\n if (request.method === 'POST' && url.pathname === '/users/forget') {\n const { userId } = await readBody(request);\n if (!isNonEmptyString(userId)) return json({ error: 'userId required' }, 400);\n return json(await forgetUser(env, userId, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/devices/unbind') {\n const { token } = await readBody(request);\n if (!isNonEmptyString(token)) return json({ error: 'token required' }, 400);\n return json(await unbindDevice(env, token, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/devices/remove') {\n const { token } = await readBody(request);\n if (!isNonEmptyString(token)) return json({ error: 'token required' }, 400);\n return json(await removeDevice(env, token, store));\n }\n\n if (request.method === 'POST' && url.pathname === '/deploy') {\n return json(await deployBundle(env, await request.json(), store));\n }\n\n return json({ error: 'not found' }, 404);\n } catch (error) {\n // Validation problems are the caller's to fix; anything else stays out of\n // the response body (internals are logged, not leaked).\n if (error instanceof z.core.$ZodError) {\n return json({ error: `invalid payload: ${error.message}` }, 400);\n }\n // The caller sent a self-inconsistent bundle: their problem to fix, so say what is wrong\n if (error instanceof BundleIntegrityError) {\n return json({ error: error.message }, 400);\n }\n // The operator's to fix (run the migrations), so the response says what is missing\n if (error instanceof SchemaMismatchError) {\n return json({ error: error.message, problems: error.problems }, 503);\n }\n console.error('[workflow router]', error);\n return json({ error: 'internal error' }, 500);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsEA,eAAsB,YACpB,KACA,OACA,QAAsBA,0BAAAA,QAAQ,GAAG,GACV;CACvB,IAAI,MAAM,MAAM,WAAW,GAAG,GAC5B,MAAM,IAAI,MAAM,eAAe,MAAM,MAAM,uCAAuC;CAEpF,MAAM,KAAK,MAAM,MAAM,KAAK,IAAI;CAChC,MAAM,UAAU,MAAM,WAAW,CAAC;CAIlC,MAAM,KAAK,MAAM,MAAM,OAAO,WAAW;CAEzC,MAAM,SAAS,MAAM,MAAM,YAAY;EACrC;EACA,QAAQ,MAAM;EACd,OAAO,MAAM;EACb;EACA;CACF,CAAC;CASD,MAAM,OAAO,MAAM,gBAAgB,KAAK,OAAO,MAAM,QAAQ,MAAM,KAAK;CACxE,MAAM,UAAU,MAAM,uBAAuB,KAAK,OAAO;EAAE,GAAG;EAAO;CAAQ,GAAG,EAAE;CAClF,QAAQ,KAAK,GAAI,MAAM,uBAAuB,KAAK,OAAO,MAAM,QAAQ,EAAE,CAAE;CAC5E,OAAO;EAAE;EAAI;EAAQ;EAAM;CAAQ;AACrC;AAEA,eAAe,gBACb,KACA,OACA,QACA,OACiB;CACjB,IAAI,OAAO;CACX,KAAK,MAAM,UAAU,MAAM,MAAM,gBAAgB,QAAQ,KAAK,GAAG;EAC/D,IAAI;EACJ,IAAI;GACF,WAAW,MAAM,IAAI,QAAQ,IAAI,MAAM;EACzC,QAAQ;GAEN,MAAM,M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