@shware/workflow 3.3.0 → 4.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 (350) hide show
  1. package/README.md +91 -29
  2. package/dist/apns.cjs +113 -26
  3. package/dist/apns.cjs.map +1 -1
  4. package/dist/apns.d.cts +52 -6
  5. package/dist/apns.d.cts.map +1 -1
  6. package/dist/apns.d.mts +52 -6
  7. package/dist/apns.d.mts.map +1 -1
  8. package/dist/apns.mjs +111 -27
  9. package/dist/apns.mjs.map +1 -1
  10. package/dist/aws/engine-step.cjs +5 -5
  11. package/dist/aws/engine-step.cjs.map +1 -1
  12. package/dist/aws/engine-step.d.cts +8 -2
  13. package/dist/aws/engine-step.d.cts.map +1 -1
  14. package/dist/aws/engine-step.d.mts +8 -2
  15. package/dist/aws/engine-step.d.mts.map +1 -1
  16. package/dist/aws/engine-step.mjs +5 -5
  17. package/dist/aws/engine-step.mjs.map +1 -1
  18. package/dist/aws/index.cjs +47 -6
  19. package/dist/aws/index.cjs.map +1 -1
  20. package/dist/aws/index.d.cts +2 -2
  21. package/dist/aws/index.d.cts.map +1 -1
  22. package/dist/aws/index.d.mts +2 -2
  23. package/dist/aws/index.d.mts.map +1 -1
  24. package/dist/aws/index.mjs +47 -6
  25. package/dist/aws/index.mjs.map +1 -1
  26. package/dist/aws/instances.cjs +29 -6
  27. package/dist/aws/instances.cjs.map +1 -1
  28. package/dist/aws/instances.d.cts +11 -1
  29. package/dist/aws/instances.d.cts.map +1 -1
  30. package/dist/aws/instances.d.mts +11 -1
  31. package/dist/aws/instances.d.mts.map +1 -1
  32. package/dist/aws/instances.mjs +27 -4
  33. package/dist/aws/instances.mjs.map +1 -1
  34. package/dist/client.cjs +4 -1
  35. package/dist/client.cjs.map +1 -1
  36. package/dist/client.d.cts +2 -2
  37. package/dist/client.d.cts.map +1 -1
  38. package/dist/client.d.mts +2 -2
  39. package/dist/client.d.mts.map +1 -1
  40. package/dist/client.mjs +4 -1
  41. package/dist/client.mjs.map +1 -1
  42. package/dist/cloudflare/bindings.cjs +28 -25
  43. package/dist/cloudflare/bindings.cjs.map +1 -1
  44. package/dist/cloudflare/bindings.d.cts +15 -129
  45. package/dist/cloudflare/bindings.d.cts.map +1 -1
  46. package/dist/cloudflare/bindings.d.mts +15 -129
  47. package/dist/cloudflare/bindings.d.mts.map +1 -1
  48. package/dist/cloudflare/bindings.mjs +28 -23
  49. package/dist/cloudflare/bindings.mjs.map +1 -1
  50. package/dist/cloudflare/d1-env.cjs +6 -6
  51. package/dist/cloudflare/d1-env.cjs.map +1 -1
  52. package/dist/cloudflare/d1-env.d.cts +5 -5
  53. package/dist/cloudflare/d1-env.d.mts +5 -5
  54. package/dist/cloudflare/d1-env.mjs +6 -6
  55. package/dist/cloudflare/d1-env.mjs.map +1 -1
  56. package/dist/cloudflare/index.cjs +28 -18
  57. package/dist/cloudflare/index.d.cts +8 -4
  58. package/dist/cloudflare/index.d.mts +8 -4
  59. package/dist/cloudflare/index.mjs +9 -5
  60. package/dist/cloudflare/runner.cjs +29 -14
  61. package/dist/cloudflare/runner.cjs.map +1 -1
  62. package/dist/cloudflare/runner.d.cts +9 -2
  63. package/dist/cloudflare/runner.d.cts.map +1 -1
  64. package/dist/cloudflare/runner.d.mts +9 -2
  65. package/dist/cloudflare/runner.d.mts.map +1 -1
  66. package/dist/cloudflare/runner.mjs +28 -13
  67. package/dist/cloudflare/runner.mjs.map +1 -1
  68. package/dist/cloudflare/schema.sql +27 -6
  69. package/dist/cloudflare/worker.cjs +19 -9
  70. package/dist/cloudflare/worker.cjs.map +1 -1
  71. package/dist/cloudflare/worker.d.cts +2 -2
  72. package/dist/cloudflare/worker.d.cts.map +1 -1
  73. package/dist/cloudflare/worker.d.mts +2 -2
  74. package/dist/cloudflare/worker.d.mts.map +1 -1
  75. package/dist/cloudflare/worker.mjs +19 -9
  76. package/dist/cloudflare/worker.mjs.map +1 -1
  77. package/dist/config.cjs +21 -5
  78. package/dist/config.cjs.map +1 -1
  79. package/dist/config.mjs +21 -5
  80. package/dist/config.mjs.map +1 -1
  81. package/dist/dsl/action.cjs +3 -6
  82. package/dist/dsl/action.cjs.map +1 -1
  83. package/dist/dsl/action.d.cts +12 -11
  84. package/dist/dsl/action.d.cts.map +1 -1
  85. package/dist/dsl/action.d.mts +12 -11
  86. package/dist/dsl/action.d.mts.map +1 -1
  87. package/dist/dsl/action.mjs +3 -6
  88. package/dist/dsl/action.mjs.map +1 -1
  89. package/dist/dsl/bundle.cjs +35 -31
  90. package/dist/dsl/bundle.cjs.map +1 -1
  91. package/dist/dsl/bundle.d.cts.map +1 -1
  92. package/dist/dsl/bundle.d.mts.map +1 -1
  93. package/dist/dsl/bundle.mjs +35 -31
  94. package/dist/dsl/bundle.mjs.map +1 -1
  95. package/dist/dsl/condition.cjs +13 -1
  96. package/dist/dsl/condition.cjs.map +1 -1
  97. package/dist/dsl/condition.d.cts +9 -1
  98. package/dist/dsl/condition.d.cts.map +1 -1
  99. package/dist/dsl/condition.d.mts +9 -1
  100. package/dist/dsl/condition.d.mts.map +1 -1
  101. package/dist/dsl/condition.mjs +13 -2
  102. package/dist/dsl/condition.mjs.map +1 -1
  103. package/dist/dsl/flow.cjs +33 -11
  104. package/dist/dsl/flow.cjs.map +1 -1
  105. package/dist/dsl/flow.d.cts +9 -1
  106. package/dist/dsl/flow.d.cts.map +1 -1
  107. package/dist/dsl/flow.d.mts +9 -1
  108. package/dist/dsl/flow.d.mts.map +1 -1
  109. package/dist/dsl/flow.mjs +34 -13
  110. package/dist/dsl/flow.mjs.map +1 -1
  111. package/dist/dsl/workflow.cjs +2 -3
  112. package/dist/dsl/workflow.cjs.map +1 -1
  113. package/dist/dsl/workflow.d.cts.map +1 -1
  114. package/dist/dsl/workflow.d.mts.map +1 -1
  115. package/dist/dsl/workflow.mjs +3 -4
  116. package/dist/dsl/workflow.mjs.map +1 -1
  117. package/dist/engine/actions.cjs +1 -8
  118. package/dist/engine/actions.cjs.map +1 -1
  119. package/dist/engine/actions.d.cts +1 -12
  120. package/dist/engine/actions.d.cts.map +1 -1
  121. package/dist/engine/actions.d.mts +1 -12
  122. package/dist/engine/actions.d.mts.map +1 -1
  123. package/dist/engine/actions.mjs +1 -8
  124. package/dist/engine/actions.mjs.map +1 -1
  125. package/dist/engine/condition.cjs +25 -5
  126. package/dist/engine/condition.cjs.map +1 -1
  127. package/dist/engine/condition.d.cts +12 -3
  128. package/dist/engine/condition.d.cts.map +1 -1
  129. package/dist/engine/condition.d.mts +12 -3
  130. package/dist/engine/condition.d.mts.map +1 -1
  131. package/dist/engine/condition.mjs +25 -6
  132. package/dist/engine/condition.mjs.map +1 -1
  133. package/dist/engine/index.cjs +3 -0
  134. package/dist/engine/index.d.cts +5 -5
  135. package/dist/engine/index.d.mts +5 -5
  136. package/dist/engine/index.mjs +4 -4
  137. package/dist/engine/interpreter.cjs +27 -20
  138. package/dist/engine/interpreter.cjs.map +1 -1
  139. package/dist/engine/interpreter.d.cts.map +1 -1
  140. package/dist/engine/interpreter.d.mts.map +1 -1
  141. package/dist/engine/interpreter.mjs +27 -20
  142. package/dist/engine/interpreter.mjs.map +1 -1
  143. package/dist/engine/ports.d.cts +15 -6
  144. package/dist/engine/ports.d.cts.map +1 -1
  145. package/dist/engine/ports.d.mts +15 -6
  146. package/dist/engine/ports.d.mts.map +1 -1
  147. package/dist/engine/retry.cjs +13 -0
  148. package/dist/engine/retry.cjs.map +1 -1
  149. package/dist/engine/retry.d.cts +12 -0
  150. package/dist/engine/retry.d.cts.map +1 -1
  151. package/dist/engine/retry.d.mts +12 -0
  152. package/dist/engine/retry.d.mts.map +1 -1
  153. package/dist/engine/retry.mjs +13 -1
  154. package/dist/engine/retry.mjs.map +1 -1
  155. package/dist/engine/time-scale.cjs +90 -15
  156. package/dist/engine/time-scale.cjs.map +1 -1
  157. package/dist/engine/time-scale.d.cts +9 -6
  158. package/dist/engine/time-scale.d.cts.map +1 -1
  159. package/dist/engine/time-scale.d.mts +9 -6
  160. package/dist/engine/time-scale.d.mts.map +1 -1
  161. package/dist/engine/time-scale.mjs +90 -16
  162. package/dist/engine/time-scale.mjs.map +1 -1
  163. package/dist/fcm.cjs +111 -38
  164. package/dist/fcm.cjs.map +1 -1
  165. package/dist/fcm.d.cts +45 -5
  166. package/dist/fcm.d.cts.map +1 -1
  167. package/dist/fcm.d.mts +45 -5
  168. package/dist/fcm.d.mts.map +1 -1
  169. package/dist/fcm.mjs +110 -39
  170. package/dist/fcm.mjs.map +1 -1
  171. package/dist/hash.cjs +6 -6
  172. package/dist/hash.cjs.map +1 -1
  173. package/dist/hash.mjs +6 -6
  174. package/dist/hash.mjs.map +1 -1
  175. package/dist/host/auth.cjs +49 -0
  176. package/dist/host/auth.cjs.map +1 -0
  177. package/dist/host/auth.d.cts +21 -0
  178. package/dist/host/auth.d.cts.map +1 -0
  179. package/dist/host/auth.d.mts +21 -0
  180. package/dist/host/auth.d.mts.map +1 -0
  181. package/dist/host/auth.mjs +47 -0
  182. package/dist/host/auth.mjs.map +1 -0
  183. package/dist/host/channels.cjs +118 -40
  184. package/dist/host/channels.cjs.map +1 -1
  185. package/dist/host/channels.d.cts +27 -1
  186. package/dist/host/channels.d.cts.map +1 -1
  187. package/dist/host/channels.d.mts +27 -1
  188. package/dist/host/channels.d.mts.map +1 -1
  189. package/dist/host/channels.mjs +121 -44
  190. package/dist/host/channels.mjs.map +1 -1
  191. package/dist/host/execute.cjs +14 -2
  192. package/dist/host/execute.cjs.map +1 -1
  193. package/dist/host/execute.d.cts +4 -4
  194. package/dist/host/execute.d.cts.map +1 -1
  195. package/dist/host/execute.d.mts +4 -4
  196. package/dist/host/execute.d.mts.map +1 -1
  197. package/dist/host/execute.mjs +13 -1
  198. package/dist/host/execute.mjs.map +1 -1
  199. package/dist/host/fresh-read.cjs +30 -0
  200. package/dist/host/fresh-read.cjs.map +1 -0
  201. package/dist/host/fresh-read.d.cts +18 -0
  202. package/dist/host/fresh-read.d.cts.map +1 -0
  203. package/dist/host/fresh-read.d.mts +18 -0
  204. package/dist/host/fresh-read.d.mts.map +1 -0
  205. package/dist/host/fresh-read.mjs +29 -0
  206. package/dist/host/fresh-read.mjs.map +1 -0
  207. package/dist/host/http.cjs +321 -0
  208. package/dist/host/http.cjs.map +1 -0
  209. package/dist/host/http.d.cts +54 -0
  210. package/dist/host/http.d.cts.map +1 -0
  211. package/dist/host/http.d.mts +54 -0
  212. package/dist/host/http.d.mts.map +1 -0
  213. package/dist/host/http.mjs +317 -0
  214. package/dist/host/http.mjs.map +1 -0
  215. package/dist/host/{router.cjs → ingest.cjs} +147 -175
  216. package/dist/host/ingest.cjs.map +1 -0
  217. package/dist/host/{router.d.cts → ingest.d.cts} +48 -30
  218. package/dist/host/ingest.d.cts.map +1 -0
  219. package/dist/host/{router.d.mts → ingest.d.mts} +48 -30
  220. package/dist/host/ingest.d.mts.map +1 -0
  221. package/dist/host/{router.mjs → ingest.mjs} +144 -173
  222. package/dist/host/ingest.mjs.map +1 -0
  223. package/dist/host/journey-host.cjs +65 -93
  224. package/dist/host/journey-host.cjs.map +1 -1
  225. package/dist/host/journey-host.d.cts +19 -26
  226. package/dist/host/journey-host.d.cts.map +1 -1
  227. package/dist/host/journey-host.d.mts +19 -26
  228. package/dist/host/journey-host.d.mts.map +1 -1
  229. package/dist/host/journey-host.mjs +65 -93
  230. package/dist/host/journey-host.mjs.map +1 -1
  231. package/dist/host/platform.cjs +21 -0
  232. package/dist/host/platform.cjs.map +1 -0
  233. package/dist/host/platform.d.cts +126 -0
  234. package/dist/host/platform.d.cts.map +1 -0
  235. package/dist/host/platform.d.mts +126 -0
  236. package/dist/host/platform.d.mts.map +1 -0
  237. package/dist/host/platform.mjs +19 -0
  238. package/dist/host/platform.mjs.map +1 -0
  239. package/dist/host/senders.cjs +18 -9
  240. package/dist/host/senders.cjs.map +1 -1
  241. package/dist/host/senders.d.cts +9 -4
  242. package/dist/host/senders.d.cts.map +1 -1
  243. package/dist/host/senders.d.mts +9 -4
  244. package/dist/host/senders.d.mts.map +1 -1
  245. package/dist/host/senders.mjs +18 -9
  246. package/dist/host/senders.mjs.map +1 -1
  247. package/dist/index.cjs +1 -1
  248. package/dist/index.mjs +1 -1
  249. package/dist/ir.cjs +5 -7
  250. package/dist/ir.cjs.map +1 -1
  251. package/dist/ir.d.cts +3 -12
  252. package/dist/ir.d.cts.map +1 -1
  253. package/dist/ir.d.mts +3 -12
  254. package/dist/ir.d.mts.map +1 -1
  255. package/dist/ir.mjs +5 -7
  256. package/dist/ir.mjs.map +1 -1
  257. package/dist/plan.cjs +27 -33
  258. package/dist/plan.cjs.map +1 -1
  259. package/dist/plan.d.cts +1 -1
  260. package/dist/plan.d.cts.map +1 -1
  261. package/dist/plan.d.mts +1 -1
  262. package/dist/plan.d.mts.map +1 -1
  263. package/dist/plan.mjs +27 -33
  264. package/dist/plan.mjs.map +1 -1
  265. package/dist/reporting/tracking.cjs +14 -4
  266. package/dist/reporting/tracking.cjs.map +1 -1
  267. package/dist/reporting/tracking.d.cts +10 -10
  268. package/dist/reporting/tracking.d.cts.map +1 -1
  269. package/dist/reporting/tracking.d.mts +10 -10
  270. package/dist/reporting/tracking.d.mts.map +1 -1
  271. package/dist/reporting/tracking.mjs +14 -4
  272. package/dist/reporting/tracking.mjs.map +1 -1
  273. package/dist/store/d1.cjs +88 -29
  274. package/dist/store/d1.cjs.map +1 -1
  275. package/dist/store/d1.d.cts +29 -11
  276. package/dist/store/d1.d.cts.map +1 -1
  277. package/dist/store/d1.d.mts +29 -11
  278. package/dist/store/d1.d.mts.map +1 -1
  279. package/dist/store/d1.mjs +88 -29
  280. package/dist/store/d1.mjs.map +1 -1
  281. package/dist/store/erasure.cjs +22 -0
  282. package/dist/store/erasure.cjs.map +1 -0
  283. package/dist/store/erasure.d.cts +18 -0
  284. package/dist/store/erasure.d.cts.map +1 -0
  285. package/dist/store/erasure.d.mts +18 -0
  286. package/dist/store/erasure.d.mts.map +1 -0
  287. package/dist/store/erasure.mjs +21 -0
  288. package/dist/store/erasure.mjs.map +1 -0
  289. package/dist/store/index.cjs +2 -0
  290. package/dist/store/index.cjs.map +1 -1
  291. package/dist/store/index.d.cts +67 -13
  292. package/dist/store/index.d.cts.map +1 -1
  293. package/dist/store/index.d.mts +67 -13
  294. package/dist/store/index.d.mts.map +1 -1
  295. package/dist/store/index.mjs +2 -1
  296. package/dist/store/index.mjs.map +1 -1
  297. package/dist/store/postgres-reporting.cjs +125 -62
  298. package/dist/store/postgres-reporting.cjs.map +1 -1
  299. package/dist/store/postgres-reporting.d.cts +30 -2
  300. package/dist/store/postgres-reporting.d.cts.map +1 -1
  301. package/dist/store/postgres-reporting.d.mts +30 -2
  302. package/dist/store/postgres-reporting.d.mts.map +1 -1
  303. package/dist/store/postgres-reporting.mjs +125 -62
  304. package/dist/store/postgres-reporting.mjs.map +1 -1
  305. package/dist/store/postgres.cjs +179 -60
  306. package/dist/store/postgres.cjs.map +1 -1
  307. package/dist/store/postgres.d.cts +44 -7
  308. package/dist/store/postgres.d.cts.map +1 -1
  309. package/dist/store/postgres.d.mts +44 -7
  310. package/dist/store/postgres.d.mts.map +1 -1
  311. package/dist/store/postgres.mjs +179 -60
  312. package/dist/store/postgres.mjs.map +1 -1
  313. package/dist/store/tables.cjs +7 -5
  314. package/dist/store/tables.cjs.map +1 -1
  315. package/dist/store/tables.d.cts.map +1 -1
  316. package/dist/store/tables.d.mts.map +1 -1
  317. package/dist/store/tables.mjs +7 -5
  318. package/dist/store/tables.mjs.map +1 -1
  319. package/dist/store/user-lock.cjs +43 -0
  320. package/dist/store/user-lock.cjs.map +1 -0
  321. package/dist/store/user-lock.d.cts +32 -0
  322. package/dist/store/user-lock.d.cts.map +1 -0
  323. package/dist/store/user-lock.d.mts +32 -0
  324. package/dist/store/user-lock.d.mts.map +1 -0
  325. package/dist/store/user-lock.mjs +40 -0
  326. package/dist/store/user-lock.mjs.map +1 -0
  327. package/dist/transports/cloudflare-email.cjs +1 -1
  328. package/dist/transports/cloudflare-email.mjs +1 -1
  329. package/dist/transports/ses.cjs +47 -6
  330. package/dist/transports/ses.cjs.map +1 -1
  331. package/dist/transports/ses.d.cts +9 -1
  332. package/dist/transports/ses.d.cts.map +1 -1
  333. package/dist/transports/ses.d.mts +9 -1
  334. package/dist/transports/ses.d.mts.map +1 -1
  335. package/dist/transports/ses.mjs +47 -7
  336. package/dist/transports/ses.mjs.map +1 -1
  337. package/dist/webpush.cjs +133 -47
  338. package/dist/webpush.cjs.map +1 -1
  339. package/dist/webpush.d.cts +49 -8
  340. package/dist/webpush.d.cts.map +1 -1
  341. package/dist/webpush.d.mts +49 -8
  342. package/dist/webpush.d.mts.map +1 -1
  343. package/dist/webpush.mjs +130 -47
  344. package/dist/webpush.mjs.map +1 -1
  345. package/package.json +1 -1
  346. package/src/cloudflare/schema.sql +27 -6
  347. package/dist/host/router.cjs.map +0 -1
  348. package/dist/host/router.d.cts.map +0 -1
  349. package/dist/host/router.d.mts.map +0 -1
  350. package/dist/host/router.mjs.map +0 -1
@@ -1,17 +1,18 @@
1
1
  import { assertEmailConfig } from "../email.mjs";
2
- import { TemplateValidationError, indexTemplates, registryValidator } from "../templates.mjs";
2
+ import { indexTemplates, registryValidator } from "../templates.mjs";
3
3
  import { compileConfig } from "../config.mjs";
4
4
  import { ContractValidationError, checkEvent } from "../contract.mjs";
5
5
  import "../store/tables.mjs";
6
6
  import { registryRenderer } from "../react-email.mjs";
7
+ import { RECIPIENT_PROPERTY } from "../engine/recipient.mjs";
8
+ import { profileUpdatedEvent } from "../engine/condition.mjs";
7
9
  import { scaleSegmentWindows } from "../engine/time-scale.mjs";
8
10
  import { d1Store } from "../cloudflare/d1-env.mjs";
9
- import { handleTracking } from "../reporting/tracking.mjs";
10
- import { SchemaMismatchError } from "../store/index.mjs";
11
- import { deployBundle, handleRequest, ingestEvent, sweepSegments } from "./router.mjs";
11
+ import { deployBundle, ingestEvent, sweepSegments, wakeSubscribers } from "./ingest.mjs";
12
12
  import { RegistryActionInvoker } from "../engine/actions.mjs";
13
13
  import { reportingObserver } from "../reporting/observer.mjs";
14
- import { channelsFromConfig, runtimeFromConfig } from "./channels.mjs";
14
+ import { channelsFromConfig, createProviderCache, runtimeFromConfig } from "./channels.mjs";
15
+ import { serve } from "./http.mjs";
15
16
  import * as z from "zod/mini";
16
17
  //#region src/host/journey-host.ts
17
18
  /** The host's environment failed its schema (`env` option). */
@@ -34,21 +35,29 @@ function sendsEmail(nodes) {
34
35
  }
35
36
  });
36
37
  }
38
+ const describeIssue = (issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`;
39
+ /** An event the host emits itself, checked against the contract like any ingest. */
40
+ function checkedPayload(contract, event, payload) {
41
+ if (contract === void 0) return payload;
42
+ const verdict = checkEvent(contract, event, payload);
43
+ if (!verdict.ok) throw new ContractValidationError(event, verdict.issues);
44
+ return verdict.data;
45
+ }
37
46
  function createJourneyHost(options, platform = {}) {
38
47
  const { config } = options;
39
48
  const emailIds = indexTemplates("email", config.templates?.email);
40
49
  assertEmailConfig(config, emailIds.values());
41
- if (options.email === void 0 && options.messages === void 0) {
42
- const emailing = compileConfig(config).workflows.filter((workflow) => sendsEmail(workflow.flow));
43
- if (emailing.length > 0) throw new TypeError(`workflows ${emailing.map((w) => `'${w.id}'`).join(", ")} send email, but the host has no \`email\` transport: pass \`email: (env) => cloudflareEmailTransport(...)\` or \`sesEmailTransport(...)\``);
44
- }
50
+ let compiled;
51
+ const bundle = () => compiled ??= compileConfig(config);
52
+ const emailing = bundle().workflows.filter((workflow) => sendsEmail(workflow.flow));
53
+ if (options.email === void 0 && options.messages === void 0 && emailing.length > 0) throw new TypeError(`workflows ${emailing.map((w) => `'${w.id}'`).join(", ")} send email, but the host has no \`email\` transport: pass \`email: (env) => cloudflareEmailTransport(...)\` or \`sesEmailTransport(...)\``);
45
54
  const checked = /* @__PURE__ */ new WeakMap();
46
55
  const checkEnv = (env) => {
47
56
  if (options.env === void 0) return env;
48
57
  const cached = checked.get(env);
49
58
  if (cached !== void 0) return cached;
50
59
  const result = z.safeParse(options.env, env);
51
- if (!result.success) throw new EnvValidationError(result.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`));
60
+ if (!result.success) throw new EnvValidationError(result.error.issues.map(describeIssue));
52
61
  const merged = {
53
62
  ...env,
54
63
  ...result.data
@@ -56,8 +65,6 @@ function createJourneyHost(options, platform = {}) {
56
65
  checked.set(env, merged);
57
66
  return merged;
58
67
  };
59
- let compiled;
60
- const bundle = () => compiled ??= compileConfig(config);
61
68
  const emails = config.templates?.email;
62
69
  const database = { schema: config.database?.schema ?? "workflow" };
63
70
  const lease = (env) => {
@@ -72,12 +79,14 @@ function createJourneyHost(options, platform = {}) {
72
79
  close: noop
73
80
  };
74
81
  };
82
+ const providers = createProviderCache();
75
83
  const messages = (env, store) => {
76
84
  if (options.messages !== void 0) return options.messages(env, store);
77
85
  return channelsFromConfig(config, env, {
78
86
  store,
79
87
  email: options.email?.(env),
80
- apnsFetch: platform.apnsFetch
88
+ apnsFetch: platform.apnsFetch,
89
+ providers
81
90
  });
82
91
  };
83
92
  const observer = (env, store) => {
@@ -94,90 +103,53 @@ function createJourneyHost(options, platform = {}) {
94
103
  validator: registryValidator(config.templates ?? {}),
95
104
  observer: observer(env, store)
96
105
  });
97
- const json = (body, status = 200) => new Response(JSON.stringify(body), {
98
- status,
99
- headers: { "content-type": "application/json" }
100
- });
101
- const authorized = (request, env) => env.API_TOKEN === void 0 || request.headers.get("authorization") === `Bearer ${env.API_TOKEN}`;
102
106
  const preview = emails === void 0 ? void 0 : registryRenderer(emails, config.email);
103
- const handle = async (request, env, store) => {
104
- const url = new URL(request.url);
105
- if (url.pathname.startsWith("/t/") && store.reporting !== void 0) {
106
- const openedEvent = config.webPush?.openedEvent;
107
- const tracked = await handleTracking(request, store.reporting, {
108
- legacyUnsubscribeUrl: config.email?.unsubscribeUrl,
109
- product: config.title,
110
- quickMs: config.email?.tracking?.quickClickMs,
111
- pushOpened: openedEvent === void 0 ? void 0 : async ({ messageId, userId, at }) => {
112
- const payload = { message_id: messageId };
113
- const contract = config.contract;
114
- const verdict = contract === void 0 ? void 0 : checkEvent(contract, openedEvent, payload);
115
- if (verdict !== void 0 && !verdict.ok) throw new ContractValidationError(openedEvent, verdict.issues);
116
- await ingestEvent(env, {
117
- id: `${openedEvent}:${messageId}`,
118
- userId,
119
- event: openedEvent,
120
- payload: verdict?.data ?? payload,
121
- ts: at
122
- }, store);
123
- }
124
- });
125
- if (tracked !== void 0) return tracked;
126
- }
127
- if (url.pathname === "/segments/sweep") {
128
- if (!authorized(request, env)) return json({ error: "unauthorized" }, 401);
129
- if (request.method !== "POST") return json({ error: "method not allowed" }, 405);
130
- return json(await sweepSegments(env, store));
131
- }
132
- if (url.pathname === "/bundle") {
133
- if (!authorized(request, env)) return json({ error: "unauthorized" }, 401);
134
- if (request.method !== "GET") return json({ error: "method not allowed" }, 405);
135
- return json(bundle());
136
- }
137
- if (url.pathname === "/bundle/deploy") {
138
- if (!authorized(request, env)) return json({ error: "unauthorized" }, 401);
139
- if (request.method !== "POST") return json({ error: "method not allowed" }, 405);
140
- try {
141
- return json(await deployBundle(env, bundle(), store));
142
- } catch (error) {
143
- if (!(error instanceof SchemaMismatchError)) throw error;
144
- return json({
145
- error: error.message,
146
- problems: error.problems
147
- }, 503);
107
+ /**
108
+ * The recipients' routes (`/t/*`): a push tapped open is recorded as the config's
109
+ * `webPush.openedEvent` — keyed by the copy, so a second tap of the same notification is the
110
+ * same event — and an unsubscribe wakes the waits reading email reachability (`reachable
111
+ * ('email')` subscribes to the email property's channel), so an `exitWhen:
112
+ * not(reachable('email'))` takes effect without waiting for a timeout.
113
+ */
114
+ const tracking = (env, store) => {
115
+ const opened = config.webPush?.openedEvent;
116
+ return {
117
+ product: config.title,
118
+ quickMs: config.email?.tracking?.quickClickMs,
119
+ pushOpened: opened === void 0 ? void 0 : async ({ messageId, userId, at }) => {
120
+ const payload = checkedPayload(config.contract, opened, { message_id: messageId });
121
+ const input = {
122
+ id: `${opened}:${messageId}`,
123
+ userId,
124
+ event: opened,
125
+ payload,
126
+ ts: at
127
+ };
128
+ await ingestEvent(env, input, store);
129
+ },
130
+ onUnsubscribed: async ({ userId }) => {
131
+ const email = profileUpdatedEvent(RECIPIENT_PROPERTY.email ?? "email");
132
+ await wakeSubscribers(env, store, userId, [email]);
148
133
  }
149
- }
150
- if (emails !== void 0 && preview !== void 0 && url.pathname.startsWith("/preview/")) {
151
- if (!authorized(request, env)) return json({ error: "unauthorized" }, 401);
152
- if (request.method !== "GET") return json({ error: "method not allowed" }, 405);
153
- const key = url.pathname.slice(9);
154
- if (!emailIds.has(key)) return json({ error: `unknown email template: ${key}` }, 404);
155
- let props = {};
156
- try {
157
- props = JSON.parse(url.searchParams.get("props") ?? "{}");
158
- } catch {
159
- return json({ error: "props must be a JSON object" }, 400);
160
- }
161
- if (typeof props !== "object" || props === null || Array.isArray(props)) return json({ error: "props must be a JSON object" }, 400);
162
- try {
163
- const { subject, html } = await preview(key, props);
164
- return new Response(html, { headers: {
165
- "content-type": "text/html; charset=utf-8",
166
- "x-subject": subject
167
- } });
168
- } catch (error) {
169
- if (error instanceof TemplateValidationError) return json({
170
- error: error.message,
171
- issues: error.issues
172
- }, 400);
173
- throw error;
174
- }
175
- }
176
- return handleRequest(request, env, store, {
134
+ };
135
+ };
136
+ const handle = (request, env, store) => serve(request, {
137
+ env,
138
+ store,
139
+ validation: {
177
140
  contract: config.contract,
178
141
  mode: options.contractMode
179
- });
180
- };
142
+ },
143
+ host: {
144
+ bundle,
145
+ preview: preview === void 0 ? void 0 : {
146
+ has: (id) => emailIds.has(id),
147
+ render: preview
148
+ },
149
+ tracking: tracking(env, store),
150
+ sweep: () => sweepSegments(env, store)
151
+ }
152
+ });
181
153
  const sweep = async (env) => {
182
154
  const { store, close } = lease(env);
183
155
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"journey-host.mjs","names":[],"sources":["../../src/host/journey-host.ts"],"sourcesContent":["import * as z from 'zod/mini';\nimport type * as core from 'zod/v4/core';\nimport type { JourneyEnv, JourneyParams } from '../cloudflare/bindings';\nimport { d1Store } from '../cloudflare/d1-env';\nimport { type JourneyConfig, compileConfig } from '../config';\nimport { ContractValidationError, checkEvent } from '../contract';\nimport { assertEmailConfig } from '../email';\nimport type { EmailTransport } from '../email-sender';\nimport { RegistryActionInvoker } from '../engine/actions';\nimport type { JourneyObserver, MessageSender } from '../engine/ports';\nimport { scaleSegmentWindows } from '../engine/time-scale';\nimport type { BundleIR, NodeIR, ScalarIR } from '../ir';\nimport { registryRenderer } from '../react-email';\nimport { reportingObserver } from '../reporting/observer';\nimport { handleTracking } from '../reporting/tracking';\nimport type { JourneyRuntimeOptions } from '../runtime';\nimport {\n type BundleVersion,\n type JourneyStore,\n SchemaMismatchError,\n type StoreLease,\n} from '../store/index';\nimport { DEFAULT_SCHEMA } from '../store/tables';\nimport { TemplateValidationError, indexTemplates, registryValidator } from '../templates';\nimport { channelsFromConfig, runtimeFromConfig } from './channels';\nimport type { JourneyRunParts } from './execute';\nimport {\n type SweepResult,\n deployBundle,\n handleRequest,\n ingestEvent,\n sweepSegments,\n} from './router';\n\n/**\n * What a journey host is, apart from the runtime it runs on: the validated environment, the\n * store lease, the outlets a run is wired to, the HTTP API (tracking, sweep, bundle, preview,\n * ingest) and the bundle that goes live with the code. `journeyWorker` (Cloudflare) and\n * `journeyLambda` (AWS) are this plus how their platform starts, wakes and stops instances.\n */\n\nexport interface JourneyHostOptions<Env extends JourneyEnv> {\n /**\n * The project's `workflow.config.ts` (`defineConfig`): what the host\n * deploys (`GET /bundle`, `POST /bundle/deploy` serve `compileConfig`), the\n * template registries the senders, the validator and `/preview` render from,\n * the contract every `/events` and `/identify` is checked against, the email\n * defaults, actions, and the runtime / APNs / FCM settings. Secrets come\n * from the env under the names `JourneyEnv` documents.\n */\n config: JourneyConfig;\n /**\n * The data plane, opened per request and per workflow run. Return a\n * `StoreLease` when the client must be released afterwards (a Postgres\n * connection); defaults to D1 + KV from the env's bindings. `database` is\n * the config's (`schema` defaulting to `workflow`), for a Postgres store:\n *\n * store: (env, database) => postgresJsStore(env.DATABASE_URL, database)\n */\n store?: (env: Env, database: { schema: string }) => JourneyStore | StoreLease;\n /**\n * Where journey emails go: a transport built from the validated env —\n * `sesEmailTransport(...)`, `cloudflareEmailTransport(...)`, or your own. Which one is\n * independent of where the workflow runs. Without it the email channel fails its sends,\n * saying so.\n */\n email?: (env: Env) => EmailTransport;\n /**\n * Reporting hooks: node arrivals, every copy sent (with the tracking it should carry — click\n * links and an open pixel for email, payload data for a push), and how each instance ended.\n * By default a store that keeps reporting (Postgres) records them itself, and the host\n * serves the email tracking routes (`/t/...`, on `WORKFLOW_ORIGIN`); override to report\n * elsewhere.\n */\n observer?: (env: Env, store: JourneyStore) => JourneyObserver;\n /**\n * Message outlet override (tests, a custom gateway): replaces every channel, `email`\n * included. By default the channels the config describes.\n */\n messages?: (env: Env, store: JourneyStore) => MessageSender;\n /** Per-instance runtime options override (a tester in fast-forward); by default `config.runtime` for `ENVIRONMENT`. */\n runtime?: (env: Env, params: JourneyParams) => JourneyRuntimeOptions;\n /**\n * The host's environment, as a zod schema over its vars and secrets (bindings pass through\n * untouched): checked the first time the host runs, so a missing or malformed variable fails\n * there — every problem listed — not at the send that needs it. Webhook templates read their\n * URL from the parsed values: `webhook: (env: Env) => env.WEBHOOK_DISCORD_ALERTS`.\n */\n env?: core.$ZodType<object>;\n /** 'enforce' (default) answers an event or patch the contract refuses with a 400; 'report' only logs it. */\n contractMode?: 'enforce' | 'report';\n}\n\n/** The host's environment failed its schema (`env` option). */\nexport class EnvValidationError extends Error {\n override readonly name = 'EnvValidationError';\n constructor(readonly issues: readonly string[]) {\n super(`the host's environment is invalid:\\n ${issues.join('\\n ')}`);\n }\n}\n\nexport interface JourneyHost<Env extends JourneyEnv> {\n config: JourneyConfig;\n /** The env, parsed by the schema once per env object (throws EnvValidationError). */\n checkEnv(env: Env): Env;\n /** A store for one request or run, its segment windows scaled with the runtime. */\n lease(env: Env): Required<StoreLease>;\n /** The bundle compiled into this code. */\n bundle(): BundleIR;\n /** The outlets one run is wired to (the store is the run's). */\n runParts(env: Env, store: JourneyStore, params: JourneyParams): JourneyRunParts;\n /** The HTTP API over one store: tracking, sweep, bundle, preview, then the ingest router. */\n handle(request: Request, env: Env, store: JourneyStore): Promise<Response>;\n /** The scheduled sweep (`sweepSegments`) on a store of its own. */\n sweep(env: Env): Promise<SweepResult>;\n /**\n * Make the bundle compiled into `version` live, once per process, only over an older live\n * version (the store records it). Undefined when there is nothing to do; a failure is logged\n * and retried a minute later.\n */\n applyOwnBundle(env: Env, version: BundleVersion | undefined): Promise<void> | undefined;\n}\n\n/** What the platform adapter itself contributes. */\nexport interface JourneyPlatform {\n /** An HTTP/2 fetch for APNs, where the runtime's own fetch is HTTP/1.1 (Node). */\n apnsFetch?: typeof fetch;\n}\n\nfunction sendsEmail(nodes: readonly NodeIR[]): boolean {\n return nodes.some((node) => {\n switch (node.type) {\n case 'message':\n return node.channel === 'email';\n case 'wait_until':\n return Array.isArray(node.onTimeout) && sendsEmail(node.onTimeout);\n case 'branch':\n return (\n node.cases.some((branch) => sendsEmail(branch.flow)) || sendsEmail(node.otherwise ?? [])\n );\n case 'cohort':\n return node.arms.some((arm) => sendsEmail(arm.flow));\n default:\n return false;\n }\n });\n}\n\nexport function createJourneyHost<Env extends JourneyEnv>(\n options: JourneyHostOptions<Env>,\n platform: JourneyPlatform = {}\n): JourneyHost<Env> {\n const { config } = options;\n const emailIds = indexTemplates('email', config.templates?.email);\n // A config still on `emails` (its sender would be silently dropped) fails here, not at a send\n assertEmailConfig(config, emailIds.values());\n // A journey that emails with nowhere to send fails here too, not at its first email\n if (options.email === undefined && options.messages === undefined) {\n const emailing = compileConfig(config).workflows.filter((workflow) =>\n sendsEmail(workflow.flow)\n );\n if (emailing.length > 0) {\n throw new TypeError(\n `workflows ${emailing.map((w) => `'${w.id}'`).join(', ')} send email, but the host has no ` +\n '`email` transport: pass `email: (env) => cloudflareEmailTransport(...)` or `sesEmailTransport(...)`'\n );\n }\n }\n // Parsed once per env object: the runtime hands the same one to every request of an isolate\n const checked = new WeakMap<object, Env>();\n const checkEnv = (env: Env): Env => {\n if (options.env === undefined) return env;\n const cached = checked.get(env);\n if (cached !== undefined) return cached;\n const result = z.safeParse(options.env, env);\n if (!result.success) {\n // Names and reasons only: the values are secrets\n throw new EnvValidationError(\n result.error.issues.map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)\n );\n }\n const merged: Env = { ...env, ...result.data };\n checked.set(env, merged);\n return merged;\n };\n let compiled: BundleIR | undefined;\n const bundle = () => (compiled ??= compileConfig(config));\n const emails = config.templates?.email;\n const database = { schema: config.database?.schema ?? DEFAULT_SCHEMA };\n // In fast-forward, segment windows scale with the journeys reading them (time-scale.ts)\n const lease = (env: Env): Required<StoreLease> => {\n const opened = options.store === undefined ? d1Store(env) : options.store(env, database);\n const noop = async () => {};\n const factor = runtimeFromConfig(config, env).timeScale;\n return 'store' in opened\n ? { store: scaleSegmentWindows(opened.store, factor), close: opened.close ?? noop }\n : { store: scaleSegmentWindows(opened, factor), close: noop };\n };\n\n const messages = (env: Env, store: JourneyStore): MessageSender => {\n if (options.messages !== undefined) return options.messages(env, store);\n return channelsFromConfig(config, env, {\n store,\n email: options.email?.(env),\n apnsFetch: platform.apnsFetch,\n });\n };\n\n const observer = (env: Env, store: JourneyStore): JourneyObserver | undefined => {\n if (options.observer !== undefined) return options.observer(env, store);\n return store.reporting === undefined\n ? undefined\n : reportingObserver(store.reporting, env.WORKFLOW_ORIGIN);\n };\n\n const runParts = (env: Env, store: JourneyStore, params: JourneyParams): JourneyRunParts => ({\n store,\n env,\n runtime:\n options.runtime === undefined ? runtimeFromConfig(config, env) : options.runtime(env, params),\n messages: messages(env, store),\n // An action ref is a registered action structurally: the same object carries name, code and hash\n actions: new RegistryActionInvoker(config.actions ?? []),\n contract: config.contract,\n validator: registryValidator(config.templates ?? {}),\n observer: observer(env, store),\n });\n\n const json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n\n const authorized = (request: Request, env: Env): boolean =>\n env.API_TOKEN === undefined ||\n request.headers.get('authorization') === `Bearer ${env.API_TOKEN}`;\n\n const preview = emails === undefined ? undefined : registryRenderer(emails, config.email);\n\n const handle = async (request: Request, env: Env, store: JourneyStore): Promise<Response> => {\n const url = new URL(request.url);\n // Opened by recipients, so no bearer: the routes only record, and redirect to recorded URLs\n if (url.pathname.startsWith('/t/') && store.reporting !== undefined) {\n const openedEvent = config.webPush?.openedEvent;\n const tracked = await handleTracking(request, store.reporting, {\n legacyUnsubscribeUrl: config.email?.unsubscribeUrl,\n product: config.title,\n quickMs: config.email?.tracking?.quickClickMs,\n pushOpened:\n openedEvent === undefined\n ? undefined\n : async ({ messageId, userId, at }) => {\n const payload: Record<string, unknown> = { message_id: messageId };\n const contract = config.contract;\n const verdict =\n contract === undefined ? undefined : checkEvent(contract, openedEvent, payload);\n if (verdict !== undefined && !verdict.ok) {\n throw new ContractValidationError(openedEvent, verdict.issues);\n }\n // Keyed by the copy: a second tap of the same notification is the same event\n await ingestEvent(\n env,\n {\n id: `${openedEvent}:${messageId}`,\n userId,\n event: openedEvent,\n payload: verdict?.data ?? payload,\n ts: at,\n },\n store\n );\n },\n });\n if (tracked !== undefined) return tracked;\n }\n if (url.pathname === '/segments/sweep') {\n if (!authorized(request, env)) return json({ error: 'unauthorized' }, 401);\n if (request.method !== 'POST') return json({ error: 'method not allowed' }, 405);\n return json(await sweepSegments(env, store));\n }\n if (url.pathname === '/bundle') {\n if (!authorized(request, env)) return json({ error: 'unauthorized' }, 401);\n if (request.method !== 'GET') return json({ error: 'method not allowed' }, 405);\n return json(bundle());\n }\n if (url.pathname === '/bundle/deploy') {\n if (!authorized(request, env)) return json({ error: 'unauthorized' }, 401);\n if (request.method !== 'POST') return json({ error: 'method not allowed' }, 405);\n try {\n return json(await deployBundle(env, bundle(), store));\n } catch (error) {\n if (!(error instanceof SchemaMismatchError)) throw error;\n return json({ error: error.message, problems: error.problems }, 503);\n }\n }\n if (emails !== undefined && preview !== undefined && url.pathname.startsWith('/preview/')) {\n if (!authorized(request, env)) return json({ error: 'unauthorized' }, 401);\n if (request.method !== 'GET') return json({ error: 'method not allowed' }, 405);\n const key = url.pathname.slice('/preview/'.length);\n if (!emailIds.has(key)) return json({ error: `unknown email template: ${key}` }, 404);\n // `?props=<JSON object>`: JSON keeps numbers and booleans typed, which query strings cannot\n let props: unknown = {};\n try {\n props = JSON.parse(url.searchParams.get('props') ?? '{}');\n } catch {\n return json({ error: 'props must be a JSON object' }, 400);\n }\n if (typeof props !== 'object' || props === null || Array.isArray(props)) {\n return json({ error: 'props must be a JSON object' }, 400);\n }\n try {\n const { subject, html } = await preview(key, props as Record<string, ScalarIR>);\n return new Response(html, {\n headers: { 'content-type': 'text/html; charset=utf-8', 'x-subject': subject },\n });\n } catch (error) {\n // The query string is the props: a refusal is the caller's to fix, with the field paths\n if (error instanceof TemplateValidationError) {\n return json({ error: error.message, issues: error.issues }, 400);\n }\n throw error;\n }\n }\n return handleRequest(request, env, store, {\n contract: config.contract,\n mode: options.contractMode,\n });\n };\n\n const sweep = async (env: Env) => {\n const { store, close } = lease(env);\n try {\n return await sweepSegments(env, store);\n } finally {\n await close();\n }\n };\n\n // The bundle compiled into this version goes live on its own, once per process: the first\n // request or scheduled run reads which version's bundle is live (one row) and applies this one\n // only over an older version, so one still serving during a rollout can never put its routes\n // back. A failure (say the migrations have not run) is logged and retried a minute later. Only\n // the request that starts the check gets its promise back: a request context cannot wait on\n // another's I/O.\n let applying: Promise<void> | undefined;\n let retryAt = 0;\n const applyOwnBundle = (env: Env, version: BundleVersion | undefined) => {\n if (version === undefined || version.id === '' || Number.isNaN(version.createdAt)) {\n return undefined;\n }\n if (applying !== undefined || Date.now() < retryAt) return undefined;\n applying = (async () => {\n const { store, close } = lease(env);\n try {\n if (store.liveBundleVersion === undefined) return; // D1: POST /bundle/deploy\n const live = await store.liveBundleVersion();\n if (live !== undefined && (live.id === version.id || live.createdAt >= version.createdAt))\n return;\n const result = await deployBundle(env, bundle(), store, version);\n if (result.applied) console.log(`[workflow] version ${version.id} is live`);\n } finally {\n await close();\n }\n })().catch((error: unknown) => {\n applying = undefined;\n retryAt = Date.now() + 60_000;\n console.error(`[workflow] could not make version ${version.id} live`, error);\n });\n return applying;\n };\n\n return { config, checkEnv, lease, bundle, runParts, handle, sweep, applyOwnBundle };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8FA,IAAa,qBAAb,cAAwC,MAAM;CAEvB;CADrB,OAAyB;CACzB,YAAY,QAAoC;EAC9C,MAAM,yCAAyC,OAAO,KAAK,MAAM,GAAG;EADjD,KAAA,SAAA;CAErB;AACF;AA8BA,SAAS,WAAW,OAAmC;CACrD,OAAO,MAAM,MAAM,SAAS;EAC1B,QAAQ,KAAK,MAAb;GACE,KAAK,WACH,OAAO,KAAK,YAAY;GAC1B,KAAK,cACH,OAAO,MAAM,QAAQ,KAAK,SAAS,KAAK,WAAW,KAAK,SAAS;GACnE,KAAK,UACH,OACE,KAAK,MAAM,MAAM,WAAW,WAAW,OAAO,IAAI,CAAC,KAAK,WAAW,KAAK,aAAa,CAAC,CAAC;GAE3F,KAAK,UACH,OAAO,KAAK,KAAK,MAAM,QAAQ,WAAW,IAAI,IAAI,CAAC;GACrD,SACE,OAAO;EACX;CACF,CAAC;AACH;AAEA,SAAgB,kBACd,SACA,WAA4B,CAAC,GACX;CAClB,MAAM,EAAE,WAAW;CACnB,MAAM,WAAW,eAAe,SAAS,OAAO,WAAW,KAAK;CAEhE,kBAAkB,QAAQ,SAAS,OAAO,CAAC;CAE3C,IAAI,QAAQ,UAAU,KAAA,KAAa,QAAQ,aAAa,KAAA,GAAW;EACjE,MAAM,WAAW,cAAc,MAAM,CAAC,CAAC,UAAU,QAAQ,aACvD,WAAW,SAAS,IAAI,CAC1B;EACA,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,UACR,aAAa,SAAS,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F;CAQA,IAAI;CACJ,IAAI,UAAU;CACd,MAAM,kBAAkB,KAAU,YAAuC;EACvE,IAAI,YAAY,KAAA,KAAa,QAAQ,OAAO,MAAM,OAAO,MAAM,QAAQ,SAAS,GAC9E;EAEF,IAAI,aAAa,KAAA,KAAa,KAAK,IAAI,IAAI,SAAS,OAAO,KAAA;EAC3D,YAAY,YAAY;GACtB,MAAM,EAAE,OAAO,UAAU,MAAM,GAAG;GAClC,IAAI;IACF,IAAI,MAAM,sBAAsB,KAAA,GAAW;IAC3C,MAAM,OAAO,MAAM,MAAM,kBAAkB;IAC3C,IAAI,SAAS,KAAA,MAAc,KAAK,OAAO,QAAQ,MAAM,KAAK,aAAa,QAAQ,YAC7E;IAEF,KAAI,MADiB,aAAa,KAAK,OAAO,GAAG,OAAO,OAAO,EAAA,CACpD,SAAS,QAAQ,IAAI,sBAAsB,QAAQ,GAAG,SAAS;GAC5E,UAAU;IACR,MAAM,MAAM;GACd;EACF,EAAA,CAAG,CAAC,CAAC,OAAO,UAAmB;GAC7B,WAAW,KAAA;GACX,UAAU,KAAK,IAAI,IAAI;GACvB,QAAQ,MAAM,qCAAqC,QAAQ,GAAG,QAAQ,KAAK;EAC7E,CAAC;EACD,OAAO;CACT;CAEA,OAAO;EAAE;EAAQ;EAAU;EAAO;EAAQ;EAAU;EAAQ;EAAO;CAAe;AACpF"}
1
+ {"version":3,"file":"journey-host.mjs","names":[],"sources":["../../src/host/journey-host.ts"],"sourcesContent":["import * as z from 'zod/mini';\nimport type * as core from 'zod/v4/core';\nimport { d1Store } from '../cloudflare/d1-env';\nimport { type JourneyConfig, compileConfig } from '../config';\nimport { type Contract, ContractValidationError, checkEvent } from '../contract';\nimport { assertEmailConfig } from '../email';\nimport type { EmailTransport } from '../email-sender';\nimport { RegistryActionInvoker } from '../engine/actions';\nimport { profileUpdatedEvent } from '../engine/condition';\nimport type { JourneyObserver, MessageSender } from '../engine/ports';\nimport { RECIPIENT_PROPERTY } from '../engine/recipient';\nimport { scaleSegmentWindows } from '../engine/time-scale';\nimport type { BundleIR, NodeIR } from '../ir';\nimport { registryRenderer } from '../react-email';\nimport { reportingObserver } from '../reporting/observer';\nimport type { TrackingOptions } from '../reporting/tracking';\nimport type { JourneyRuntimeOptions } from '../runtime';\nimport type { BundleVersion, JourneyStore, StoreLease } from '../store/index';\nimport { DEFAULT_SCHEMA } from '../store/tables';\nimport { indexTemplates, registryValidator } from '../templates';\nimport { channelsFromConfig, createProviderCache, runtimeFromConfig } from './channels';\nimport type { JourneyRunParts } from './execute';\nimport { serve } from './http';\nimport {\n type SweepResult,\n deployBundle,\n ingestEvent,\n sweepSegments,\n wakeSubscribers,\n} from './ingest';\nimport type { JourneyEnv, JourneyParams } from './platform';\n\n/**\n * What a journey host is, apart from the runtime it runs on: the validated environment, the\n * store lease, the outlets a run is wired to, the HTTP API (`http.ts`, with the host's parts\n * plugged in) and the bundle that goes live with the code. `journeyWorker` (Cloudflare) and\n * `journeyLambda` (AWS) are this plus how their platform starts, wakes and stops instances.\n */\n\nexport interface JourneyHostOptions<Env extends JourneyEnv> {\n /**\n * The project's `workflow.config.ts` (`defineConfig`): what the host deploys (`GET /bundle`,\n * `POST /bundle/deploy` serve `compileConfig`), the template registries the senders, the\n * validator and `/preview` render from, the contract every `/events` and `/identify` is\n * checked against, the email defaults, actions, and the runtime / APNs / FCM settings.\n * Secrets come from the env under the names `JourneyEnv` documents.\n */\n config: JourneyConfig;\n /**\n * The data plane, opened per request and per workflow run. Return a `StoreLease` when the\n * client must be released afterwards (a Postgres connection); defaults to D1 from the env's\n * binding. `database` is the config's (`schema` defaulting to `workflow`), for Postgres:\n *\n * store: (env, database) => postgresJsStore(env.DATABASE_URL, database)\n */\n store?: (env: Env, database: { schema: string }) => JourneyStore | StoreLease;\n /**\n * Where journey emails go: a transport built from the validated env — `sesEmailTransport(...)`,\n * `cloudflareEmailTransport(...)`, or your own. Which one is independent of where the workflow\n * runs. Without it the email channel fails its sends, saying so.\n */\n email?: (env: Env) => EmailTransport;\n /**\n * Reporting hooks: node arrivals, every copy sent (with the tracking it should carry — click\n * links and an open pixel for email, payload data for a push), and how each instance ended.\n * By default a store that keeps reporting (Postgres) records them itself, and the host serves\n * the email tracking routes (`/t/...`, on `WORKFLOW_ORIGIN`); override to report elsewhere.\n */\n observer?: (env: Env, store: JourneyStore) => JourneyObserver;\n /** Message outlet override (tests, a custom gateway): replaces every channel, `email` included. */\n messages?: (env: Env, store: JourneyStore) => MessageSender;\n /** Per-instance runtime options override (a tester in fast-forward); by default `config.runtime` for `ENVIRONMENT`. */\n runtime?: (env: Env, params: JourneyParams) => JourneyRuntimeOptions;\n /**\n * The host's environment, as a zod schema over its vars and secrets (bindings pass through\n * untouched): checked the first time the host runs, so a missing or malformed variable fails\n * there — every problem listed — not at the send that needs it. Webhook templates read their\n * URL from the parsed values: `webhook: (env: Env) => env.WEBHOOK_DISCORD_ALERTS`.\n */\n env?: core.$ZodType<object>;\n /** 'enforce' (default) answers an event or patch the contract refuses with a 400; 'report' only logs it. */\n contractMode?: 'enforce' | 'report';\n}\n\n/** The host's environment failed its schema (`env` option). */\nexport class EnvValidationError extends Error {\n override readonly name = 'EnvValidationError';\n constructor(readonly issues: readonly string[]) {\n super(`the host's environment is invalid:\\n ${issues.join('\\n ')}`);\n }\n}\n\nexport interface JourneyHost<Env extends JourneyEnv> {\n config: JourneyConfig;\n /** The env, parsed by the schema once per env object (throws EnvValidationError). */\n checkEnv(env: Env): Env;\n /** A store for one request or run, its segment windows scaled with the runtime. */\n lease(env: Env): Required<StoreLease>;\n /** The bundle compiled into this code. */\n bundle(): BundleIR;\n /** The outlets one run is wired to (the store is the run's). */\n runParts(env: Env, store: JourneyStore, params: JourneyParams): JourneyRunParts;\n /** The HTTP API over one store: the ingest API plus tracking, the sweep, the bundle and previews. */\n handle(request: Request, env: Env, store: JourneyStore): Promise<Response>;\n /** The scheduled sweep (`sweepSegments`) on a store of its own. */\n sweep(env: Env): Promise<SweepResult>;\n /**\n * Make the bundle compiled into `version` live, once per process, only over an older live\n * version (the store records it). Undefined when there is nothing to do; a failure is logged\n * and retried a minute later.\n */\n applyOwnBundle(env: Env, version: BundleVersion | undefined): Promise<void> | undefined;\n}\n\n/** What the platform adapter itself contributes. */\nexport interface JourneyPlatform {\n /** An HTTP/2 fetch for APNs, where the runtime's own fetch is HTTP/1.1 (Node). */\n apnsFetch?: typeof fetch;\n}\n\nfunction sendsEmail(nodes: readonly NodeIR[]): boolean {\n return nodes.some((node) => {\n switch (node.type) {\n case 'message':\n return node.channel === 'email';\n case 'wait_until':\n return Array.isArray(node.onTimeout) && sendsEmail(node.onTimeout);\n case 'branch':\n return (\n node.cases.some((branch) => sendsEmail(branch.flow)) || sendsEmail(node.otherwise ?? [])\n );\n case 'cohort':\n return node.arms.some((arm) => sendsEmail(arm.flow));\n default:\n return false;\n }\n });\n}\n\nconst describeIssue = (issue: { path: PropertyKey[]; message: string }): string =>\n `${issue.path.join('.') || '(root)'}: ${issue.message}`;\n\n/** An event the host emits itself, checked against the contract like any ingest. */\nfunction checkedPayload(\n contract: Contract | undefined,\n event: string,\n payload: Record<string, unknown>\n): Record<string, unknown> {\n if (contract === undefined) return payload;\n const verdict = checkEvent(contract, event, payload);\n if (!verdict.ok) throw new ContractValidationError(event, verdict.issues);\n return verdict.data;\n}\n\nexport function createJourneyHost<Env extends JourneyEnv>(\n options: JourneyHostOptions<Env>,\n platform: JourneyPlatform = {}\n): JourneyHost<Env> {\n const { config } = options;\n const emailIds = indexTemplates('email', config.templates?.email);\n // A config still on `emails` (its sender would be silently dropped) fails here, not at a send\n assertEmailConfig(config, emailIds.values());\n let compiled: BundleIR | undefined;\n const bundle = () => (compiled ??= compileConfig(config));\n // A journey that emails with nowhere to send fails here too, not at its first email\n const emailing = bundle().workflows.filter((workflow) => sendsEmail(workflow.flow));\n if (options.email === undefined && options.messages === undefined && emailing.length > 0) {\n throw new TypeError(\n `workflows ${emailing.map((w) => `'${w.id}'`).join(', ')} send email, but the host has no ` +\n '`email` transport: pass `email: (env) => cloudflareEmailTransport(...)` or `sesEmailTransport(...)`'\n );\n }\n // Parsed once per env object: the runtime hands the same one to every request of an isolate\n const checked = new WeakMap<object, Env>();\n const checkEnv = (env: Env): Env => {\n if (options.env === undefined) return env;\n const cached = checked.get(env);\n if (cached !== undefined) return cached;\n const result = z.safeParse(options.env, env);\n // Names and reasons only: the values are secrets\n if (!result.success) throw new EnvValidationError(result.error.issues.map(describeIssue));\n const merged: Env = { ...env, ...result.data };\n checked.set(env, merged);\n return merged;\n };\n const emails = config.templates?.email;\n const database = { schema: config.database?.schema ?? DEFAULT_SCHEMA };\n // In fast-forward, segment windows scale with the journeys reading them (time-scale.ts)\n const lease = (env: Env): Required<StoreLease> => {\n const opened = options.store === undefined ? d1Store(env) : options.store(env, database);\n const noop = async () => {};\n const factor = runtimeFromConfig(config, env).timeScale;\n return 'store' in opened\n ? { store: scaleSegmentWindows(opened.store, factor), close: opened.close ?? noop }\n : { store: scaleSegmentWindows(opened, factor), close: noop };\n };\n\n // The provider clients (APNs JWT, FCM access token) live with the host, not with a run: a\n // run's env is a fresh object on every Lambda invocation, so nothing keyed on it would be reused\n const providers = createProviderCache();\n const messages = (env: Env, store: JourneyStore): MessageSender => {\n if (options.messages !== undefined) return options.messages(env, store);\n return channelsFromConfig(config, env, {\n store,\n email: options.email?.(env),\n apnsFetch: platform.apnsFetch,\n providers,\n });\n };\n\n const observer = (env: Env, store: JourneyStore): JourneyObserver | undefined => {\n if (options.observer !== undefined) return options.observer(env, store);\n return store.reporting === undefined\n ? undefined\n : reportingObserver(store.reporting, env.WORKFLOW_ORIGIN);\n };\n\n const runParts = (env: Env, store: JourneyStore, params: JourneyParams): JourneyRunParts => ({\n store,\n env,\n runtime:\n options.runtime === undefined ? runtimeFromConfig(config, env) : options.runtime(env, params),\n messages: messages(env, store),\n // An action ref is a registered action structurally: the same object carries name, code and hash\n actions: new RegistryActionInvoker(config.actions ?? []),\n contract: config.contract,\n validator: registryValidator(config.templates ?? {}),\n observer: observer(env, store),\n });\n\n const preview = emails === undefined ? undefined : registryRenderer(emails, config.email);\n\n /**\n * The recipients' routes (`/t/*`): a push tapped open is recorded as the config's\n * `webPush.openedEvent` — keyed by the copy, so a second tap of the same notification is the\n * same event — and an unsubscribe wakes the waits reading email reachability (`reachable\n * ('email')` subscribes to the email property's channel), so an `exitWhen:\n * not(reachable('email'))` takes effect without waiting for a timeout.\n */\n const tracking = (env: Env, store: JourneyStore): TrackingOptions => {\n const opened = config.webPush?.openedEvent;\n return {\n product: config.title,\n quickMs: config.email?.tracking?.quickClickMs,\n pushOpened:\n opened === undefined\n ? undefined\n : async ({ messageId, userId, at }) => {\n const payload = checkedPayload(config.contract, opened, { message_id: messageId });\n const input = {\n id: `${opened}:${messageId}`,\n userId,\n event: opened,\n payload,\n ts: at,\n };\n await ingestEvent(env, input, store);\n },\n onUnsubscribed: async ({ userId }) => {\n const email = profileUpdatedEvent(RECIPIENT_PROPERTY.email ?? 'email');\n await wakeSubscribers(env, store, userId, [email]);\n },\n };\n };\n\n const handle = (request: Request, env: Env, store: JourneyStore): Promise<Response> =>\n serve(request, {\n env,\n store,\n validation: { contract: config.contract, mode: options.contractMode },\n host: {\n bundle,\n preview:\n preview === undefined ? undefined : { has: (id) => emailIds.has(id), render: preview },\n tracking: tracking(env, store),\n sweep: () => sweepSegments(env, store),\n },\n });\n\n const sweep = async (env: Env) => {\n const { store, close } = lease(env);\n try {\n return await sweepSegments(env, store);\n } finally {\n await close();\n }\n };\n\n // The bundle compiled into this version goes live on its own, once per process: the first\n // request or scheduled run reads which version's bundle is live (one row) and applies this one\n // only over an older version, so one still serving during a rollout can never put its routes\n // back. A failure (say the migrations have not run) is logged and retried a minute later. Only\n // the request that starts the check gets its promise back: a request context cannot wait on\n // another's I/O.\n let applying: Promise<void> | undefined;\n let retryAt = 0;\n const applyOwnBundle = (env: Env, version: BundleVersion | undefined) => {\n if (version === undefined || version.id === '' || Number.isNaN(version.createdAt)) {\n return undefined;\n }\n if (applying !== undefined || Date.now() < retryAt) return undefined;\n applying = (async () => {\n const { store, close } = lease(env);\n try {\n if (store.liveBundleVersion === undefined) return; // D1: POST /bundle/deploy\n const live = await store.liveBundleVersion();\n if (live !== undefined && (live.id === version.id || live.createdAt >= version.createdAt))\n return;\n const result = await deployBundle(env, bundle(), store, version);\n if (result.applied) console.log(`[workflow] version ${version.id} is live`);\n } finally {\n await close();\n }\n })().catch((error: unknown) => {\n applying = undefined;\n retryAt = Date.now() + 60_000;\n console.error(`[workflow] could not make version ${version.id} live`, error);\n });\n return applying;\n };\n\n return { config, checkEnv, lease, bundle, runParts, handle, sweep, applyOwnBundle };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqFA,IAAa,qBAAb,cAAwC,MAAM;CAEvB;CADrB,OAAyB;CACzB,YAAY,QAAoC;EAC9C,MAAM,yCAAyC,OAAO,KAAK,MAAM,GAAG;EADjD,KAAA,SAAA;CAErB;AACF;AA8BA,SAAS,WAAW,OAAmC;CACrD,OAAO,MAAM,MAAM,SAAS;EAC1B,QAAQ,KAAK,MAAb;GACE,KAAK,WACH,OAAO,KAAK,YAAY;GAC1B,KAAK,cACH,OAAO,MAAM,QAAQ,KAAK,SAAS,KAAK,WAAW,KAAK,SAAS;GACnE,KAAK,UACH,OACE,KAAK,MAAM,MAAM,WAAW,WAAW,OAAO,IAAI,CAAC,KAAK,WAAW,KAAK,aAAa,CAAC,CAAC;GAE3F,KAAK,UACH,OAAO,KAAK,KAAK,MAAM,QAAQ,WAAW,IAAI,IAAI,CAAC;GACrD,SACE,OAAO;EACX;CACF,CAAC;AACH;AAEA,MAAM,iBAAiB,UACrB,GAAG,MAAM,KAAK,KAAK,GAAG,KAAK,SAAS,IAAI,MAAM;;AAGhD,SAAS,eACP,UACA,OACA,SACyB;CACzB,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,MAAM,UAAU,WAAW,UAAU,OAAO,OAAO;CACnD,IAAI,CAAC,QAAQ,IAAI,MAAM,IAAI,wBAA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G,OAAO,OAAO,EAAA,CACpD,SAAS,QAAQ,IAAI,sBAAsB,QAAQ,GAAG,SAAS;GAC5E,UAAU;IACR,MAAM,MAAM;GACd;EACF,EAAA,CAAG,CAAC,CAAC,OAAO,UAAmB;GAC7B,WAAW,KAAA;GACX,UAAU,KAAK,IAAI,IAAI;GACvB,QAAQ,MAAM,qCAAqC,QAAQ,GAAG,QAAQ,KAAK;EAC7E,CAAC;EACD,OAAO;CACT;CAEA,OAAO;EAAE;EAAQ;EAAU;EAAO;EAAQ;EAAU;EAAQ;EAAO;CAAe;AACpF"}
@@ -0,0 +1,21 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/host/platform.ts
3
+ /**
4
+ * The runtime does not know the instance: the only lookup failure that lets the host drop the
5
+ * instance's wakes, or count it as stopped. Every `WorkflowBindingLike.get` answers it this way.
6
+ */
7
+ var InstanceNotFoundError = class extends Error {
8
+ instanceId;
9
+ name = "InstanceNotFoundError";
10
+ constructor(instanceId, options) {
11
+ super(`no such instance: ${instanceId}`, options);
12
+ this.instanceId = instanceId;
13
+ }
14
+ };
15
+ /** The event type the host uses to wake waiting instances (sendEvent's `type`). */
16
+ const WAKE_EVENT_TYPE = "wake";
17
+ //#endregion
18
+ exports.InstanceNotFoundError = InstanceNotFoundError;
19
+ exports.WAKE_EVENT_TYPE = WAKE_EVENT_TYPE;
20
+
21
+ //# sourceMappingURL=platform.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platform.cjs","names":[],"sources":["../../src/host/platform.ts"],"sourcesContent":["import type { D1DatabaseLike, EmailBindingLike } from '../cloudflare/bindings';\nimport type { ExecutionStart } from '../store/index';\n\n/**\n * The runtime port: what the host needs from the platform it runs on, whichever one that is.\n * Cloudflare's Workflow binding satisfies it (`cloudflareJourneyBinding`), the AWS adapter's\n * `AwsInstances` implements it over durable executions.\n */\n\nexport interface WorkflowInstanceLike {\n id: string;\n sendEvent(event: { type: string; payload?: unknown }): Promise<void>;\n /** Stop the instance for good (Cloudflare Workflows' `terminate`). */\n terminate?(): Promise<void>;\n /** Where it stands (`complete`, `errored`, `terminated`, `running`, …). */\n status?(): Promise<{ status: string }>;\n}\n\n/** How the host starts, wakes and stops instances. */\nexport interface WorkflowBindingLike {\n create(options: { id: string; params: unknown }): Promise<WorkflowInstanceLike>;\n /** The instance, or an `InstanceNotFoundError` when the runtime does not know the id. */\n get(id: string): Promise<WorkflowInstanceLike>;\n /**\n * For a runtime whose start is a submit that can be lost in flight (AWS): the start to record\n * with the entry, in one transaction. A failed `create` then keeps the entry — its recorded\n * start is retried by the next ingest for the pair (`resume`) or by maintenance, never rolled\n * back and re-entered as a second execution.\n */\n plan?(options: {\n id: string;\n params: JourneyParams;\n ts: number;\n /** The code version whose routes named `params.contentHash` (absent after a forced deploy). */\n version?: string | undefined;\n }): Promise<ExecutionStart>;\n /** Retry the recorded, unconfirmed start of the (workflow, user) entry still running, if any. */\n resume?(entry: { workflow: string; userId: string }): Promise<void>;\n /**\n * Maintenance the sweep runs first: old unconfirmed starts retried (or given up on), and\n * executions the platform ended on its own (timeout, stop, crash) reconciled into the ledger.\n */\n maintain?(): Promise<void>;\n}\n\n/**\n * The runtime does not know the instance: the only lookup failure that lets the host drop the\n * instance's wakes, or count it as stopped. Every `WorkflowBindingLike.get` answers it this way.\n */\nexport class InstanceNotFoundError extends Error {\n override readonly name = 'InstanceNotFoundError';\n constructor(\n readonly instanceId: string,\n options?: ErrorOptions\n ) {\n super(`no such instance: ${instanceId}`, options);\n }\n}\n\n/** The event type the host uses to wake waiting instances (sendEvent's `type`). */\nexport const WAKE_EVENT_TYPE = 'wake';\n\n/** Journey instance parameters, passed by the host when it creates one. */\nexport interface JourneyParams {\n workflowId: string;\n /** The IR version pinned at entry. */\n contentHash: string;\n userId: string;\n trigger: { event: string; payload: Record<string, unknown> };\n [key: string]: unknown;\n}\n\n/** Every binding, variable and secret the journey host reads (names match the wrangler config). */\nexport interface JourneyEnv {\n /**\n * The default D1 store's database (events / profiles / segments / triggers / entries /\n * subscriptions / workflow IR). Optional: a host on another JourneyStore (Postgres, say)\n * does not declare it.\n */\n DB?: D1DatabaseLike;\n /** The runtime port: creating instances, waking and stopping them. */\n JOURNEY: WorkflowBindingLike;\n /** Optional message-delivery webhook (defaults to the console logging sender). */\n MESSAGE_WEBHOOK_URL?: string;\n /**\n * Bearer token required on every mutating HTTP endpoint (`Authorization:\n * Bearer <token>`). Unset = open — acceptable only for local dev; /deploy in\n * particular rewrites the whole routing table, so production must set this.\n */\n API_TOKEN?: string;\n /**\n * The host's public origin. With a store that keeps reporting (Postgres), journey emails'\n * links and open pixel point at its `/t/...` routes; without it emails go out untracked.\n */\n WORKFLOW_ORIGIN?: string;\n /** Which `workflow.config.ts` entry applies (`development`, `production`, …); production when unset. */\n ENVIRONMENT?: string;\n /** Cloudflare Email Sending, when the config has `emails`. */\n EMAIL?: EmailBindingLike;\n /** The APNs auth key (`.p8`, base64) named by the config's `apns.keyId`. */\n APNS_PRIVATE_KEY_BASE64?: string;\n /** The Firebase service account (base64 JSON) the config's `fcm` sends with. */\n GOOGLE_APPLICATION_CREDENTIALS_BASE64?: string;\n /** The VAPID key pair web pushes are signed with (`generateVapidKeys`); the config's `webPush` turns the channel on. */\n VAPID_PUBLIC_KEY?: string;\n VAPID_PRIVATE_KEY?: string;\n /**\n * Cloudflare's version metadata binding (wrangler `\"version_metadata\": { \"binding\":\n * \"CF_VERSION_METADATA\" }`). With it, and a store that records the live version (Postgres),\n * journeyWorker makes the bundle compiled into each new version live by itself: `wrangler\n * deploy` is the whole deploy.\n */\n CF_VERSION_METADATA?: { id: string; tag?: string; timestamp: string };\n /** Development only: the HTTP/2 relay `wrangler dev` sends APNs requests through (see `@shware/workflow/apns-relay`). */\n APNS_RELAY_ORIGIN?: string;\n}\n"],"mappings":";;;;;;AAiDA,IAAa,wBAAb,cAA2C,MAAM;CAGpC;CAFX,OAAyB;CACzB,YACE,YACA,SACA;EACA,MAAM,qBAAqB,cAAc,OAAO;EAHvC,KAAA,aAAA;CAIX;AACF;;AAGA,MAAa,kBAAkB"}
@@ -0,0 +1,126 @@
1
+ import { D1DatabaseLike, EmailBindingLike } from "../cloudflare/bindings.cjs";
2
+ import { ExecutionStart } from "../store/index.cjs";
3
+ //#region src/host/platform.d.ts
4
+ /**
5
+ * The runtime port: what the host needs from the platform it runs on, whichever one that is.
6
+ * Cloudflare's Workflow binding satisfies it (`cloudflareJourneyBinding`), the AWS adapter's
7
+ * `AwsInstances` implements it over durable executions.
8
+ */
9
+ export interface WorkflowInstanceLike {
10
+ id: string;
11
+ sendEvent(event: {
12
+ type: string;
13
+ payload?: unknown;
14
+ }): Promise<void>;
15
+ /** Stop the instance for good (Cloudflare Workflows' `terminate`). */
16
+ terminate?(): Promise<void>;
17
+ /** Where it stands (`complete`, `errored`, `terminated`, `running`, …). */
18
+ status?(): Promise<{
19
+ status: string;
20
+ }>;
21
+ }
22
+ /** How the host starts, wakes and stops instances. */
23
+ export interface WorkflowBindingLike {
24
+ create(options: {
25
+ id: string;
26
+ params: unknown;
27
+ }): Promise<WorkflowInstanceLike>;
28
+ /** The instance, or an `InstanceNotFoundError` when the runtime does not know the id. */
29
+ get(id: string): Promise<WorkflowInstanceLike>;
30
+ /**
31
+ * For a runtime whose start is a submit that can be lost in flight (AWS): the start to record
32
+ * with the entry, in one transaction. A failed `create` then keeps the entry — its recorded
33
+ * start is retried by the next ingest for the pair (`resume`) or by maintenance, never rolled
34
+ * back and re-entered as a second execution.
35
+ */
36
+ plan?(options: {
37
+ id: string;
38
+ params: JourneyParams;
39
+ ts: number;
40
+ /** The code version whose routes named `params.contentHash` (absent after a forced deploy). */
41
+ version?: string | undefined;
42
+ }): Promise<ExecutionStart>;
43
+ /** Retry the recorded, unconfirmed start of the (workflow, user) entry still running, if any. */
44
+ resume?(entry: {
45
+ workflow: string;
46
+ userId: string;
47
+ }): Promise<void>;
48
+ /**
49
+ * Maintenance the sweep runs first: old unconfirmed starts retried (or given up on), and
50
+ * executions the platform ended on its own (timeout, stop, crash) reconciled into the ledger.
51
+ */
52
+ maintain?(): Promise<void>;
53
+ }
54
+ /**
55
+ * The runtime does not know the instance: the only lookup failure that lets the host drop the
56
+ * instance's wakes, or count it as stopped. Every `WorkflowBindingLike.get` answers it this way.
57
+ */
58
+ export declare class InstanceNotFoundError extends Error {
59
+ readonly instanceId: string;
60
+ readonly name = "InstanceNotFoundError";
61
+ constructor(instanceId: string, options?: ErrorOptions);
62
+ }
63
+ /** The event type the host uses to wake waiting instances (sendEvent's `type`). */
64
+ export declare const WAKE_EVENT_TYPE = "wake";
65
+ /** Journey instance parameters, passed by the host when it creates one. */
66
+ export interface JourneyParams {
67
+ workflowId: string;
68
+ /** The IR version pinned at entry. */
69
+ contentHash: string;
70
+ userId: string;
71
+ trigger: {
72
+ event: string;
73
+ payload: Record<string, unknown>;
74
+ };
75
+ [key: string]: unknown;
76
+ }
77
+ /** Every binding, variable and secret the journey host reads (names match the wrangler config). */
78
+ export interface JourneyEnv {
79
+ /**
80
+ * The default D1 store's database (events / profiles / segments / triggers / entries /
81
+ * subscriptions / workflow IR). Optional: a host on another JourneyStore (Postgres, say)
82
+ * does not declare it.
83
+ */
84
+ DB?: D1DatabaseLike;
85
+ /** The runtime port: creating instances, waking and stopping them. */
86
+ JOURNEY: WorkflowBindingLike;
87
+ /** Optional message-delivery webhook (defaults to the console logging sender). */
88
+ MESSAGE_WEBHOOK_URL?: string;
89
+ /**
90
+ * Bearer token required on every mutating HTTP endpoint (`Authorization:
91
+ * Bearer <token>`). Unset = open — acceptable only for local dev; /deploy in
92
+ * particular rewrites the whole routing table, so production must set this.
93
+ */
94
+ API_TOKEN?: string;
95
+ /**
96
+ * The host's public origin. With a store that keeps reporting (Postgres), journey emails'
97
+ * links and open pixel point at its `/t/...` routes; without it emails go out untracked.
98
+ */
99
+ WORKFLOW_ORIGIN?: string;
100
+ /** Which `workflow.config.ts` entry applies (`development`, `production`, …); production when unset. */
101
+ ENVIRONMENT?: string;
102
+ /** Cloudflare Email Sending, when the config has `emails`. */
103
+ EMAIL?: EmailBindingLike;
104
+ /** The APNs auth key (`.p8`, base64) named by the config's `apns.keyId`. */
105
+ APNS_PRIVATE_KEY_BASE64?: string;
106
+ /** The Firebase service account (base64 JSON) the config's `fcm` sends with. */
107
+ GOOGLE_APPLICATION_CREDENTIALS_BASE64?: string;
108
+ /** The VAPID key pair web pushes are signed with (`generateVapidKeys`); the config's `webPush` turns the channel on. */
109
+ VAPID_PUBLIC_KEY?: string;
110
+ VAPID_PRIVATE_KEY?: string;
111
+ /**
112
+ * Cloudflare's version metadata binding (wrangler `"version_metadata": { "binding":
113
+ * "CF_VERSION_METADATA" }`). With it, and a store that records the live version (Postgres),
114
+ * journeyWorker makes the bundle compiled into each new version live by itself: `wrangler
115
+ * deploy` is the whole deploy.
116
+ */
117
+ CF_VERSION_METADATA?: {
118
+ id: string;
119
+ tag?: string;
120
+ timestamp: string;
121
+ };
122
+ /** Development only: the HTTP/2 relay `wrangler dev` sends APNs requests through (see `@shware/workflow/apns-relay`). */
123
+ APNS_RELAY_ORIGIN?: string;
124
+ }
125
+ //#endregion
126
+ //# sourceMappingURL=platform.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platform.d.cts","names":[],"sources":["../../src/host/platform.ts"],"mappings":";;;;;;;;iBASiB;EACf;EACA,UAAU;IAAS;IAAc;MAAsB;;EAEvD,cAAc;;EAEd,WAAW;IAAU;;;;iBAIN;EACf,OAAO;IAAW;IAAY;MAAoB,QAAQ;;EAE1D,IAAI,aAAa,QAAQ;;;;;;;EAOzB,MAAM;IACJ;IACA,QAAQ;IACR;;IAEA;MACE,QAAQ;;EAEZ,QAAQ;IAAS;IAAkB;MAAmB;;;;;EAKtD,aAAa;;;;;;qBAOF,8BAA8B;WAG9B;WAFO;EAClB,YACW,oBACT,UAAU;;;qBAOD;;iBAGI;EACf;;EAEA;EACA;EACA;IAAW;IAAe,SAAS;;GAClC;;;iBAIc;;;;;;EAMf,KAAK;;EAEL,SAAS;;EAET;;;;;;EAMA;;;;;EAKA;;EAEA;;EAEA,QAAQ;;EAER;;EAEA;;EAEA;EACA;;;;;;;EAOA;IAAwB;IAAY;IAAc;;;EAElD"}
@@ -0,0 +1,126 @@
1
+ import { D1DatabaseLike, EmailBindingLike } from "../cloudflare/bindings.mjs";
2
+ import { ExecutionStart } from "../store/index.mjs";
3
+ //#region src/host/platform.d.ts
4
+ /**
5
+ * The runtime port: what the host needs from the platform it runs on, whichever one that is.
6
+ * Cloudflare's Workflow binding satisfies it (`cloudflareJourneyBinding`), the AWS adapter's
7
+ * `AwsInstances` implements it over durable executions.
8
+ */
9
+ export interface WorkflowInstanceLike {
10
+ id: string;
11
+ sendEvent(event: {
12
+ type: string;
13
+ payload?: unknown;
14
+ }): Promise<void>;
15
+ /** Stop the instance for good (Cloudflare Workflows' `terminate`). */
16
+ terminate?(): Promise<void>;
17
+ /** Where it stands (`complete`, `errored`, `terminated`, `running`, …). */
18
+ status?(): Promise<{
19
+ status: string;
20
+ }>;
21
+ }
22
+ /** How the host starts, wakes and stops instances. */
23
+ export interface WorkflowBindingLike {
24
+ create(options: {
25
+ id: string;
26
+ params: unknown;
27
+ }): Promise<WorkflowInstanceLike>;
28
+ /** The instance, or an `InstanceNotFoundError` when the runtime does not know the id. */
29
+ get(id: string): Promise<WorkflowInstanceLike>;
30
+ /**
31
+ * For a runtime whose start is a submit that can be lost in flight (AWS): the start to record
32
+ * with the entry, in one transaction. A failed `create` then keeps the entry — its recorded
33
+ * start is retried by the next ingest for the pair (`resume`) or by maintenance, never rolled
34
+ * back and re-entered as a second execution.
35
+ */
36
+ plan?(options: {
37
+ id: string;
38
+ params: JourneyParams;
39
+ ts: number;
40
+ /** The code version whose routes named `params.contentHash` (absent after a forced deploy). */
41
+ version?: string | undefined;
42
+ }): Promise<ExecutionStart>;
43
+ /** Retry the recorded, unconfirmed start of the (workflow, user) entry still running, if any. */
44
+ resume?(entry: {
45
+ workflow: string;
46
+ userId: string;
47
+ }): Promise<void>;
48
+ /**
49
+ * Maintenance the sweep runs first: old unconfirmed starts retried (or given up on), and
50
+ * executions the platform ended on its own (timeout, stop, crash) reconciled into the ledger.
51
+ */
52
+ maintain?(): Promise<void>;
53
+ }
54
+ /**
55
+ * The runtime does not know the instance: the only lookup failure that lets the host drop the
56
+ * instance's wakes, or count it as stopped. Every `WorkflowBindingLike.get` answers it this way.
57
+ */
58
+ export declare class InstanceNotFoundError extends Error {
59
+ readonly instanceId: string;
60
+ readonly name = "InstanceNotFoundError";
61
+ constructor(instanceId: string, options?: ErrorOptions);
62
+ }
63
+ /** The event type the host uses to wake waiting instances (sendEvent's `type`). */
64
+ export declare const WAKE_EVENT_TYPE = "wake";
65
+ /** Journey instance parameters, passed by the host when it creates one. */
66
+ export interface JourneyParams {
67
+ workflowId: string;
68
+ /** The IR version pinned at entry. */
69
+ contentHash: string;
70
+ userId: string;
71
+ trigger: {
72
+ event: string;
73
+ payload: Record<string, unknown>;
74
+ };
75
+ [key: string]: unknown;
76
+ }
77
+ /** Every binding, variable and secret the journey host reads (names match the wrangler config). */
78
+ export interface JourneyEnv {
79
+ /**
80
+ * The default D1 store's database (events / profiles / segments / triggers / entries /
81
+ * subscriptions / workflow IR). Optional: a host on another JourneyStore (Postgres, say)
82
+ * does not declare it.
83
+ */
84
+ DB?: D1DatabaseLike;
85
+ /** The runtime port: creating instances, waking and stopping them. */
86
+ JOURNEY: WorkflowBindingLike;
87
+ /** Optional message-delivery webhook (defaults to the console logging sender). */
88
+ MESSAGE_WEBHOOK_URL?: string;
89
+ /**
90
+ * Bearer token required on every mutating HTTP endpoint (`Authorization:
91
+ * Bearer <token>`). Unset = open — acceptable only for local dev; /deploy in
92
+ * particular rewrites the whole routing table, so production must set this.
93
+ */
94
+ API_TOKEN?: string;
95
+ /**
96
+ * The host's public origin. With a store that keeps reporting (Postgres), journey emails'
97
+ * links and open pixel point at its `/t/...` routes; without it emails go out untracked.
98
+ */
99
+ WORKFLOW_ORIGIN?: string;
100
+ /** Which `workflow.config.ts` entry applies (`development`, `production`, …); production when unset. */
101
+ ENVIRONMENT?: string;
102
+ /** Cloudflare Email Sending, when the config has `emails`. */
103
+ EMAIL?: EmailBindingLike;
104
+ /** The APNs auth key (`.p8`, base64) named by the config's `apns.keyId`. */
105
+ APNS_PRIVATE_KEY_BASE64?: string;
106
+ /** The Firebase service account (base64 JSON) the config's `fcm` sends with. */
107
+ GOOGLE_APPLICATION_CREDENTIALS_BASE64?: string;
108
+ /** The VAPID key pair web pushes are signed with (`generateVapidKeys`); the config's `webPush` turns the channel on. */
109
+ VAPID_PUBLIC_KEY?: string;
110
+ VAPID_PRIVATE_KEY?: string;
111
+ /**
112
+ * Cloudflare's version metadata binding (wrangler `"version_metadata": { "binding":
113
+ * "CF_VERSION_METADATA" }`). With it, and a store that records the live version (Postgres),
114
+ * journeyWorker makes the bundle compiled into each new version live by itself: `wrangler
115
+ * deploy` is the whole deploy.
116
+ */
117
+ CF_VERSION_METADATA?: {
118
+ id: string;
119
+ tag?: string;
120
+ timestamp: string;
121
+ };
122
+ /** Development only: the HTTP/2 relay `wrangler dev` sends APNs requests through (see `@shware/workflow/apns-relay`). */
123
+ APNS_RELAY_ORIGIN?: string;
124
+ }
125
+ //#endregion
126
+ //# sourceMappingURL=platform.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platform.d.mts","names":[],"sources":["../../src/host/platform.ts"],"mappings":";;;;;;;;iBASiB;EACf;EACA,UAAU;IAAS;IAAc;MAAsB;;EAEvD,cAAc;;EAEd,WAAW;IAAU;;;;iBAIN;EACf,OAAO;IAAW;IAAY;MAAoB,QAAQ;;EAE1D,IAAI,aAAa,QAAQ;;;;;;;EAOzB,MAAM;IACJ;IACA,QAAQ;IACR;;IAEA;MACE,QAAQ;;EAEZ,QAAQ;IAAS;IAAkB;MAAmB;;;;;EAKtD,aAAa;;;;;;qBAOF,8BAA8B;WAG9B;WAFO;EAClB,YACW,oBACT,UAAU;;;qBAOD;;iBAGI;EACf;;EAEA;EACA;EACA;IAAW;IAAe,SAAS;;GAClC;;;iBAIc;;;;;;EAMf,KAAK;;EAEL,SAAS;;EAET;;;;;;EAMA;;;;;EAKA;;EAEA;;EAEA,QAAQ;;EAER;;EAEA;;EAEA;EACA;;;;;;;EAOA;IAAwB;IAAY;IAAc;;;EAElD"}
@@ -0,0 +1,19 @@
1
+ //#region src/host/platform.ts
2
+ /**
3
+ * The runtime does not know the instance: the only lookup failure that lets the host drop the
4
+ * instance's wakes, or count it as stopped. Every `WorkflowBindingLike.get` answers it this way.
5
+ */
6
+ var InstanceNotFoundError = class extends Error {
7
+ instanceId;
8
+ name = "InstanceNotFoundError";
9
+ constructor(instanceId, options) {
10
+ super(`no such instance: ${instanceId}`, options);
11
+ this.instanceId = instanceId;
12
+ }
13
+ };
14
+ /** The event type the host uses to wake waiting instances (sendEvent's `type`). */
15
+ const WAKE_EVENT_TYPE = "wake";
16
+ //#endregion
17
+ export { InstanceNotFoundError, WAKE_EVENT_TYPE };
18
+
19
+ //# sourceMappingURL=platform.mjs.map